repo_id
stringlengths
5
115
size
int64
590
5.01M
file_path
stringlengths
4
212
content
stringlengths
590
5.01M
vvaltchev/tilck
1,333
kernel/arch/i386/vdso.S
# SPDX-License-Identifier: BSD-2-Clause .intel_syntax noprefix #define ASM_FILE 1 #include <tilck_gen_headers/config_mm.h> #include <tilck/kernel/arch/i386/asm_defs.h> .code32 .text .global vdso_begin .global vdso_end .align 4096 vdso_begin: .align 4 # Sysexit will jump to here when returning to usermode and will # do EXACTLY what the Linux kernel does in VDSO after sysexit. .sysexit_user_code: pop ebp pop edx pop ecx ret .align 4 # When each signal handler returns, it will jump here .post_sig_handler: mov eax, 173 # sys_rt_sigreturn_impl() int 0x80 # do the syscall .align 4 # When we cannot immediately KILL a task != current, we make it call sys_pause() # and it will be killed after the task switch, in handle_syscall(). .pause_trampoline: mov eax, 29 # sys_pause() int 0x80 .space 4096-(.-vdso_begin), 0 vdso_end: .global sysexit_user_code_user_vaddr sysexit_user_code_user_vaddr: .long USER_VDSO_VADDR + (offset .sysexit_user_code - vdso_begin) .global post_sig_handler_user_vaddr post_sig_handler_user_vaddr: .long USER_VDSO_VADDR + (offset .post_sig_handler - vdso_begin) .global pause_trampoline_user_vaddr pause_trampoline_user_vaddr: .long USER_VDSO_VADDR + (offset .pause_trampoline - vdso_begin) # Tell GNU ld to not worry about us having an executable stack .section .note.GNU-stack,"",@progbits
vvaltchev/tilck
9,829
kernel/arch/x86_64/start.S
# SPDX-License-Identifier: BSD-2-Clause .intel_syntax noprefix #define ASM_FILE 1 #include <tilck_gen_headers/config_global.h> #include <tilck_gen_headers/config_kernel.h> #include <tilck_gen_headers/config_boot.h> #include <tilck/kernel/arch/x86_64/asm_defs.h> #include <multiboot.h> .code32 .section bss .global kernel_initial_stack .comm kernel_initial_stack, ASM_KERNEL_STACK_SZ, 4096 .section .text.start .global _start #define MULTIBOOT_FLAGS (MULTIBOOT_PAGE_ALIGN | \ MULTIBOOT_MEMORY_INFO | \ MULTIBOOT_VIDEO_MODE) #define PML4 ((offset page_size_buf) - KERNEL_BASE_VA) #define PDPT0 ((offset early_pdpt0) - KERNEL_BASE_VA) #define PDPT1 ((offset early_pdpt1) - KERNEL_BASE_VA) #define PDT0 ((offset early_pdt0) - KERNEL_BASE_VA) #define FL_PRESENT (1 << 0) #define FL_RW (1 << 1) #define FL_PAGE_SIZE (1 << 7) #define MAKE_2MB_PAGE(paddr) \ (FL_PRESENT | FL_RW | FL_PAGE_SIZE | (paddr)) /* * Generic macro for making a table entry in both PDPT and PDT. * HACK: use '+' instead of '|' because the paddr is a symbol and we cannot * emit a symbol relocation that needs to be calculated with an OR operation. */ #define MAKE_ENTRY(paddr) \ (paddr + (FL_PRESENT | FL_RW)) /* Offset of an entry in the PML4 table */ #define PML4E_OFF(va) \ (8 * (((va) & 0xFF8000000000) >> 39)) /* Offset of an entry in the PDPT table */ #define PDPTE_OFF(va) \ (8 * (((va) & 0x007F80000000) >> 30)) /* Offset of an entry in the PDT table */ #define PDTE_OFF(va) \ (8 * (((va) & 0xFF80000) >> 21)) FUNC(_start): jmp multiboot_entry /* Multiboot header */ .align 4 .long MULTIBOOT_HEADER_MAGIC .long MULTIBOOT_FLAGS .long -(MULTIBOOT_HEADER_MAGIC+MULTIBOOT_FLAGS) /* checksum */ .long 0 .long 0 .long 0 .long 0 .long 0 .long 0 /* mode_type: graphic */ .long PREFERRED_GFX_MODE_W .long PREFERRED_GFX_MODE_H .long 32 /* color depth */ /* End multiboot header */ multiboot_entry: /* Clear the direction flag */ cld /* Store the multiboot information in the first two args of main() */ mov edi, eax # multiboot magic mov esi, ebx # multiboot information structure /* * Long mode is supported if: * * 1. CPUID is supported * 2. CPUID Extended Functions are available * 3. CPUID.80000001H:EDX.[29] == 1 */ /* * 1. Assume that CPUID is supported. * * 2. CPUID Extended Functions are available: * * Maximum Input Value for Extended Function CPUID Information * is given by CPUID.80000000H:EAX * (Intel Manual Vol. 2: Table 3-8) * * So if any extended function > 80000000H does not * exist then Long mode is not supported. */ mov eax, 0x80000000 cpuid cmp eax, 0x80000000 jbe no_long_mode /* * 3. CPUID.80000001H:EDX.[29] == 1: * * Bit 29: Intel(R) 64 Architecture available if 1 * (Intel Manual Vol. 2: Table 3-8) */ mov eax, 0x80000001 cpuid bt edx, 29 jnc no_long_mode /* * To switch to Long mode: * * 1. Enable Long mode (LME) * 2. Enable Physical Address Extension (PAE) * 3. Set up Paging * 4. Enable Paging (PG) * * (AMD Manual Vol. 2: Figure 1-6) */ /* * 1. Enable Long mode (LME): * * MSR IA32_EFER (C0000080H) * Bit 8: IA-32e Mode Enable: IA32_EFER.LME (R/W) * Enables IA-32e mode operation * (Intel Manual Vol. 4: Table 2-2) */ mov ecx, 0xc0000080 rdmsr bts eax, 8 wrmsr /* * 2. Enable Physical Address Extension (PAE): * * (Bit 5) CR4.PAE = 1 * (Intel Manual Vol. 3: 4.1) */ mov eax, cr4 bts eax, 5 mov cr4, eax /* * 3. Set up Paging: * * We use 4-level paging: * CR3 -> PML4T -> PDPT -> PDT -> PT * (Intel Manual Vol. 3: 4.5) * * Each table (PML4T, PDPT, PDT, PT) has * 512 entries and each entry is 8 bytes. * * Since we skip the 4 KB pages here, this is effectively: * CR3 -> PML4T -> PDPT -> PDT -> 2MB page */ // First, build a PDT (Page Directory) with the first 8 MB mapped to 0-8 MB. mov edx, PDT0 mov dword ptr [edx + PDTE_OFF(0 * MB)], MAKE_2MB_PAGE(0 * MB) mov dword ptr [edx + PDTE_OFF(2 * MB)], MAKE_2MB_PAGE(2 * MB) mov dword ptr [edx + PDTE_OFF(4 * MB)], MAKE_2MB_PAGE(4 * MB) mov dword ptr [edx + PDTE_OFF(6 * MB)], MAKE_2MB_PAGE(6 * MB) // Second, build a PDPT (Page-Directory-Pointer Table) that will map in // its first entry (0 - 1 GB) our PDT for identity mapping. We'll later // refer this PDPT in multiple entries in the PML4. mov edx, PDPT0 mov dword ptr [edx + PDPTE_OFF(0)], MAKE_ENTRY(PDT0) mov dword ptr [edx + PDPTE_OFF(BASE_VA)], MAKE_ENTRY(PDT0) // Third, build another PDPT for the kernel mappings. Reuse PDT0, since // we're still assuming that the kernel is physically mapped at +1 MB. mov edx, PDPT1 mov dword ptr [edx + PDPTE_OFF(KERNEL_BASE_VA)], MAKE_ENTRY(PDT0) // Fourth, build a PML4 referring the PDPT0 for two virtual addresses // [0 (early identity mapping) and BASE_VA] and PDPT1 at KERNEL_BASE_VA. mov edx, PML4 mov dword ptr [edx + PML4E_OFF(0)], MAKE_ENTRY(PDPT0) mov dword ptr [edx + PML4E_OFF(BASE_VA)], MAKE_ENTRY(PDPT0) mov dword ptr [edx + PML4E_OFF(KERNEL_BASE_VA)], MAKE_ENTRY(PDPT1) // Set cr3 register to the physical address of PML4 mov cr3, edx /* * 4. Enable Paging (PG): * * (Bit 31) CR0.PG = 1 * This requires protection to be enabled (CR0.PE = 1) * Since we are in protected mode, CR0.PE is * already 1. * * The values of CR4.PAE, CR4.LA57, and IA32_EFER.LME * determine which paging mode is used. * We use 4-level paging, for which the values of the * bits should be 1, 0 and 1 respectively. * (Intel Manual Vol. 3: 4.1, 4.1.1) */ mov eax, cr4 btr eax, 12 // LA57 is bit 12 mov cr4, eax mov eax, cr0 bts eax, 31 mov cr0, eax /* * We are now in Compatibility submode of Long mode. * To enter 64-bit submode of Long mode, * Set up GDT, set CS.L = 1 and jump to * 64-bit code segment. * (AMD Manual Vol. 2: Figure 1-6) */ mov eax, offset gdtr - KERNEL_BASE_VA lgdt [eax] /* * Set the Code Segment Selector * * 15-3 2 1-0 * +----+---+----+ * |SI |TI |RPL | * +----+---+----+ * * SI: Selector Index. Index of entry in the * descriptor table. 1 for CS * TI: Table Indicator. 0 for GDT, 1 for LDT * RPL: Requestor Privilege Level * * (AMD Manual Vol. 2: section 4.5.1) */ /* * We cannot directly jump to 64 bit address * because there is no jmp insruction in 32 bit that * accepts a 64 bit address. * * So instead, do a far jump to 64 bit code * segment (trampoline) running at a 32 bit * address. Then from there do a near jump * to 64 bit address. */ mov eax, offset trampoline - KERNEL_BASE_VA push 0x08 // SI=1, TI=0, RPL=00 push eax retf gdt: /* Null Descriptor */ .quad 0x0 /* * Code Segment Descriptor * * First double-word is ignored. * Second double-word: * * 31-23 22 21 20-16 15 14-13 12 11 10 9 8-0 * +--------+---+---+-------+---+------+---+---+---+---+----+ * |Ign |D |L |Ign |P |DPL |S |1 |C |R |Ign | * +--------+---+---+-------+---+------+---+---+---+--------+ * * Ign : Ignored * D : Default. In long mode, D=0 means default operand * size of 32 and default address size of 64. D=1 is reserved. * L : 64-bit flag * P : Present * DPL : Descriptor Privilege Level. 4 levels, typically only 2 are * used - 00 (highest) and 11 (lowest) * S : System flag. 1 for NON-system segment and * 0 for system segment. (Not intuitive, be careful) * C : Conforming * R : Readable * * Note: Bit 11 is 1 for code segment, and 0 * for data segment. * * (Intel Manual Vol. 3, section 5.2.1) * (AMD Manual Vol. 2, section 4.8) */ // D=0, L=1, P=1, DPL=00, S=1, Bit 11=1, C=0, R=1 .quad 0x00209A0000000000 /* * Data Segment Descriptor * * First double-word is ignored. * Second double-word: * * 31-16 15 14-13 12 11 14-0 * +------+---+------+---+---+-----+ * |Ign |P |Ign |S |0 |Ign | * +------+---+------+---+---+-----+ * * Note: There is bit 9 (W: Writable) which is * ignored but QEMU still requires it. Otherwise, * there is crash when loading ss. * * (Intel Manual Vol. 3, section 5.2.1) * (AMD Manual Vol. 2, section 4.8) */ // P=1, S=1, W=1, Bit 11=0 .quad 0x0000920000000000 gdt_end: gdtr: /* * GDTR contains 2 fields: * 1. Limit (2 bytes): size of gdt in bytes * 2. Base (8 bytes): starting byte address of gdt * in virtual memory space */ .word gdt_end - gdt - 1 // subtract 1 because limit + base // should specify the address of the // last valid byte in gdt .quad offset gdt - KERNEL_BASE_VA no_long_mode: hlt .code64 trampoline: // 0x10 is DS segment selector // SI=2, TI=0, RPL=00 mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax // Perform a near jump to 64 bit address // to enter 64 bit long mode movabs rax, offset long_mode jmp rax long_mode: cli mov rsp, offset kernel_initial_stack + ASM_KERNEL_STACK_SZ - 16 call kmain END_FUNC(_start) # Tell GNU ld to not worry about us having an executable stack .section .note.GNU-stack,"",@progbits
vvaltchev/tilck
3,274
kernel/arch/x86_64/misc.S
# SPDX-License-Identifier: BSD-2-Clause .intel_syntax noprefix #define ASM_FILE 1 #include <tilck_gen_headers/config_global.h> #include <tilck_gen_headers/config_sched.h> #include <tilck/kernel/arch/i386/asm_defs.h> #include <multiboot.h> .code64 .section .text .global asm_nop_loop .global asm_do_bogomips_loop .global asm_enable_sse .global asm_enable_osxsave .global asm_enable_avx .global __asm_fpu_cpy_single_256_nt .global __asm_fpu_cpy_single_256_nt_read # Loop used to perform short delays, used by delay_us(). It requires the # bogoMIPS measurement to be completed in order to be accurate. FUNC(asm_nop_loop): .loop: nop sub ecx, 1 jne .loop ret END_FUNC(asm_nop_loop) # Function used to measure Tilck's bogoMIPS, a "bogus" way to measure time which # stands for "millions of iterations per second". See do_bogomips_loop(). # # How it works # ---------------- # # In measure_bogomips_irq_handler() we'll going to measure the number of # iterations of the inner loop by calculating: __bogo_loops * BOGOMIPS_CONST. # Why the double loop? Because __bogo_loops needs to be atomic and atomic # operations have a significant overhead. To make it negligible, we increment # __bogo_loops by 1 only once every BOGOMIPS_CONST iterations of the inner loop. # # The loop terminates when `__bogo_loops` becomes 0 and that happens when after # MEASURE_BOGOMIPS_TICKS ticks, measure_bogomips_irq_handler() sets it to -1. # FUNC(asm_do_bogomips_loop): # Note: these NOPs are important to align the instructions in the inner loop. # Try removing them and performing the loop: on my machine, the loop count # drops by half! nop nop nop .outer_loop: mov eax, BOGOMIPS_CONST # Loop identical to asm_nop_loop(), except for the ECX -> EAX replacement .inner_loop: nop sub eax, 1 jne .inner_loop mov eax, 1 lock xadd DWORD PTR [rip+__bogo_loops], eax test eax, eax jns .outer_loop ret END_FUNC(asm_do_bogomips_loop) # This function initialize both the x87 FPU and SSE FUNC(asm_enable_sse): mov rax, cr0 and rax, ~CR0_EM # set CR0.EM = 0 [coprocessor emulation] and rax, ~CR0_TS # set CR0.TS = 0 [Task switched] or rax, CR0_MP # set CR0.MP = 1 [coprocessor monitoring] or rax, CR0_NE # set CR0.NE = 1 [Native Exception handling] mov cr0, rax fninit mov rax, cr4 or rax, CR4_OSFXSR or rax, CR4_OSXMMEXCPT mov cr4, rax ret END_FUNC(asm_enable_sse) FUNC(asm_enable_osxsave): mov rax, cr4 or rax, CR4_OSXSAVE mov cr4, rax ret END_FUNC(asm_enable_osxsave) FUNC(asm_enable_avx): xor rcx, rcx xgetbv # Load XCR0 in eax or rax, XCR0_X87 # FPU/MMX x87 enabled [must be 1] or rax, XCR0_SSE # Set SSE enabled [can be 0 if AVX is 0] or rax, XCR0_AVX # Set AVX enabled [must be 1, if SSE is 1] xsetbv # Save rax back to XCR0 ret END_FUNC(asm_enable_avx) FUNC(__asm_fpu_cpy_single_256_nt): jmp memcpy_single_256_failsafe .space 128 END_FUNC(__asm_fpu_cpy_single_256_nt) FUNC(__asm_fpu_cpy_single_256_nt_read): jmp memcpy_single_256_failsafe .space 128 END_FUNC(__asm_fpu_cpy_single_256_nt_read) # Tell GNU ld to not worry about us having an executable stack .section .note.GNU-stack,"",@progbits
vvaltchev/tilck
1,196
kernel/arch/x86_64/fault_resumable.S
# SPDX-License-Identifier: BSD-2-Clause .intel_syntax noprefix #define ASM_FILE 1 #include <tilck_gen_headers/config_global.h> #include <tilck/kernel/arch/i386/asm_defs.h> .code64 .section .text .global fault_resumable_call FUNC(fault_resumable_call): // our 1st arg (mask) -> ignored mov rax, rsi // our 2nd arg (func pointer) -> RAX // our 3rd arg (nargs) -> ignored mov rdi, rcx // our 4rd arg -> 1st arg for func (RDI) mov rsi, r8 // our 5th arg -> 2nd arg for func (RSI) mov rdx, r9 // our 6th arg -> 3rd arg for func (RDX) mov rcx, QWORD PTR [rsp+16] // our 7th arg -> 4th arg of func (RCX) mov r8, QWORD PTR [rsp+24] // our 8th arg -> 5th arg of func (R8) mov r9, QWORD PTR [rsp+32] // our 9th arg -> 6th arg of func (R9) call rax xor rax, rax // simulate no faults, return 0 ret .asm_fault_resumable_call_resume: //TODO: implement this ret END_FUNC(fault_resumable_call) # Tell GNU ld to not worry about us having an executable stack .section .note.GNU-stack,"",@progbits
VVicer/Cortex_M0_FPGA
2,197
MDK_code/startup_CMSDK_CM0.s
PRESERVE8 THUMB AREA RESET, DATA, READONLY EXPORT __Vectors __Vectors DCD 0x20000000 ; Top of Stack DCD Reset_Handler ; Reset Handler DCD 0 ; NMI Handler DCD 0 ; Hard Fault Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; SVCall Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; PendSV Handler DCD 0 ; SysTick Handler DCD 0 ; IRQ0 Handler AREA |.text|, CODE, READONLY ; Reset Handler Reset_Handler PROC GLOBAL Reset_Handler ENTRY LDR R2, =0x40000020 ;R2 GPIO OUT reg addr ADDS R3, R2, #4 ;R3 GPIO IN reg addr ADDS R4, R3, #4 ;R4 GPIO OUTen reg addr GPIO LDR R6, =0x00 ;GPIO INPUT ENABLE VALUE STR R6, [R4] ;Set input ENABLE LDR R5, [R3] ;read GPIO value LDR R6, =0x01 ;GPIO OUTPUT ENABLE VALUE STR R6, [R4] ;Set OUTPUT ENABLE LDR R6, =0X01 ;GPIO_0 Set value STR R6, [R2] ;store MOVS R1, #1 ;Interval cnt initial BL delay LDR R6, =0X03 ;GPIO_1 Set value STR R6, [R2] ;store MOVS R1, #1 ;Interval cnt initial BL delay B GPIO delay ADDS R1,R1,#1 LDR R0,=0X600000 CMP R0,R1 BNE delay BX LR ;;;;;;;;;;;;;;;;;;;;;; ENDP END
vxcc-backend/vxcc-old
1,718
tests/sum.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("int" simple ((float 0) (size 4) (align 4)))) (type ("int*" simple ((float 0) (size 8) (align 64)))) (type ("ulong" simple ((float 0) (size 8) (align 8)))) (type ("bool" simple ((float 0) (size 1) (align 1)))) (cu-block (((name "sum") (export 1)) (block ((args (("int*" 1) ("ulong" 2))) (ops (((outs (("int" 0))) (name "imm") (params (("val" (uninit)))) (args ())) ((outs (("int" 4))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("int" 3))) (name "imm") (params (("val" (var 4)))) (args ())) ((outs ()) (name "cfor") (params (("start" (block ((args ()) (ops (((outs (("ulong" 5))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 5)))) (args ())))) (rets ())))) ("cond" (block ((args ()) (ops (((outs (("bool" 7))) (name "ult") (params (("a" (var 6)) ("b" (var 2)))) (args ())))) (rets (7))))) ("endex" (block ((args ()) (ops (((outs (("ulong" 8))) (name "add") (params (("a" (var 6)) ("b" (int 1)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 8)))) (args ())))) (rets ())))) ("do" (block ((args ()) (ops (((outs (("int*" 9))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 10))) (name "add") (params (("a" (var 1)) ("b" (var 9)))) (args ())) ((outs (("int" 11))) (name "load") (params (("addr" (var 10)))) (args ())) ((outs (("int" 12))) (name "add") (params (("a" (var 11)) ("b" (var 3)))) (args ())) ((outs (("int" 3))) (name "imm") (params (("val" (var 12)))) (args ())))) (rets ())))))) (args ())) ((outs ()) (name "ret") (params ()) (args ((var 3)))))) (rets (0)))))))
vxcc-backend/vxcc-old
2,154
tests/eltwise_add.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("int*" simple ((float 0) (size 8) (align 64)))) (type ("ulong" simple ((float 0) (size 8) (align 8)))) (type ("bool" simple ((float 0) (size 1) (align 1)))) (type ("int" simple ((float 0) (size 4) (align 4)))) (cu-block (((name "eltwise_add") (export 1)) (block ((args (("int*" 1) ("int*" 2) ("int*" 3) ("ulong" 4))) (ops (((outs ()) (name "cfor") (params (("start" (block ((args ()) (ops (((outs (("ulong" 5))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 5)))) (args ())))) (rets ())))) ("cond" (block ((args ()) (ops (((outs (("bool" 7))) (name "ult") (params (("a" (var 6)) ("b" (var 4)))) (args ())))) (rets (7))))) ("endex" (block ((args ()) (ops (((outs (("ulong" 8))) (name "add") (params (("a" (var 6)) ("b" (int 1)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 8)))) (args ())))) (rets ())))) ("do" (block ((args ()) (ops (((outs (("int*" 9))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 10))) (name "add") (params (("a" (var 1)) ("b" (var 9)))) (args ())) ((outs (("int" 11))) (name "load") (params (("addr" (var 10)))) (args ())) ((outs (("int*" 12))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 13))) (name "add") (params (("a" (var 2)) ("b" (var 12)))) (args ())) ((outs (("int" 14))) (name "load") (params (("addr" (var 13)))) (args ())) ((outs (("int*" 15))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 16))) (name "add") (params (("a" (var 3)) ("b" (var 15)))) (args ())) ((outs (("int" 17))) (name "load") (params (("addr" (var 16)))) (args ())) ((outs (("int" 18))) (name "add") (params (("a" (var 17)) ("b" (var 14)))) (args ())) ((outs (("int*" 19))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 20))) (name "add") (params (("a" (var 1)) ("b" (var 19)))) (args ())) ((outs ()) (name "store") (params (("addr" (var 20)) ("val" (var 18)))) (args ())))) (rets ())))))) (args ())))) (rets ()))))))
vxcc-backend/vxcc-old
2,126
tests/strcpy.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("char*" simple ((float 0) (size 8) (align 64)))) (type ("ulong" simple ((float 0) (size 8) (align 8)))) (type ("bool" simple ((float 0) (size 1) (align 1)))) (type ("char" simple ((float 0) (size 1) (align 1)))) (cu-block (((name "strcpy") (export 1)) (block ((args (("char*" 1) ("char*" 2))) (ops (((outs ()) (name "cfor") (params (("start" (block ((args ()) (ops (((outs (("ulong" 3))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("ulong" 4))) (name "imm") (params (("val" (var 3)))) (args ())))) (rets ())))) ("cond" (block ((args ()) (ops (((outs (("char*" 5))) (name "mul") (params (("a" (var 4)) ("b" (int 1)))) (args ())) ((outs (("char*" 6))) (name "add") (params (("a" (var 2)) ("b" (var 5)))) (args ())) ((outs (("char" 7))) (name "load") (params (("addr" (var 6)))) (args ())) ((outs (("char" 8))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("bool" 9))) (name "neq") (params (("a" (var 8)) ("b" (var 7)))) (args ())))) (rets (9))))) ("endex" (block ((args ()) (ops (((outs (("ulong" 10))) (name "add") (params (("a" (var 4)) ("b" (int 1)))) (args ())) ((outs (("ulong" 4))) (name "imm") (params (("val" (var 10)))) (args ())))) (rets ())))) ("do" (block ((args ()) (ops (((outs (("char*" 11))) (name "mul") (params (("a" (var 4)) ("b" (int 1)))) (args ())) ((outs (("char*" 12))) (name "add") (params (("a" (var 1)) ("b" (var 11)))) (args ())) ((outs (("char" 13))) (name "load") (params (("addr" (var 12)))) (args ())) ((outs (("char*" 14))) (name "mul") (params (("a" (var 4)) ("b" (int 1)))) (args ())) ((outs (("char*" 15))) (name "add") (params (("a" (var 2)) ("b" (var 14)))) (args ())) ((outs (("char" 16))) (name "load") (params (("addr" (var 15)))) (args ())) ((outs (("char*" 17))) (name "mul") (params (("a" (var 4)) ("b" (int 1)))) (args ())) ((outs (("char*" 18))) (name "add") (params (("a" (var 1)) ("b" (var 17)))) (args ())) ((outs ()) (name "store") (params (("addr" (var 18)) ("val" (var 16)))) (args ())))) (rets ())))))) (args ())))) (rets ()))))))
vxcc-backend/vxcc-old
2,013
tests/addfirst4.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("int" simple ((float 0) (size 4) (align 4)))) (type ("int*" simple ((float 0) (size 8) (align 64)))) (type ("long" simple ((float 0) (size 8) (align 8)))) (cu-block (((name "addfirst4") (export 1)) (block ((args (("int*" 1))) (ops (((outs (("int" 0))) (name "imm") (params (("val" (uninit)))) (args ())) ((outs (("long" 2))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("int*" 3))) (name "mul") (params (("a" (var 2)) ("b" (int 4)))) (args ())) ((outs (("int*" 4))) (name "add") (params (("a" (var 1)) ("b" (var 3)))) (args ())) ((outs (("int" 5))) (name "load") (params (("addr" (var 4)))) (args ())) ((outs (("long" 6))) (name "imm") (params (("val" (int 1)))) (args ())) ((outs (("int*" 7))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 8))) (name "add") (params (("a" (var 1)) ("b" (var 7)))) (args ())) ((outs (("int" 9))) (name "load") (params (("addr" (var 8)))) (args ())) ((outs (("int" 10))) (name "add") (params (("a" (var 9)) ("b" (var 5)))) (args ())) ((outs (("long" 11))) (name "imm") (params (("val" (int 2)))) (args ())) ((outs (("int*" 12))) (name "mul") (params (("a" (var 11)) ("b" (int 4)))) (args ())) ((outs (("int*" 13))) (name "add") (params (("a" (var 1)) ("b" (var 12)))) (args ())) ((outs (("int" 14))) (name "load") (params (("addr" (var 13)))) (args ())) ((outs (("int" 15))) (name "add") (params (("a" (var 14)) ("b" (var 10)))) (args ())) ((outs (("long" 16))) (name "imm") (params (("val" (int 3)))) (args ())) ((outs (("int*" 17))) (name "mul") (params (("a" (var 16)) ("b" (int 4)))) (args ())) ((outs (("int*" 18))) (name "add") (params (("a" (var 1)) ("b" (var 17)))) (args ())) ((outs (("int" 19))) (name "load") (params (("addr" (var 18)))) (args ())) ((outs (("int" 20))) (name "add") (params (("a" (var 19)) ("b" (var 15)))) (args ())) ((outs ()) (name "ret") (params ()) (args ((var 20)))))) (rets (0)))))))
vxcc-backend/vxcc-old
2,941
tests/coltwise_reduce_sum.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("int*" simple ((float 0) (size 8) (align 64)))) (type ("ulong" simple ((float 0) (size 8) (align 8)))) (type ("bool" simple ((float 0) (size 1) (align 1)))) (type ("int" simple ((float 0) (size 4) (align 4)))) (cu-block (((name "colwise_reduce_sum") (export 1)) (block ((args (("int*" 1) ("int*" 2) ("ulong" 3) ("ulong" 4))) (ops (((outs ()) (name "cfor") (params (("start" (block ((args ()) (ops (((outs (("ulong" 5))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 5)))) (args ())))) (rets ())))) ("cond" (block ((args ()) (ops (((outs (("bool" 7))) (name "ult") (params (("a" (var 6)) ("b" (var 3)))) (args ())))) (rets (7))))) ("endex" (block ((args ()) (ops (((outs (("ulong" 8))) (name "add") (params (("a" (var 6)) ("b" (int 1)))) (args ())) ((outs (("ulong" 6))) (name "imm") (params (("val" (var 8)))) (args ())))) (rets ())))) ("do" (block ((args ()) (ops (((outs (("int" 10))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("int" 9))) (name "imm") (params (("val" (var 10)))) (args ())) ((outs ()) (name "cfor") (params (("start" (block ((args ()) (ops (((outs (("ulong" 11))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("ulong" 12))) (name "imm") (params (("val" (var 11)))) (args ())))) (rets ())))) ("cond" (block ((args ()) (ops (((outs (("bool" 13))) (name "ult") (params (("a" (var 12)) ("b" (var 4)))) (args ())))) (rets (13))))) ("endex" (block ((args ()) (ops (((outs (("ulong" 14))) (name "add") (params (("a" (var 12)) ("b" (int 1)))) (args ())) ((outs (("ulong" 12))) (name "imm") (params (("val" (var 14)))) (args ())))) (rets ())))) ("do" (block ((args ()) (ops (((outs (("ulong" 15))) (name "mul") (params (("a" (var 3)) ("b" (var 6)))) (args ())) ((outs (("ulong" 16))) (name "add") (params (("a" (var 12)) ("b" (var 15)))) (args ())) ((outs (("int*" 17))) (name "mul") (params (("a" (var 16)) ("b" (int 4)))) (args ())) ((outs (("int*" 18))) (name "add") (params (("a" (var 2)) ("b" (var 17)))) (args ())) ((outs (("int" 19))) (name "load") (params (("addr" (var 18)))) (args ())) ((outs (("int" 20))) (name "add") (params (("a" (var 19)) ("b" (var 9)))) (args ())) ((outs (("int" 9))) (name "imm") (params (("val" (var 20)))) (args ())))) (rets ())))))) (args ())) ((outs (("int*" 21))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 22))) (name "add") (params (("a" (var 1)) ("b" (var 21)))) (args ())) ((outs (("int" 23))) (name "load") (params (("addr" (var 22)))) (args ())) ((outs (("int*" 24))) (name "mul") (params (("a" (var 6)) ("b" (int 4)))) (args ())) ((outs (("int*" 25))) (name "add") (params (("a" (var 1)) ("b" (var 24)))) (args ())) ((outs ()) (name "store") (params (("addr" (var 25)) ("val" (var 9)))) (args ())))) (rets ())))))) (args ())))) (rets ()))))))
vxcc-backend/vxcc-old
1,920
tests/assignments.c3.s
("amd64:cmov" (opt ((max_total_cmov_inline_cost 4) (consteval_iterations 6) (loop_simplify 1) (if_eval 1))) (type ("int" simple ((float 0) (size 4) (align 4)))) (cu-block (((name "assignments") (export 1)) (block ((args (("int" 1))) (ops (((outs (("int" 0))) (name "imm") (params (("val" (uninit)))) (args ())) ((outs (("int" 3))) (name "imm") (params (("val" (int 0)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 3)))) (args ())) ((outs (("int" 4))) (name "add") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 4)))) (args ())) ((outs (("int" 5))) (name "sub") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 5)))) (args ())) ((outs (("int" 6))) (name "smod") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 6)))) (args ())) ((outs (("int" 7))) (name "sdiv") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 7)))) (args ())) ((outs (("int" 8))) (name "mul") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 8)))) (args ())) ((outs (("int" 9))) (name "shl") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 9)))) (args ())) ((outs (("int" 10))) (name "ashr") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 10)))) (args ())) ((outs (("int" 11))) (name "or") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 11)))) (args ())) ((outs (("int" 12))) (name "bwand") (params (("a" (var 1)) ("b" (var 2)))) (args ())) ((outs (("int" 2))) (name "imm") (params (("val" (var 12)))) (args ())) ((outs ()) (name "ret") (params ()) (args ((var 2)))))) (rets (0)))))))
w296488320/JnitraceForCpp
1,077
nativeLib/src/main/cpp/hook/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/dummy/closure-trampoline-template-arm.S
// .section __TEXT,__text,regular,pure_instructions #if defined(ENABLE_CLOSURE_BRIDGE_TEMPLATE) #if defined(__WIN32__) || defined(__APPLE__) #define cdecl(s) _##s #else #define cdecl(s) s #endif .align 4 #if !defined(ENABLE_CLOSURE_TRAMPOLINE_CARRY_OBJECT_PTR) // closure trampoline carray the object pointer, and fetch required members at the runtime assembly code. // #include "TrampolineBridge/ClosureTrampolineBridge/ClosureTrampoline.h" // #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) #define OFFSETOF_ClourseTrampolineEntry_carry_data 4 #define OFFSETOF_ClourseTrampolineEntry_carry_handler 0 .globl cdecl(closure_trampoline_template) cdecl(closure_trampoline_template): ldr r12, ClourseTrampolineEntryPtr ldr pc, [r12, #0] ClourseTrampolineEntryPtr: .long 0 #else ; closure trampoline just carray the required members from the object. .globl cdecl(closure_trampoline_template) cdecl(closure_trampoline_template): ldr r12, =carry_data ldr pc, =carry_handler carry_data: .long 0 carry_handler: .long 0 #endif #endif
w296488320/JnitraceForCpp
1,230
nativeLib/src/main/cpp/hook/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/dummy/closure-trampoline-template-arm64.S
// .section __TEXT,__text,regular,pure_instructions #if defined(ENABLE_CLOSURE_BRIDGE_TEMPLATE) #if defined(__WIN32__) || defined(__APPLE__) #define cdecl(s) _##s #else #define cdecl(s) s #endif .align 4 #if !defined(ENABLE_CLOSURE_TRAMPOLINE_CARRY_OBJECT_PTR) // closure trampoline carray the object pointer, and fetch required members at the runtime assembly code. // #include "TrampolineBridge/ClosureTrampolineBridge/ClosureTrampoline.h" // #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) #define OFFSETOF_ClourseTrampolineEntry_carry_data 8 #define OFFSETOF_ClourseTrampolineEntry_carry_handler 0 .globl cdecl(closure_trampoline_template) cdecl(closure_trampoline_template): ldr x17, ClourseTrampolineEntryPtr ldr x16, OFFSETOF_ClourseTrampolineEntry_carry_data ldr x17, OFFSETOF_ClourseTrampolineEntry_carry_handler br x17 ClourseTrampolineEntryPtr: .long 0 .long 0 #else ; closure trampoline just carray the required members from the object. .globl cdecl(closure_trampoline_template) cdecl(closure_trampoline_template): ldr x16, =carry_data ldr x17, =carry_handler br x17 carry_data: .long 0 .long 0 carry_handler: .long 0 .long 0 #endif #endif
w296488320/JnitraceForCpp
15,273
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/breakpad_getcontext.S
// Copyright (c) 2012, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A minimalistic implementation of getcontext() to be used by // Google Breakpad on Android. #include "ucontext_constants.h" /* int getcontext (ucontext_t *ucp) */ #if defined(__arm__) .text .global getcontext //.hidden getcontext .type getcontext, #function .align 0 .fnstart getcontext: /* First, save r4-r11 */ add r1, r0, #(MCONTEXT_GREGS_OFFSET + 4*4) stm r1, {r4-r11} /* r12 is a scratch register, don't save it */ /* Save sp and lr explicitly. */ /* - sp can't be stored with stmia in Thumb-2 */ /* - STM instructions that store sp and pc are deprecated in ARM */ str sp, [r0, #(MCONTEXT_GREGS_OFFSET + 13*4)] str lr, [r0, #(MCONTEXT_GREGS_OFFSET + 14*4)] /* Save the caller's address in 'pc' */ str lr, [r0, #(MCONTEXT_GREGS_OFFSET + 15*4)] /* Save ucontext_t* pointer across next call */ mov r4, r0 /* Call sigprocmask(SIG_BLOCK, NULL, &(ucontext->uc_sigmask)) */ mov r0, #0 /* SIG_BLOCK */ mov r1, #0 /* NULL */ add r2, r4, #UCONTEXT_SIGMASK_OFFSET bl sigprocmask(PLT) /* Intentionally do not save the FPU state here. This is because on * Linux/ARM, one should instead use ptrace(PTRACE_GETFPREGS) or * ptrace(PTRACE_GETVFPREGS) to get it. * * Note that a real implementation of getcontext() would need to save * this here to allow setcontext()/swapcontext() to work correctly. */ /* Restore the values of r4 and lr */ mov r0, r4 ldr lr, [r0, #(MCONTEXT_GREGS_OFFSET + 14*4)] ldr r4, [r0, #(MCONTEXT_GREGS_OFFSET + 4*4)] /* Return 0 */ mov r0, #0 bx lr .fnend .size getcontext, . - getcontext #elif defined(__aarch64__) #define _NSIG 64 #define __NR_rt_sigprocmask 135 .text .global getcontext //.hidden getcontext .type getcontext, #function .align 4 .cfi_startproc getcontext: /* The saved context will return to the getcontext() call point with a return value of 0 */ str xzr, [x0, MCONTEXT_GREGS_OFFSET + 0 * REGISTER_SIZE] stp x18, x19, [x0, MCONTEXT_GREGS_OFFSET + 18 * REGISTER_SIZE] stp x20, x21, [x0, MCONTEXT_GREGS_OFFSET + 20 * REGISTER_SIZE] stp x22, x23, [x0, MCONTEXT_GREGS_OFFSET + 22 * REGISTER_SIZE] stp x24, x25, [x0, MCONTEXT_GREGS_OFFSET + 24 * REGISTER_SIZE] stp x26, x27, [x0, MCONTEXT_GREGS_OFFSET + 26 * REGISTER_SIZE] stp x28, x29, [x0, MCONTEXT_GREGS_OFFSET + 28 * REGISTER_SIZE] str x30, [x0, MCONTEXT_GREGS_OFFSET + 30 * REGISTER_SIZE] /* Place LR into the saved PC, this will ensure that when switching to this saved context with setcontext() control will pass back to the caller of getcontext(), we have already arranged to return the appropriate return value in x0 above. */ str x30, [x0, MCONTEXT_PC_OFFSET] /* Save the current SP */ mov x2, sp str x2, [x0, MCONTEXT_SP_OFFSET] /* Initialize the pstate. */ str xzr, [x0, MCONTEXT_PSTATE_OFFSET] /* Figure out where to place the first context extension block. */ add x2, x0, #MCONTEXT_EXTENSION_OFFSET /* Write the context extension fpsimd header. */ mov w3, #(FPSIMD_MAGIC & 0xffff) movk w3, #(FPSIMD_MAGIC >> 16), lsl #16 str w3, [x2, #FPSIMD_CONTEXT_MAGIC_OFFSET] mov w3, #FPSIMD_CONTEXT_SIZE str w3, [x2, #FPSIMD_CONTEXT_SIZE_OFFSET] /* Fill in the FP SIMD context. */ add x3, x2, #(FPSIMD_CONTEXT_VREGS_OFFSET + 8 * SIMD_REGISTER_SIZE) stp d8, d9, [x3], #(2 * SIMD_REGISTER_SIZE) stp d10, d11, [x3], #(2 * SIMD_REGISTER_SIZE) stp d12, d13, [x3], #(2 * SIMD_REGISTER_SIZE) stp d14, d15, [x3], #(2 * SIMD_REGISTER_SIZE) add x3, x2, FPSIMD_CONTEXT_FPSR_OFFSET mrs x4, fpsr str w4, [x3] mrs x4, fpcr str w4, [x3, FPSIMD_CONTEXT_FPCR_OFFSET - FPSIMD_CONTEXT_FPSR_OFFSET] /* Write the termination context extension header. */ add x2, x2, #FPSIMD_CONTEXT_SIZE str xzr, [x2, #FPSIMD_CONTEXT_MAGIC_OFFSET] str xzr, [x2, #FPSIMD_CONTEXT_SIZE_OFFSET] /* Grab the signal mask */ /* rt_sigprocmask (SIG_BLOCK, NULL, &ucp->uc_sigmask, _NSIG8) */ add x2, x0, #UCONTEXT_SIGMASK_OFFSET mov x0, #0 /* SIG_BLOCK */ mov x1, #0 /* NULL */ mov x3, #(_NSIG / 8) mov x8, #__NR_rt_sigprocmask svc 0 /* Return x0 for success */ mov x0, 0 ret .cfi_endproc .size getcontext, . - getcontext #elif defined(__i386__) .text .global getcontext //.hidden getcontext .align 4 .type getcontext, @function getcontext: movl 4(%esp), %eax /* eax = uc */ /* Save register values */ movl %ecx, MCONTEXT_ECX_OFFSET(%eax) movl %edx, MCONTEXT_EDX_OFFSET(%eax) movl %ebx, MCONTEXT_EBX_OFFSET(%eax) movl %edi, MCONTEXT_EDI_OFFSET(%eax) movl %esi, MCONTEXT_ESI_OFFSET(%eax) movl %ebp, MCONTEXT_EBP_OFFSET(%eax) movl (%esp), %edx /* return address */ lea 4(%esp), %ecx /* exclude return address from stack */ mov %edx, MCONTEXT_EIP_OFFSET(%eax) mov %ecx, MCONTEXT_ESP_OFFSET(%eax) xorl %ecx, %ecx movw %kernel.fs, %cx mov %ecx, MCONTEXT_FS_OFFSET(%eax) movl $0, MCONTEXT_EAX_OFFSET(%eax) /* Save floating point state to fpregstate, then update * the fpregs pointer to point to it */ leal UCONTEXT_FPREGS_MEM_OFFSET(%eax), %ecx fnstenv (%ecx) fldenv (%ecx) mov %ecx, UCONTEXT_FPREGS_OFFSET(%eax) /* Save signal mask: sigprocmask(SIGBLOCK, NULL, &uc->uc_sigmask) */ leal UCONTEXT_SIGMASK_OFFSET(%eax), %edx xorl %ecx, %ecx push %edx /* &uc->uc_sigmask */ push %ecx /* NULL */ push %ecx /* SIGBLOCK == 0 on i386 */ call sigprocmask@PLT addl $12, %esp movl $0, %eax ret .size getcontext, . - getcontext #elif defined(__mips__) // This implementation is inspired by implementation of getcontext in glibc. #include <asm-mips/asm.h> #include <asm-mips/regdef.h> #if _MIPS_SIM == _ABIO32 #include <asm-mips/fpregdef.h> #endif // from asm-mips/asm.h #if _MIPS_SIM == _ABIO32 #define ALSZ 7 #define ALMASK ~7 #define SZREG 4 #else // _MIPS_SIM != _ABIO32 #define ALSZ 15 #define ALMASK ~15 #define SZREG 8 #endif #include <asm/unistd.h> // for __NR_rt_sigprocmask #define _NSIG8 128 / 8 #define SIG_BLOCK 1 .text LOCALS_NUM = 1 // save gp on stack FRAME_SIZE = ((LOCALS_NUM * SZREG) + ALSZ) & ALMASK GP_FRAME_OFFSET = FRAME_SIZE - (1 * SZREG) MCONTEXT_REG_SIZE = 8 #if _MIPS_SIM == _ABIO32 NESTED (getcontext, FRAME_SIZE, ra) .mask 0x00000000, 0 .fmask 0x00000000, 0 .set noreorder .cpload t9 .set reorder move a2, sp #define _SP a2 addiu sp, -FRAME_SIZE .cprestore GP_FRAME_OFFSET sw s0, (16 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s1, (17 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s2, (18 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s3, (19 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s4, (20 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s5, (21 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s6, (22 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw s7, (23 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw _SP, (29 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw fp, (30 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw ra, (31 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sw ra, MCONTEXT_PC_OFFSET(a0) #ifdef __mips_hard_float s.d fs0, (20 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d fs1, (22 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d fs2, (24 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d fs3, (26 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d fs4, (28 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d fs5, (30 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) cfc1 v1, fcr31 sw v1, MCONTEXT_FPC_CSR(a0) #endif // __mips_hard_float /* rt_sigprocmask (SIG_BLOCK, NULL, &ucp->uc_sigmask, _NSIG8) */ li a3, _NSIG8 addu a2, a0, UCONTEXT_SIGMASK_OFFSET move a1, zero li a0, SIG_BLOCK li v0, __NR_rt_sigprocmask syscall addiu sp, FRAME_SIZE jr ra END (getcontext) #else #ifndef NESTED /* * NESTED - declare nested routine entry point */ #define NESTED(symbol, framesize, rpc) \ .globl symbol; \ .align 2; \ .type symbol,@function; \ .ent symbol,0; \ symbol: .frame sp, framesize, rpc; #endif /* * END - mark end of function */ #ifndef END # define END(function) \ .end function; \ .size function,.-function #endif /* int getcontext (ucontext_t *ucp) */ NESTED (getcontext, FRAME_SIZE, ra) .mask 0x10000000, 0 .fmask 0x00000000, 0 move a2, sp #define _SP a2 move a3, gp #define _GP a3 daddiu sp, -FRAME_SIZE .cpsetup $25, GP_FRAME_OFFSET, getcontext /* Store a magic flag. */ li v1, 1 sd v1, (0 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) /* zero */ sd s0, (16 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s1, (17 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s2, (18 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s3, (19 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s4, (20 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s5, (21 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s6, (22 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s7, (23 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd _GP, (28 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd _SP, (29 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd s8, (30 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd ra, (31 * MCONTEXT_REG_SIZE + MCONTEXT_GREGS_OFFSET)(a0) sd ra, MCONTEXT_PC_OFFSET(a0) #ifdef __mips_hard_float s.d $f24, (24 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f25, (25 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f26, (26 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f27, (27 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f28, (28 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f29, (29 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f30, (30 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) s.d $f31, (31 * MCONTEXT_REG_SIZE + MCONTEXT_FPREGS_OFFSET)(a0) cfc1 v1, $31 sw v1, MCONTEXT_FPC_CSR(a0) #endif /* __mips_hard_float */ /* rt_sigprocmask (SIG_BLOCK, NULL, &ucp->uc_sigmask, _NSIG8) */ li a3, _NSIG8 daddu a2, a0, UCONTEXT_SIGMASK_OFFSET move a1, zero li a0, SIG_BLOCK li v0, __NR_rt_sigprocmask syscall .cpreturn daddiu sp, FRAME_SIZE move v0, zero jr ra END (getcontext) #endif // _MIPS_SIM == _ABIO32 #elif defined(__x86_64__) /* The x64 implementation of getcontext was derived in part from the implementation of libunwind which requires the following notice. */ /* libunwind - a platform-independent unwind library Copyright (C) 2008 Google, Inc Contributed by Paul Pluzhnikov <ppluzhnikov@google.com> Copyright (C) 2010 Konstantin Belousov <kib@freebsd.org> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .text .global getcontext //.hidden getcontext .align 4 .type getcontext, @function getcontext: .cfi_startproc /* Callee saved: RBX, RBP, R12-R15 */ movq %r12, MCONTEXT_GREGS_R12(%rdi) movq %r13, MCONTEXT_GREGS_R13(%rdi) movq %r14, MCONTEXT_GREGS_R14(%rdi) movq %r15, MCONTEXT_GREGS_R15(%rdi) movq %rbp, MCONTEXT_GREGS_RBP(%rdi) movq %rbx, MCONTEXT_GREGS_RBX(%rdi) /* Save argument registers (not strictly needed, but setcontext restores them, so don't restore garbage). */ movq %r8, MCONTEXT_GREGS_R8(%rdi) movq %r9, MCONTEXT_GREGS_R9(%rdi) movq %rdi, MCONTEXT_GREGS_RDI(%rdi) movq %rsi, MCONTEXT_GREGS_RSI(%rdi) movq %rdx, MCONTEXT_GREGS_RDX(%rdi) movq %rax, MCONTEXT_GREGS_RAX(%rdi) movq %rcx, MCONTEXT_GREGS_RCX(%rdi) /* Save fp state (not needed, except for setcontext not restoring garbage). */ leaq MCONTEXT_FPREGS_MEM(%rdi),%r8 movq %r8, MCONTEXT_FPREGS_PTR(%rdi) fnstenv (%r8) stmxcsr FPREGS_OFFSET_MXCSR(%r8) leaq 8(%rsp), %rax /* exclude this call. */ movq %rax, MCONTEXT_GREGS_RSP(%rdi) movq 0(%rsp), %rax movq %rax, MCONTEXT_GREGS_RIP(%rdi) /* Save signal mask: sigprocmask(SIGBLOCK, NULL, &uc->uc_sigmask) */ leaq UCONTEXT_SIGMASK_OFFSET(%rdi), %rdx // arg3 xorq %rsi, %rsi // arg2 NULL xorq %rdi, %rdi // arg1 SIGBLOCK == 0 call sigprocmask@PLT /* Always return 0 for success, even if sigprocmask failed. */ xorl %eax, %eax ret .cfi_endproc .size getcontext, . - getcontext #else #error "This file has not been ported for your CPU!" #endif
w296488320/JnitraceForCpp
3,802
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/aarch64/setcontext.S
/* Set current context. Copyright (C) 2009-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" #include "ucontext_i.h" #include "ucontext-internal.h" /* int __setcontext (const ucontext_t *ucp) Restores the machine context in UCP and thereby resumes execution in that context. This implementation is intended to be used for *synchronous* context switches only. Therefore, it does not have to restore anything other than the PRESERVED state. */ .text ENTRY (__setcontext) /* Save a copy of UCP. */ # mov x9, x0 /* Set the signal mask with rt_sigprocmask (SIG_SETMASK, mask, NULL, _NSIG/8). */ # mov x0, #SIG_SETMASK # add x1, x9, #UCONTEXT_SIGMASK # mov x2, #0 # mov x3, #_NSIG8 # mov x8, SYS_ify (rt_sigprocmask) # svc 0 # cbz x0, 1f # b C_SYMBOL_NAME (__syscall_error) #1: /* Restore the general purpose registers. */ # mov x0, x9 cfi_def_cfa (x0, 0) cfi_offset (x18, oX0 + 18 * SZREG) cfi_offset (x19, oX0 + 19 * SZREG) cfi_offset (x20, oX0 + 20 * SZREG) cfi_offset (x21, oX0 + 21 * SZREG) cfi_offset (x22, oX0 + 22 * SZREG) cfi_offset (x23, oX0 + 23 * SZREG) cfi_offset (x24, oX0 + 24 * SZREG) cfi_offset (x25, oX0 + 25 * SZREG) cfi_offset (x26, oX0 + 26 * SZREG) cfi_offset (x27, oX0 + 27 * SZREG) cfi_offset (x28, oX0 + 28 * SZREG) cfi_offset (x29, oX0 + 29 * SZREG) cfi_offset (x30, oX0 + 30 * SZREG) cfi_offset ( d8, oV0 + 8 * SZVREG) cfi_offset ( d9, oV0 + 9 * SZVREG) cfi_offset (d10, oV0 + 10 * SZVREG) cfi_offset (d11, oV0 + 11 * SZVREG) cfi_offset (d12, oV0 + 12 * SZVREG) cfi_offset (d13, oV0 + 13 * SZVREG) cfi_offset (d14, oV0 + 14 * SZVREG) cfi_offset (d15, oV0 + 15 * SZVREG) ldp x18, x19, [x0, oX0 + 18 * SZREG] ldp x20, x21, [x0, oX0 + 20 * SZREG] ldp x22, x23, [x0, oX0 + 22 * SZREG] ldp x24, x25, [x0, oX0 + 24 * SZREG] ldp x26, x27, [x0, oX0 + 26 * SZREG] ldp x28, x29, [x0, oX0 + 28 * SZREG] ldr x30, [x0, oX0 + 30 * SZREG] ldr x2, [x0, oSP] mov sp, x2 /* Check for FP SIMD context. We don't support restoring contexts created by the kernel, so this context must have been created by getcontext. Hence we can rely on the first extension block being the FP SIMD context. */ add x2, x0, #oEXTENSION mov w3, #(FPSIMD_MAGIC & 0xffff) movk w3, #(FPSIMD_MAGIC >> 16), lsl #16 ldr w1, [x2, #oHEAD + oMAGIC] cmp w1, w3 b.ne 2f /* Restore the FP SIMD context. */ add x3, x2, #oV0 + 8 * SZVREG ldp d8, d9, [x3], #2 * SZVREG ldp d10, d11, [x3], #2 * SZVREG ldp d12, d13, [x3], #2 * SZVREG ldp d14, d15, [x3], #2 * SZVREG add x3, x2, oFPSR ldr w4, [x3] msr fpsr, x4 ldr w4, [x3, oFPCR - oFPSR] msr fpcr, x4 2: ldr x16, [x0, oPC] /* Restore arg registers. */ ldp x2, x3, [x0, oX0 + 2 * SZREG] ldp x4, x5, [x0, oX0 + 4 * SZREG] ldp x6, x7, [x0, oX0 + 6 * SZREG] ldp x0, x1, [x0, oX0 + 0 * SZREG] /* Jump to the new pc value. */ br x16 PSEUDO_END (__setcontext) weak_alias (__setcontext, setcontext) ENTRY (__startcontext) mov x0, x19 cbnz x0, __setcontext 1: b HIDDEN_JUMPTARGET (_exit) END (__startcontext)
w296488320/JnitraceForCpp
2,961
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/aarch64/getcontext.S
/* Save current context. Copyright (C) 2009-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" #include "ucontext_i.h" #include "ucontext-internal.h" /* int getcontext (ucontext_t *ucp) Returns 0 on success -1 and errno on failure. */ .text ENTRY(__getcontext) /* The saved context will return to the getcontext() call point with a return value of 0 */ str xzr, [x0, oX0 + 0 * SZREG] stp x18, x19, [x0, oX0 + 18 * SZREG] stp x20, x21, [x0, oX0 + 20 * SZREG] stp x22, x23, [x0, oX0 + 22 * SZREG] stp x24, x25, [x0, oX0 + 24 * SZREG] stp x26, x27, [x0, oX0 + 26 * SZREG] stp x28, x29, [x0, oX0 + 28 * SZREG] str x30, [x0, oX0 + 30 * SZREG] /* Place LR into the saved PC, this will ensure that when switching to this saved context with setcontext() control will pass back to the caller of getcontext(), we have already arrange to return the appropriate return value in x0 above. */ str x30, [x0, oPC] /* Save the current SP */ mov x2, sp str x2, [x0, oSP] /* Initialize the pstate. */ str xzr, [x0, oPSTATE] /* Figure out where to place the first context extension block. */ add x2, x0, #oEXTENSION /* Write the context extension fpsimd header. */ mov w3, #(FPSIMD_MAGIC & 0xffff) movk w3, #(FPSIMD_MAGIC >> 16), lsl #16 str w3, [x2, #oHEAD + oMAGIC] mov w3, #FPSIMD_CONTEXT_SIZE str w3, [x2, #oHEAD + oSIZE] /* Fill in the FP SIMD context. */ add x3, x2, #oV0 + 8 * SZVREG stp d8, d9, [x3], # 2 * SZVREG stp d10, d11, [x3], # 2 * SZVREG stp d12, d13, [x3], # 2 * SZVREG stp d14, d15, [x3], # 2 * SZVREG add x3, x2, oFPSR mrs x4, fpsr str w4, [x3] mrs x4, fpcr str w4, [x3, oFPCR - oFPSR] /* Write the termination context extension header. */ add x2, x2, #FPSIMD_CONTEXT_SIZE str xzr, [x2, #oHEAD + oMAGIC] str xzr, [x2, #oHEAD + oSIZE] /* Grab the signal mask */ /* rt_sigprocmask (SIG_BLOCK, NULL, &ucp->uc_sigmask, _NSIG8) */ add x2, x0, #UCONTEXT_SIGMASK mov x0, SIG_BLOCK mov x1, 0 mov x3, _NSIG8 mov x8, SYS_ify (rt_sigprocmask) svc 0 cbnz x0, 1f /* Return 0 for success */ mov x0, 0 RET 1: b C_SYMBOL_NAME(__syscall_error) PSEUDO_END (__getcontext) weak_alias (__getcontext, getcontext)
w296488320/JnitraceForCpp
2,766
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/aarch64/swapcontext.S
/* Modify saved context. Copyright (C) 2009-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" #include "ucontext_i.h" #include "ucontext-internal.h" /* int swapcontext (ucontext_t *oucp, const ucontext_t *ucp) */ .text ENTRY(__swapcontext) /* Set the value returned when swapcontext() returns in this context. */ str xzr, [x0, oX0 + 0 * SZREG] stp x18, x19, [x0, oX0 + 18 * SZREG] stp x20, x21, [x0, oX0 + 20 * SZREG] stp x22, x23, [x0, oX0 + 22 * SZREG] stp x24, x25, [x0, oX0 + 24 * SZREG] stp x26, x27, [x0, oX0 + 26 * SZREG] stp x28, x29, [x0, oX0 + 28 * SZREG] str x30, [x0, oX0 + 30 * SZREG] str x30, [x0, oPC] mov x2, sp str x2, [x0, oSP] /* Figure out where to place the first context extension block. */ add x2, x0, #oEXTENSION /* Write the context extension fpsimd header. */ mov w3, #(FPSIMD_MAGIC & 0xffff) movk w3, #(FPSIMD_MAGIC >> 16), lsl #16 str w3, [x2, #oHEAD + oMAGIC] mov w3, #FPSIMD_CONTEXT_SIZE str w3, [x2, #oHEAD + oSIZE] /* Fill in the FP SIMD context. */ add x3, x2, #oV0 + 8 * SZVREG stp d8, d9, [x3], #2 * SZVREG stp d10, d11, [x3], #2 * SZVREG stp d12, d13, [x3], #2 * SZVREG stp d14, d15, [x3], #2 * SZVREG add x3, x2, #oFPSR mrs x4, fpsr str w4, [x3, #oFPSR - oFPSR] mrs x4, fpcr str w4, [x3, #oFPCR - oFPSR] /* Write the termination context extension header. */ add x2, x2, #FPSIMD_CONTEXT_SIZE str xzr, [x2, #oHEAD + oMAGIC] str xzr, [x2, #oHEAD + oSIZE] /* Preserve ucp. */ mov x21, x1 /* rt_sigprocmask (SIG_SETMASK, &ucp->uc_sigmask, &oucp->uc_sigmask, _NSIG8) */ /* Grab the signal mask */ /* rt_sigprocmask (SIG_BLOCK, NULL, &ucp->uc_sigmask, _NSIG8) */ add x2, x0, #UCONTEXT_SIGMASK mov x0, SIG_BLOCK mov x1, 0 mov x3, _NSIG8 mov x8, SYS_ify (rt_sigprocmask) svc 0 cbnz x0, 1f mov x22, x30 mov x0, x21 bl JUMPTARGET (__setcontext) mov x30, x22 RET 1: b C_SYMBOL_NAME(__syscall_error) PSEUDO_END (__swapcontext) weak_alias (__swapcontext, swapcontext)
w296488320/JnitraceForCpp
2,292
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/arm/setcontext.S
/* Copyright (C) 2012 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" #include "ucontext_i.h" .syntax unified .text /* int setcontext (const ucontext_t *ucp) */ ENTRY(setcontext) mov r4, r0 #if (defined __VFP_FP__) && !defined (__ANDROID__) /* Following instruction is vldmia r0!, {d8-d15}. */ ldc p11, cr8, [r0], #64 /* Restore the floating-point status register. */ ldr r1, [r0], #4 /* Following instruction is fmxr fpscr, r1. */ mcr p10, 7, r1, cr1, cr0, 0 #endif #ifdef __IWMMXT__ /* Restore the call-preserved iWMMXt registers. */ /* Following instructions are wldrd wr10, [r0], #8 (etc.) */ ldcl p1, cr10, [r0], #8 ldcl p1, cr11, [r0], #8 ldcl p1, cr12, [r0], #8 ldcl p1, cr13, [r0], #8 ldcl p1, cr14, [r0], #8 ldcl p1, cr15, [r0], #8 #endif /* Now bring back the signal status. */ mov r0, #SIG_SETMASK add r1, r4, #UCONTEXT_SIGMASK mov r2, #0 bl PLTJMP(sigprocmask) /* Loading r0-r3 makes makecontext easier. */ add r14, r4, #MCONTEXT_ARM_R0 ldmia r14, {r0-r11} ldr r13, [r14, #(MCONTEXT_ARM_SP - MCONTEXT_ARM_R0)] add r14, r14, #(MCONTEXT_ARM_LR - MCONTEXT_ARM_R0) ldmia r14, {r14, pc} END(setcontext) // weak_alias(__setcontext, setcontext) /* Called when a makecontext() context returns. Start the context in R4 or fall through to exit(). */ ENTRY(__startcontext) movs r0, r4 bne PLTJMP(setcontext) @ New context was 0 - exit b PLTJMP(_exit) END(__startcontext)
w296488320/JnitraceForCpp
2,312
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/arm/getcontext.S
/* Copyright (C) 2012 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" //#include "weak-alias.h" #include "ucontext_i.h" .syntax unified .text /* int getcontext (ucontext_t *ucp) */ ENTRY(getcontext) /* No need to save r0-r3, d0-d7, or d16-d31. */ add r1, r0, #MCONTEXT_ARM_R4 stmia r1, {r4-r11} /* Save R13 separately as Thumb can't STM it. */ str r13, [r0, #MCONTEXT_ARM_SP] str r14, [r0, #MCONTEXT_ARM_LR] /* Return to LR */ str r14, [r0, #MCONTEXT_ARM_PC] /* Return zero */ mov r2, #0 str r2, [r0, #MCONTEXT_ARM_R0] /* Save ucontext_t * across the next call. */ mov r4, r0 /* __sigprocmask(SIG_BLOCK, NULL, &(ucontext->uc_sigmask)) */ mov r0, #SIG_BLOCK mov r1, #0 add r2, r4, #UCONTEXT_SIGMASK bl PLTJMP(sigprocmask) #if (defined __VFP_FP__) && !defined (__ANDROID__) /* Store the VFP registers. */ /* Following instruction is fstmiax ip!, {d8-d15}. */ stc p11, cr8, [r0], #64 /* Store the floating-point status register. */ /* Following instruction is fmrx r2, fpscr. */ mrc p10, 7, r1, cr1, cr0, 0 str r1, [r0], #4 #endif #ifdef __IWMMXT__ /* Save the call-preserved iWMMXt registers. */ /* Following instructions are wstrd wr10, [r0], #8 (etc.) */ stcl p1, cr10, [r0], #8 stcl p1, cr11, [r0], #8 stcl p1, cr12, [r0], #8 stcl p1, cr13, [r0], #8 stcl p1, cr14, [r0], #8 stcl p1, cr15, [r0], #8 #endif /* Restore the clobbered R4 and LR. */ ldr r14, [r4, #MCONTEXT_ARM_LR] ldr r4, [r4, #MCONTEXT_ARM_R4] mov r0, #0 DO_RET(r14) END(getcontext)
w296488320/JnitraceForCpp
1,649
nativeLib/src/main/cpp/hook/signhook/exts/ucontext/arm/swapcontext.S
/* Copyright (C) 2012 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include "sysdep.h" #include "ucontext_i.h" .syntax unified .text /* int swapcontext (ucontext_t *oucp, const ucontext_t *ucp) */ ENTRY(swapcontext) /* Have getcontext() do most of the work then fix up LR afterwards. Save R3 to keep the stack aligned. */ push {r0,r1,r3,r14} cfi_adjust_cfa_offset (16) cfi_rel_offset (r0,0) cfi_rel_offset (r1,4) cfi_rel_offset (r3,8) cfi_rel_offset (r14,12) bl getcontext mov r4, r0 pop {r0,r1,r3,r14} cfi_adjust_cfa_offset (-16) cfi_restore (r0) cfi_restore (r1) cfi_restore (r3) cfi_restore (r14) /* Exit if getcontext() failed. */ cmp r4, #0 itt ne movne r0, r4 RETINSTR(ne, r14) /* Fix up LR and the PC. */ str r13,[r0, #MCONTEXT_ARM_SP] str r14,[r0, #MCONTEXT_ARM_LR] str r14,[r0, #MCONTEXT_ARM_PC] /* And swap using swapcontext(). */ mov r0, r1 b setcontext END(swapcontext)
w3c/Amaya-Editor
2,167
annotlib/Annot.S
{ Author: J. Kahan 1999-2003 } STRUCTURE Annot; DEFPRES AnnotP; CONST C_Empty = ' '; STRUCT { An annotation is made of a description, an HTML body, and, optionally a thread } Annot (ATTR XmlBody = Yes_; Charset = Text) = BEGIN Description; Body = CASE OF { the annotation body can be of any type } HTML; MathML; SVG; XML; TextFile; END; ? Thread; END; Description = AGGREGATE ATitle = Text; Author = CONSTANT C_Empty; CreatorEmail = CONSTANT C_Empty; CreatorGivenName = CONSTANT C_Empty; CreatorFamilyName = CONSTANT C_Empty; SourceDoc (ATTR HREF_=Text) = CONSTANT C_Empty; RDFtype (ATTR isReply=YES_,NO_) = CONSTANT C_Empty with isReply ? = NO_; AnnotCDate = CONSTANT C_Empty; AnnotMDate = CONSTANT C_Empty; END; { ======= THREADS ====== } {a thread is made of one or more thread items} Thread = LIST OF (Thread_item); { a thread item contains a description and may contain other thread items } Thread_item (ATTR HREF_; Annot_HREF_ = Text; Orphan_item = Yes_) = { link to the annotation } { HREF_ = body URL; Annot_HREF_ = Annot Meta URL; Orphan_item = no parent t } BEGIN TI_desc; ? TI_content = LIST OF (Thread_item); END; TI_desc (ATTR Selected_ = Yes_;) { user is viewing this thread item } = BEGIN TI_Title = TEXT; TI_Date = TEXT; TI_Author = TEXT; TI_Type = TEXT; END; EXCEPT { Annotation } Annot: NoMove, NoResize; { metadata } Description: NoCut; ATitle: NoCut; Author: NoCut; CreatorEmail: NoCut; CreatorFamilyName: NoCut; CreatorGivenName: NoCut; SourceDoc: NoCut; RDFtype: NoCut; isReply: Invisible; AnnotCDate: NoCut; AnnotMDate: NoCut; { body } Body: NoCut; C_Empty: NoCut; { threads } Thread: NoCut; Thread_item: NoCut; TI_desc: NoCut; TI_content: NoCut; Annot_HREF_: Invisible; Orphan_item: Invisible; END
w3c/Amaya-Editor
1,747
annotlib/Topics.S
{ Author: J. Kahan @W3C 2003-2004 } STRUCTURE Topics; DEFPRES TopicsP; CONST C_Empty = ' '; STRUCT { A bookmark collection is a set of bookmarks and topics. } { ======= TOPICS ====== } Topics (ATTR XmlBody = Yes_; Charset = Text) = LIST OF (Item); { a topic item is made of a title, a reference to the model, and an optional list of Items } Topic_item (ATTR Model_HREF_ = Text; Closed_ = Yes; Open_ = Yes_; Selected_ = Yes_;) = BEGIN Topic_title = Text; ? Topic_content = LIST OF (Item) + (SeeAlso_content); END; { an Item can be either a Topic_item a Bookmark_item, or a Separator_item } Item = CASE OF Topic_item; Bookmark_item; Separator_item; END; { a Bookmark has a pointer to the bookmarked document and a title} Bookmark_item (ATTR Model_HREF_; HREF_ = Text;) = BEGIN Bookmark_title = Text; ? SeeAlso_content; END; { a Separator is an empty element} Separator_item (ATTR Model_HREF_; ) = CONSTANT C_Empty; SeeAlso_content = LIST OF (SeeAlso_item); { a SeeAlso item points to related information; it has a pointer to the related document and a title} SeeAlso_item (ATTR Model_HREF_; HREF_;) = BEGIN SeeAlso_title = Text; END; EXCEPT Topics: NoResize, NoMove, NoResize, NoCut; { topics } Topic_title: NoCut, NoSelect, Hidden; Topic_content: NoSelect, Hidden; Selected_: Invisible; { Bookmarks } Bookmark_item: Nocut; Bookmark_title: NoCut, NoSelect, Hidden; { SeeAlso } SeeAlso_item: Nocut, NoSelect; SeeAlso_title: NoCut, NoSelect, Hidden; SeeAlso_content: NoSelect, Hidden; { Separator } C_Empty: NoCut, Hidden; END
w3c/Amaya-Editor
3,209
amaya/Template.S
{ Structure Schema for XTiger Templates Francesc Campoy Flores & I. Vatton January 2007 } STRUCTURE Template; DEFPRES TemplateP; ATTR { generic attributes for internal use } Unknown_attribute = TEXT; { to store an unknown attribute } xmlid = Text; { id } Highlight = Yes_; { to show the element corresponding to the current selection in the source view } SetInLine = Yes_; { to force display: inline } CONST C_CR = '\12'; STRUCT Template (ATTR version = TEXT; templateVersion = TEXT) = LIST OF (Declaration) + (head); Declaration = CASE OF component; union; import; Comment\240; XMLPI; END; TemplateObject = CASE OF repeat; useEl; useSimple; bag; attribute; END + (Comment\240, XMLPI); head ( ATTR version; templateVersion ) = LIST OF (Declaration); DOCTYPE = LIST OF (DOCTYPE_line = TEXT); Comment\240 = LIST OF (Comment_line = TEXT); XMLPI (ATTR is_css = Text) = LIST OF (PI_line = TEXT); component (ATTR name = TEXT) = ANY - (head, union, import); union (ATTR name; includeAt = TEXT; exclude = TEXT) = CONSTANT C_CR; {It is always empty} import (ATTR src = TEXT) = CONSTANT C_CR; {It is always empty} repeat ( ATTR title = TEXT; minOccurs = TEXT; maxOccurs = TEXT) = LIST OF (Repetition); Repetition = CASE OF useEl; useSimple; END + (Comment\240, XMLPI); useEl (ATTR option = option_set, option_unset; title; types = TEXT; currentType = TEXT; prompt = Yes_) = ANY - (head, union, import, component); useSimple (ATTR option; title; types; currentType; prompt) = ANY - (head, union, import, component); bag (ATTR title; types) = LIST OF (ANY) - (head, union, import, component); attribute (ATTR ref_name = TEXT; type = number, string, listVal; useAt = required, optional, prohibited; defaultAt = TEXT; fixed = TEXT; values = TEXT) = CONSTANT C_CR; {It is always empty} EXCEPT XMLPI: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; PI_line: Hidden, MarkupPreserve; DOCTYPE: NoCut, NoSpellCheck, NotAnElementNode; DOCTYPE_line: Hidden, NoCut; Comment\240: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; Comment_line: Hidden, MarkupPreserve; useEl: NoReplicate, NoBreakByReturn, NoCreate, ClickableSurface; component: NewRoot, NoReplicate, NoBreakByReturn, NoCreate, ClickableSurface; useSimple: NoReplicate, NoBreakByReturn, NoCreate, ClickableSurface; repeat: NoReplicate, NoBreakByReturn, NoCreate, ClickableSurface; bag: NoReplicate, NoBreakByReturn, NoCreate, ParagraphBreak, ClickableSurface; {Hiding unkown and language attributes} Highlight: Invisible; SetInLine: Invisible; Unknown_attribute:Invisible; Language: Invisible; types : GiveTypes, DuplicateAttr; option: DuplicateAttr; currentType: Invisible; ref_name: GiveName; name: GiveName; title: GiveName; prompt: Invisible; xmlid: CssId; END
w3c/Amaya-Editor
1,589
amaya/XML.S
{ Thot structure schema for generic XML documents } STRUCTURE XML; DEFPRES XMLP; ATTR { global attributes for all XML elements } xml_space = xml_space_default, xml_space_preserve; Highlight = Yes_; { to show the XML element corresponding to the current selection in the source view } xmlid = Text; { id } class = Text; { class } PseudoClass = Text; STRUCT XML (ATTR RealLang = Yes_;) = LIST OF (XML_Element) + (xmlcomment, xmlpi, cdata); XML_Element = ANY; xmlcomment = LIST OF (xmlcomment_line = TEXT) - (xmlcomment); xmlpi = LIST OF (xmlpi_line = TEXT); doctype = LIST OF (doctype_line = TEXT); cdata = LIST OF (cdata_line = TEXT); xmlbr = TEXT; EXCEPT XML: MoveResize, NoMove; PICTURE: NoMove, NoResize; TEXT: NoMove, NoResize; Highlight: Invisible; class: CssClass, DuplicateAttr; PseudoClass: Invisible, CssPseudoClass; RealLang: Invisible; xmlpi: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; xmlcomment: ReturnCreateNL, NoReplicate, NotAnElementNode; xmlcomment_line: Hidden, MarkupPreserve; xmlpi_line: Hidden, MarkupPreserve; doctype_line: Hidden, NoCut; doctype: NoCut, NotAnElementNode; cdata_line: Hidden, MarkupPreserve; XML_Element: Hidden, IsPlaceholder; xmlbr: Hidden, IsBreak; xml_space: SpacePreserve; xmlid: CssId; END
w3c/Amaya-Editor
1,143
amaya/XLink.S
{ V. Quint June 2000 } STRUCTURE XLink; DEFPRES XLinkP; ATTR type = simple, extended, locator, arc, resource, title_, none_; href_ = TEXT; role = TEXT; arcrole = TEXT; title = TEXT; show = new, replace, embed, other, none_; actuate = onLoad, onRequest, other, none_; from = TEXT; to = TEXT; { annotations } id = TEXT; { To store the reverse link, from an annotation to a source doc } { generic attributes for internal use } Unknown_attribute = TEXT; { to store an unknown attribute } Ghost_restruct = TEXT; { to help structure transformation } CONST C_Empty = ' '; STRUCT XLink (ATTR AnnotIsHidden = Yes_; { AnnotIsHidden: do not show this annotation } AnnotIcon = TEXT; AnnotIcon1 = Yes_; AnnotOrphIcon = Yes_; { the icons we can associate with an annotation }) = BEGIN PICTURE; END; EXCEPT XLink: Hidden; {PICTURE: SelectParent;} AnnotIsHidden: Invisible; AnnotIcon: Invisible; AnnotIcon1: Invisible; AnnotOrphIcon: Invisible; Unknown_attribute: Invisible; END
w3c/Amaya-Editor
4,866
amaya/Timeline.S
{ Thot structure schema for Timeline documents Pierre Geneves June 2002} STRUCTURE Timeline; DEFPRES TimelineP; ATTR { global attributes for all elements } id = text; { global attributes for internal processing } Unknown_attribute = text; Ghost_restruct = text; Highlight = Yes_; { to show the element corresponding to the current selection in the source view } Namespace = text; IntEmptyShape = yes_, no_; STRUCT { Document Structure } Timeline (ATTR fill = text; stroke = text; font_family = text; font_size = text; x = text; y = text; width_ = text; height_ = text) = LIST OF (GraphicsElement); abstract_group (ATTR transform = text) = LIST OF (GraphicsElement); { Images } image_slider (ATTR xlink_href = text; x; y) = AGGREGATE PICTURE; Timeline_Image = Timeline; END; image_collapse (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; image_toolbar (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; image_color (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; image_motion (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; image_interp (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; image_help (ATTR xlink_href; x; y;) = AGGREGATE PICTURE; Timeline_Image; END; exp_period (ATTR fill; stroke; x; y; width_; height_) = BEGIN GRAPHICS; END; col_period (ATTR fill; stroke; x; y; width_; height_) = BEGIN GRAPHICS; END; rect_interface (ATTR fill; stroke; x; y; width_; height_) = BEGIN GRAPHICS; END; rect_id (ATTR fill; stroke; x; y; width_; height_) = BEGIN GRAPHICS; END; tline (ATTR fill; stroke; x1 = text; y1 = text; x2 = text; y2 = text) = BEGIN GRAPHICS; END; { Text } text_ (ATTR fill; stroke; font_family; font_size; x; y) = LIST OF (TEXT); text_id (ATTR fill; stroke; font_family; font_size;) = LIST OF (TEXT); timing_text (ATTR fill; stroke; font_family; font_size; x; y) = LIST OF (TEXT); GraphicsElement = CASE OF exp_period; col_period; rect_interface; rect_id; text_; text_id; timing_text; tline; image_slider; image_collapse; image_help; image_motion; image_color; image_toolbar; image_interp; Timeline; abstract_group; END; EXCEPT Document: NoSelect; Timeline: IsDraw, MoveResize, NoMove, NoCut, NoSelect; abstract_group: NoMove, NoResize, HighlightChildren, NoShowBox, NoCreate, NoSelect, NoCut; col_period: MoveResize, NoShowBox, NoCreate, NoVMove, NoResize; exp_period: MoveResize, NoShowBox, NoCreate, NoVMove, NoVresize; rect_interface: NoMove, NoResize, NoShowBox, NoCreate, NoCut; rect_id: NoMove, NoResize, NoShowBox, NoCreate, NoCut; tline: NoMove, NoResize, NoShowBox, NoCreate, NoCut; text_: NoMove, NoResize, NoShowBox, ReturnCreateWithin, NoCreate, NoCut, NoSelect; timing_text: NoMove, NoResize, ReturnCreateWithin, NoCreate, NoCut; text_id: NoMove, NoResize, ReturnCreateWithin, NoCreate, NoCut; image_slider: MoveResize, NoResize, NoShowBox, NoVMove, NoCut, NoSelect; image_collapse: NoMove, NoResize, NoShowBox, NoCut; image_color: NoMove, NoResize, NoShowBox, NoCut; image_motion: NoMove, NoResize, NoShowBox, NoCut; image_toolbar: NoMove, NoResize, NoShowBox, NoCut; image_help: NoMove, NoResize, NoShowBox, NoCut; image_interp: NoMove, NoResize, NoShowBox, NoCut; Timeline_Image: Hidden, SelectParent, NoCut; GRAPHICS: SelectParent, NoCut; PICTURE: NoMove, NoResize, SelectParent, NoCut; TEXT: NoMove, NoResize, NoCut; id: CssId; Unknown_attribute: Invisible; Highlight: Invisible; Ghost_restruct: Invisible; Namespace: Invisible; IntEmptyShape: Invisible; END
w3c/Amaya-Editor
15,725
amaya/MathML.S
{ Thot Structure Schema for MathML I. Vatton, V. Quint June 1997 } STRUCTURE MathML; DEFPRES MathMLP; ATTR { att-global } class = TEXT; PseudoClass = Text; style\240 = TEXT; { style } id = TEXT; xref = TEXT; other = TEXT; xmlid = Text; { xml:id } xml_space = xml_space_default, xml_space_preserve; { generic attributes for internal use } Highlight = Yes_; { to show the MathML element corresponding to the current selection in the source view } Unknown_attribute = TEXT; { to store an unknown attribute } EntityName = TEXT; { the content of the Thot element is the name of an entity } Ghost_restruct = TEXT; { to help structure transformation } IntDisplaystyle = true, false; { for internal use } IntHidden = Yes_; { for internal use: hide unselected subexpressions in maction element } CONST C_Empty = ' '; C_Space = ' '; MC_Head = ' '; STRUCT MathML { the top-level math element } (ATTR macros = TEXT; display_ = block_, inline_; overflow = scroll, elide, truncate, scale_; altimg = TEXT; alttext = TEXT; RealLang = Yes_; Charset = TEXT; IntSelected = Yes_) = LIST OF (Construct) + (XMLcomment, XMLPI, CDATA, Unknown_namespace); DOCTYPE = LIST OF (DOCTYPE_line = TEXT); Unknown_namespace = TEXT; XMLcomment = LIST OF (XMLcomment_line = TEXT) - (XMLcomment); XMLPI = LIST OF (XMLPI_line = TEXT) ; CDATA = LIST OF (CDATA_line = TEXT); { Presentation: all presentation constructs } Construct (ATTR IntPlaceholder = yes_) = CASE OF { ptoken } MTEXT (ATTR fontsize = TEXT; { deprecated } fontweight = normal_, bold_; { deprecated } fontstyle = normal_, italic; { deprecated } fontfamily = TEXT; { deprecated } color = TEXT; { deprecated } mathvariant = normal_, bold_, italic, bold_italic, double_struck, bold_fraktur, script_, bold_script, fraktur_, sans_serif, bold_sans_serif, sans_serif_italic, sans_serif_bold_italic, monospace; mathsize = TEXT; mathcolor = TEXT; mathbackground = TEXT; IntFontstyle = IntNormal, IntItalic; { for internal use } IntParseMe = yes_) { for internal use } = LIST OF (MathMLCharacters); MI (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} mathvariant; mathsize; mathcolor; mathbackground; IntFontstyle) = LIST OF (MathMLCharacters); MN (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} mathvariant; mathsize; mathcolor; mathbackground; IntFontstyle) = LIST OF (MathMLCharacters); MO (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} mathvariant; mathsize; mathcolor; mathbackground; form = prefix, infix, postfix; fence = true, false; separator = true, false; lspace = TEXT; rspace = TEXT; stretchy = true, false; symmetric = true, false; maxsize = TEXT; minsize = TEXT; largeop = true, false; movablelimits = true, false; accent = true, false; IntFontstyle; { for internal use } IntVertStretch = yes_; { for internal use } IntAddSpace = nospace, spacebefore, spaceafter, both_; IntLargeOp = yes_) = LIST OF (MathMLCharacters); MS (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} mathvariant; mathsize; mathcolor; mathbackground; lquote = TEXT; rquote = TEXT; IntFontstyle) = LIST OF (MathMLCharacters); { petoken } MSPACE (ATTR width\240 = TEXT; height\240 = TEXT; depth\240 = TEXT; linebreak_ = auto_, newline, indentingnewline, nobreak_, goodbreak, badbreak) = CONSTANT C_Space; { plschema } { pgenschema } MROW = LIST OF (Construct); MFRAC (ATTR linethickness = TEXT; numalign = left\240, center\240, right\240; denomalign = left\240, center\240, right\240; bevelled = true, false) = BEGIN Numerator = LIST OF (Construct) with IntDisplaystyle = false; Denominator = LIST OF (Construct) with IntDisplaystyle = false; END; BevelledMFRAC (ATTR linethickness; numalign; denomalign; bevelled) = BEGIN Numerator; Denominator; END ; MSQRT = BEGIN SqrtBase = LIST OF (Construct); END; MENCLOSE (ATTR notation = longdiv, actuarial, radical, box, roundedbox, circle_, left_, right_, top_, bottom_, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike, madruwb) = LIST OF (Construct); MROOT = BEGIN RootBase = LIST OF (Construct); Index = LIST OF (Construct) with IntDisplaystyle = false; END; MSTYLE (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} mathvariant; mathsize; mathcolor; mathbackground; form; fence; separator; lspace; rspace; stretchy; symmetric; maxsize; minsize; largeop; movablelimits; accent; lquote; rquote; linethickness; scriptlevel = TEXT; scriptsizemultiplier = TEXT; scriptminsize = TEXT; background\240 = TEXT; open = TEXT; close = TEXT; separators = TEXT; subscriptshift = TEXT; superscriptshift = TEXT; accentunder = true, false; align = top_, bottom_, center, baseline, axis; rowalign = TEXT; columnalign = TEXT; columnwidth = TEXT; groupalign = TEXT; alignmentscope = TEXT; rowspacing = TEXT; columnspacing = TEXT; rowlines = TEXT; columnlines = TEXT; frame = none\240, solid\240, dashed\240; framespacing = TEXT; equalrows = true, false; equalcolumns = true, false; displaystyle = true, false; rowspan\240 = INTEGER; columnspan = INTEGER; edge = left\240, right\240; actiontype = TEXT; selection = INTEGER; veryverythinmathspace = TEXT; verythinmathspace = TEXT; thinmathspace = TEXT; mediummathspace = TEXT; thickmathspace = TEXT; verythickmathspace = TEXT; veryverythickmathspace = TEXT; IntFontstyle) { for internal use } = LIST OF (Construct); MERROR = LIST OF (Construct); MPADDED (ATTR width\240; height\240; depth\240; lspace) = LIST OF (Construct); MPHANTOM = LIST OF (Construct); MFENCED (ATTR open; close; separators; IntVertStretch) { for internal use } = BEGIN OpeningFence (ATTR IntVertStretch; IntAddSpace) = SYMBOL with IntVertStretch = yes_; FencedExpression = LIST OF (Construct) + (FencedSeparator); ClosingFence (ATTR IntVertStretch; IntAddSpace) = SYMBOL with IntVertStretch = yes_; END; { MF is for internal use. Exported as MO } MF (ATTR fontsize; fontweight; fontstyle; fontfamily; color;{deprecated} form; fence; separator; lspace; rspace; stretchy; symmetric; maxsize; minsize; largeop; movablelimits; accent; IntVertStretch) { for internal use } = TEXT with IntVertStretch = yes_; { pscrschema } MSUB (ATTR subscriptshift; IntVertStretch) { for internal use } = BEGIN Base; Subscript; END; MSUP (ATTR superscriptshift; IntVertStretch) { for internal use } = BEGIN Base; Superscript; END; MSUBSUP (ATTR subscriptshift; superscriptshift; IntVertStretch) { for internal use } = BEGIN Base = LIST OF (Construct); Subscript = LIST OF (Construct) with IntDisplaystyle = false; Superscript = LIST OF (Construct) with IntDisplaystyle = false; END; MUNDER (ATTR accentunder; IntMovelimits = yes_; { for internal use } IntVertStretch) { for internal use } = BEGIN UnderOverBase (ATTR IntHorizStretch = yes_) { for internal use } = LIST OF (Construct); Underscript (ATTR IntHorizStretch) { for internal use } = LIST OF (Construct) with IntDisplaystyle = false; END; MOVER (ATTR accent; IntMovelimits; { for internal use } IntVertStretch) { for internal use } = BEGIN UnderOverBase; Overscript (ATTR IntHorizStretch) { for internal use } = LIST OF (Construct) with IntDisplaystyle = false; END; MUNDEROVER (ATTR accent; accentunder; IntMovelimits; { for internal use } IntVertStretch) { for internal use } = BEGIN UnderOverBase; Underscript; Overscript; END; MMULTISCRIPTS (ATTR subscriptshift; superscriptshift) = BEGIN MultiscriptBase = LIST OF (Construct); PostscriptPairs = LIST OF (PostscriptPair = BEGIN MSubscript = LIST OF (Construct); MSuperscript = LIST OF (Construct); END) with IntDisplaystyle = false; { pscreschema: mprescripts, none } PrescriptPairs = LIST OF (PrescriptPair = BEGIN MSubscript; MSuperscript; END) with IntDisplaystyle = false; END; { ptabschema } MTABLE (ATTR align; {*** add rownumber ***} rowalign; columnalign; groupalign; alignmentscope; columnwidth; width\240; rowspacing; columnspacing; rowlines; columnlines; frame; framespacing; equalrows; equalcolumns; displaystyle; side = left\240, right\240, leftoverlap, rightoverlap; minlabelspacing = TEXT) = BEGIN MTable_head = LIST OF (MColumn_head = CONSTANT MC_Head); MTable_body = LIST OF (TableRow = CASE OF MTR (ATTR rowalign_mtr = top_, bottom_, center, baseline, axis; IntRowAlign = IntTop, IntBottom, IntCenter, IntBaseline, IntAxis; columnalign; groupalign) = LIST OF (MTD); MLABELEDTR (ATTR rowalign_mtr; IntRowAlign; columnalign; groupalign) = LIST OF (MTD) + (RowLabel, LabelCell); END); END with IntDisplaystyle = false; MGLYPH (ATTR alt = TEXT; fontfamily; index = INTEGER) = CONSTANT C_Empty; { pactions } MACTION (ATTR actiontype; selection) = LIST OF (Construct); SEMANTICS { this element is part of the content markup } (ATTR definitionURL = TEXT; encoding = TEXT) = LIST OF (SemanticsContent = CASE OF Construct; ANNOTATION (ATTR encoding) = TEXT; ANNOTATION_XML (ATTR encoding) = Any; END); XLink; { for annotations } { Construct1 is used as a placeholder after a msubsup, msup, msub, munderover, munder or mover that stretches vertically. This allows P rules to play correctly. } { This definition must be the same as Construct. } Construct1 = CASE OF MTEXT; MI; MN; MO; MS; MSPACE; MROW; MFRAC; BevelledMFRAC; MSQRT; MENCLOSE; MROOT; MSTYLE; MERROR; MPADDED; MPHANTOM; MFENCED; MF; MSUB; MSUP; MSUBSUP; MUNDER; MOVER; MUNDEROVER; MMULTISCRIPTS; MTABLE; MGLYPH; MACTION; XLink; END; END; { End of Construct definition } RowLabel = BEGIN Construct; END; { a label within a mlabeledtr } LabelCell = LIST OF (Construct); { a MTD element used as a label in a mlabeledtr element } MTD (ATTR rowalign_mtr; IntRowAlign; columnalign_mtd = left\240, center\240, right\240; IntColAlign = IntLeft, IntCenter, IntRight; groupalign; rowspan\240; columnspan; MRef_column = REFERENCE(MColumn_head); { for internal use } MColExt = REFERENCE(MColumn_head); { for internal use } MRowExt = REFERENCE(TableRow); { for internal use } MLineBelow = solid_, dashed_; { for internal use } MLineOnTheRight = solid_, dashed_; { for internal use } MLineBelowExt = solid_, dashed_; { for internal use } MLineOnTheRightExt = solid_, dashed_) { for internal use } = BEGIN CellWrapper = LIST OF (Construct); END + (MALIGNGROUP, MALIGNMARK); { peschema } MALIGNMARK (ATTR edge) = CONSTANT C_Empty; MALIGNGROUP (ATTR groupalign_malgr = left\240, center\240, right\240, decimalpoint) = CONSTANT C_Empty; { FencedSeparator is for internal use only. It contains a separator in a mfenced expression, according to the separator attribute } FencedSeparator (ATTR IntVertStretch; IntAddSpace) = TEXT; { MathMLCharacters } MathMLCharacters = CASE OF TEXT; MGLYPH; END; EXCEPT MathML: NoMove, NoResize; XMLcomment_line: Hidden, MarkupPreserve; XMLPI_line: Hidden, MarkupPreserve; DOCTYPE: NoCut, NoSpellCheck, NotAnElementNode; DOCTYPE_line: Hidden, NoCut; CDATA_line: Hidden, MarkupPreserve; XMLPI: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; XMLcomment: ReturnCreateNL, NoReplicate, NotAnElementNode; Unknown_namespace: NoCreate; Construct: Hidden; Construct1: Hidden; Numerator: Hidden; Denominator: Hidden; RootBase: Hidden, NoCut; SqrtBase: Hidden, NoCut; Index: Hidden; OpeningFence: Hidden, NoCut, NoCreate; FencedExpression: Hidden, NoCut, NoCreate; ClosingFence: Hidden, NoCut, NoCreate; Base: Hidden, NoCut; Subscript: Hidden; Superscript: Hidden; UnderOverBase: Hidden, NoCut; Underscript: Hidden; Overscript: Hidden; MultiscriptBase: Hidden, NoCut; PostscriptPairs: Hidden, NoCut; PostscriptPair: Hidden; MSubscript: Hidden, NoCut; MSuperscript: Hidden, NoCut; PrescriptPairs: Hidden; PrescriptPair: Hidden; MTABLE: IsTable, NoBreakByReturn; MTable_head: NoCut, Hidden, NoSelect, NoBreakByReturn; MColumn_head: IsColHead, NoCut, Hidden, NoSelect, NoBreakByReturn; MC_Head: Hidden, NoSelect; MTable_body: Hidden, NoBreakByReturn; TableRow: IsRow; MTR: IsRow, NoBreakByReturn; MLABELEDTR: IsRow, NoBreakByReturn; RowLabel: IsCell, Hidden, NoMove, NoResize, NoBreakByReturn, NoCreate; MTD: IsCell, NoMove, NoResize, NoBreakByReturn; CellWrapper: NoCut, Hidden, NoBreakByReturn; FencedSeparator: Hidden, NoCut, NoCreate; C_Empty: Hidden, NoSelect; C_Space: Hidden, NoSelect; id: CssId; {Default id attribute} class: CssClass, DuplicateAttr; PseudoClass: Invisible, CssPseudoClass; { attributes for internal use } RealLang: Invisible; Charset: Invisible; Highlight: Invisible; Unknown_attribute: Invisible; EntityName: Invisible; Ghost_restruct: Invisible; IntDisplaystyle: Invisible; IntHidden: Invisible; IntPlaceholder: Invisible; IntFontstyle: Invisible; IntParseMe: Invisible; IntAddSpace: Invisible; IntLargeOp: Invisible; IntMovelimits: Invisible; IntHorizStretch: Invisible; IntVertStretch: Invisible; IntRowAlign: Invisible; IntColAlign: Invisible; IntSelected: Invisible; rowspan\240: RowSpan; columnspan: ColSpan; MRef_column: ColRef, Invisible; MColExt: Invisible; MRowExt: Invisible; MLineBelow: Invisible; MLineOnTheRight: Invisible; MLineBelowExt: Invisible; MLineOnTheRightExt: Invisible; xml_space: SpacePreserve; END
w3c/Amaya-Editor
150,910
amaya/SVG.S
{ Thot structure schema for Scalable Vector Graphics } STRUCTURE SVG; DEFPRES SVGP; ATTR { global attributes for all SVG elements } {stdAttrs} id = text; xml_base = text; xmlid = Text; { xml:id } xml_space = xml_space_default, xml_space_preserve; { attributes for internal processing } Unknown_attribute = text; Ghost_restruct = text; PseudoClass = text; Highlight = Yes_; { to show the SVG element corresponding to the current selection in the source view } Namespace = text; { for children of element foreignObject } IsCopy = Yes_; CONST C_Empty = ' '; STRUCT { Document Structure } SVG (ATTR requiredFeatures = text; {testAttrs} requiredExtensions = text; {testAttrs} systemLanguage = text; {testAttrs} baseProfile = text; externalResourcesRequired = false, true; class = text; style_ = text; { PresentationAttributes-All } color = text; {PresentationAttributes-Color} color_interpolation = auto, sRGB, linearRGB, inherit; {PresentationAttributes-Color} color_rendering = auto, optimizeSpeed, optimizeQuality, inherit; {PresentationAttributes-Color} enable_background = text; {PresentationAttributes-Containers} flood_color = text; {PresentationAttributes-feFlood} flood_opacity = text; {PresentationAttributes-feFlood} fill = text; {PresentationAttributes-FillStroke} fill_opacity = text; {PresentationAttributes-FillStroke} fill_rule = nonzero, evenodd, inherit; {PresentationAttributes-FillStroke} stroke = text; {PresentationAttributes-FillStroke} stroke_dasharray = text; {PresentationAttributes-FillStroke} stroke_dashoffset = text; {PresentationAttributes-FillStroke} stroke_linecap = butt, round, square, inherit; {PresentationAttributes-FillStroke} stroke_linejoin = miter, round, bevel, inherit; {PresentationAttributes-FillStroke} stroke_miterlimit = text; {PresentationAttributes-FillStroke} stroke_opacity = text; {PresentationAttributes-FillStroke} stroke_width = text; {PresentationAttributes-FillStroke} color_interpolation_filters = auto, sRGB, linearRGB, inherit; {PresentationAttributes-FilterPrimitives} font_family = text; {PresentationAttributes-FontSpecification} font_size = text; {PresentationAttributes-FontSpecification} font_size_adjust =text;{PresentationAttributes-FontSpecification} font_stretch = normal_, wider, narrower, ultra_condensed, extra_condensed, condensed, semi_condensed, semi_expanded, expanded, extra_expanded, ultra_expanded, inherit; {PresentationAttributes-FontSpecification} font_style = normal_, italic, oblique_, inherit; {PresentationAttributes-FontSpecification} font_variant = normal_, small_caps, inherit; {PresentationAttributes-FontSpecification} font_weight = normal_, bold_, bolder, lighter, w100, w200, w300, w400, w500, w600, w700, w800, w900, inherit; {PresentationAttributes-FontSpecification} stop_color = text; {PresentationAttributes-Gradients} stop_opacity = text; {PresentationAttributes-Gradients} clip_path = text; {PresentationAttributes-Graphics} clip_rule = nonzero, evenodd, inherit; {PresentationAttributes-Graphics} cursor_ = text; {PresentationAttributes-Graphics} display_ = inline, block, list_item, run_in, compact, marker_, table, inline_table, table_row_group, table_header_group, table_footer_group, table_row, table_column_group, table_column, table_cell, table_caption, none, inherit; {PresentationAttributes-Graphics} filter_ = text; {PresentationAttributes-Graphics} image_rendering = auto, optimizeSpeed, optimizeQuality, inherit; {PresentationAttributes-Graphics} mask_ = text; {PresentationAttributes-Graphics} opacity_ = text; {PresentationAttributes-Graphics} pointer_events = visiblePainted, visibleFill, visibleStroke, visible, painted, fill__, stroke_, all, none, inherit; {PresentationAttributes-Graphics} shape_rendering = auto, optimizeSpeed, crispEdges, geometricPrecision, inherit; {PresentationAttributes-Graphics} text_rendering = auto, optimizeSpeed, optimizeLegibility, geometricPrecision, inherit; {PresentationAttributes-Graphics} visibility_ = visible, hidden_, inherit; {PresentationAttributes-Graphics} color_profile_ = text; {PresentationAttributes-Images} lighting_color = text; {PresentationAttributes-LightingEffects} marker_start = text; {PresentationAttributes-Markers} marker_mid = text; {PresentationAttributes-Markers} marker_end = text; {PresentationAttributes-Markers} alignment_baseline = baseline, top, before_edge, text_top, text_before_edge, middle, bottom, after_edge, text_bottom, text_after_edge, ideographic_, lower, hanging_, mathematical_, inherit; {PresentationAttributes-TextContentElements} baseline_shift = text; {PresentationAttributes-TextContentElements} direction_ = ltr_, rtl_, inherit; {PresentationAttributes-TextContentElements} dominant_baseline = auto, autosense_script, no_change, reset, ideographic_, lower, hanging_, mathematical_, inherit; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal = text; {PresentationAttributes-TextContentElements} glyph_orientation_vertical = text; {PresentationAttributes-TextContentElements} kerning = text; {PresentationAttributes-TextContentElements} letter_spacing = text; {PresentationAttributes-TextContentElements} text_anchor = start, middle, end__, inherit; {PresentationAttributes-TextContentElements} text_decoration = text; {PresentationAttributes-TextContentElements} unicode_bidi = normal_, embed_, bidi_override, inherit; {PresentationAttributes-TextContentElements} word_spacing = text; {PresentationAttributes-TextContentElements} writing_mode = lr_tb, rl_tb, tb_rl, lr, rl, tb, inherit; {PresentationAttributes-TextElements} clip = text; {PresentationAttributes-Viewports} overflow = visible, hidden_, scroll, auto, inherit; {PresentationAttributes-Viewports} viewBox = text; preserveAspectRatio = text; zoomAndPan = disable, magnify; onfocusin = text; {graphicsElementEvents} onfocusout = text; {graphicsElementEvents} onactivate = text; {graphicsElementEvents} onclick = text; {graphicsElementEvents} onmousedown = text; {graphicsElementEvents} onmouseup = text; {graphicsElementEvents} onmouseover = text; {graphicsElementEvents} onmousemove = text; {graphicsElementEvents} onmouseout = text; {graphicsElementEvents} onload = text; {graphicsElementEvents} onunload = text; {documentEvents} onabort = text; {documentEvents} onerror = text; {documentEvents} onresize = text; {documentEvents} onscroll = text; {documentEvents} onzoom = text; {documentEvents} version = text; x = text; y = text; width_ = text; height_ = text; contentScriptType = text; contentStyleType = text; RealLang = Yes_; Charset = text; UnresolvedRef = Yes_) = LIST OF (GraphicsElement) + (XMLcomment, XMLPI, CDATA, Unknown_namespace); DOCTYPE = LIST OF (DOCTYPE_line = TEXT); Unknown_namespace = TEXT; XMLcomment = LIST OF (XMLcomment_line = TEXT) - (XMLcomment); XMLPI = LIST OF (XMLPI_line = TEXT); CDATA = LIST OF (CDATA_line = TEXT); g (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform = text; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload) {graphicsElementEvents} = LIST OF (GraphicsElement); defs (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload) {graphicsElementEvents} = LIST OF (GraphicsElement); desc (ATTR class; style_; content_ = text) {StructuredText} = TEXT; title (ATTR class; style_; content_) {StructuredText} = TEXT; symbol_ { not in SVG Tiny } (ATTR externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} viewBox; preserveAspectRatio; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload) {graphicsElementEvents} = LIST OF (GraphicsElement); use_ (ATTR xlink_type = simple; {xlinkRefAttrs} xlink_role = text; {xlinkRefAttrs} xlink_arcrole = text; {xlinkRefAttrs} xlink_title = text; {xlinkRefAttrs} xlink_show = other, embed; {xlinkRefAttrs} xlink_actuate = onLoad; {xlinkRefAttrs} xlink_href = text; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; width_; height_) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; END); { Images } image (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} clip; overflow; {PresentationAttributes-Viewports} transform; preserveAspectRatio; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; width_; height_) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; PICTURE; SVG_Image = SVG; END); { Conditional Processing } switch (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload;) {graphicsElementEvents} = LIST OF (CASE OF desc; title; metadata; path; text_; rect; circle_; ellipse; line_; polyline; polygon; use_; image; Timeline_cross; SVG; g; switch; a; foreignObject; script_; style__; symbol_; clipPath; animate; set_; animateMotion; animateColor; animateTransform; END); { Styling } style__ { not in SVG Tiny } (ATTR type = text; media = text; title_ = text) = TEXT; { Paths } path (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} d = text; pathLength = text) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); { Basic Shapes } rect (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; width_; height_; rx = text; ry = text) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); circle_ (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} cx = text; cy = text; r = text) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); ellipse (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} cx; cy; rx; ry) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); line_ (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x1 = text; y1 = text; x2 = text; y2 = text) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); polyline (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} points = text) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); polygon (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} points) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateMotion; animateColor; animateTransform; GRAPHICS; END); { Text } text_ (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; dx = text; dy = text; rotate = text; textLength = text; lengthAdjust = spacing_, spacingAndGlyphs;) = LIST OF (CASE OF tspan; { must be the first option, to allow the Return key to create tspan elements } TEXT; desc; title; metadata; tref; textPath; altGlyph; a; animate; set_; animateMotion; animateColor; animateTransform; END); tspan { not in SVG Tiny } (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; dx; dy; rotate; textLength; lengthAdjust;) = LIST OF (SpanElement = CASE OF TEXT; desc; title; metadata; tspan; tref; altGlyph; a; animate; set_; animateColor; END); tref { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; dx; dy; rotate; textLength; lengthAdjust;) = LIST OF (CASE OF desc; title; metadata; animate; set_; animateColor; END); textPath { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} startOffset = text; textLength; lengthAdjust; method = align, stretch; spacing = auto, exact) = LIST OF (CASE OF TEXT; desc; title; metadata; tspan; tref; altGlyph; a; animate; set_; animateColor; END); altGlyph { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; glyphRef_ = text; format = text; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; dx; dy; rotate) = TEXT; altGlyphDef { not in SVG Tiny } = BEGIN CASE OF LIST OF (glyphRef); LIST OF (altGlyphItem); END; END; altGlyphItem { not in SVG Tiny } = LIST OF (glyphRef); glyphRef { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; class; style_; font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} glyphRef_; format; x; y; dx; dy) = CONSTANT C_Empty; { Marker Symbols } marker { not in SVG Tiny, not in SVG Basic } (ATTR externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} viewBox; preserveAspectRatio; refX = text; refY = text; markerUnits = strokeWidth, userSpaceOnUse; markerWidth = text; markerHeight = text; orient = text) = LIST OF (GraphicsElement); { Color } color_profile { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; local = text; name = text; rendering_intent = auto, perceptual, relative_colorimetric, saturation, absolute_colorimetric) = LIST OF (CASE OF desc; title; metadata; END); { Gradients and Patterns } linearGradient { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} stop_color; stop_opacity; {PresentationAttributes-Gradients} gradientUnits = userSpaceOnUse, objectBoundingBox; gradientTransform = text; x1; y1; x2; y2; spreadMethod = pad, reflect, repeat) = LIST OF (CASE OF desc; title; metadata; stop; animate; set_; animateTransform; END); radialGradient { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} stop_color; stop_opacity; {PresentationAttributes-Gradients} gradientUnits; gradientTransform; cx; cy; r; fx = text; fy = text; spreadMethod) = LIST OF (CASE OF desc; title; metadata; stop; animate; set_; animateTransform; END); stop { not in SVG Tiny } (ATTR class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} stop_color; stop_opacity; {PresentationAttributes-Gradients} offset = text) = LIST OF (CASE OF animate; set_; animateColor; END); pattern { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} viewBox; preserveAspectRatio; patternUnits = userSpaceOnUse, objectBoundingBox; patternContentUnits = userSpaceOnUse, objectBoundingBox; patternTransform = text; x; y; width_; height_) = LIST OF (GraphicsElement); { Clipping, Masking and Compositing } clipPath { not in SVG Tiny } (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} transform; clipPathUnits = userSpaceOnUse, objectBoundingBox;) = AGGREGATE desc; title; metadata; LIST OF (CASE OF path; text_; rect; circle_; ellipse; line_; polyline; polygon; use_; animate; set_; animateMotion; animateColor; animateTransform; END); END; mask { not in SVG Tiny } (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} maskUnits = userSpaceOnUse, objectBoundingBox; maskContentUnits = userSpaceOnUse, objectBoundingBox; x; y; width_; height_) = LIST OF (GraphicsElement); { Filter Effects } filter (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} filterUnits = userSpaceOnUse, objectBoundingBox; primitiveUnits = userSpaceOnUse, objectBoundingBox; x; y; width_; height_; filterRes = text) = LIST OF (CASE OF desc; title; metadata; feBlend; feFlood; feColorMatrix; feComponentTransfer; feComposite; feConvolveMatrix; feDiffuseLighting; feDisplacementMap; feGaussianBlur; feImage; feMerge; feMorphology; feOffset; feSpecularLighting; feTile; feTurbulence; animate; set_; END); feDistantLight (ATTR azimuth = text; elevation = text) = LIST OF (CASE OF animate; set_; END); fePointLight (ATTR x; y; z = text) = LIST OF (CASE OF animate; set_; END); feSpotLight (ATTR x; y; z; pointsAtX = text; pointsAtY = text; pointsAtZ = text; specularExponent = text; limitingConeAngle = text) = LIST OF (CASE OF animate; set_; END); feBlend (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result = text; {filter_primitive_attributes_with_in} in_ = text; {filter_primitive_attributes_with_in} in2 = text; mode = normal_, multiply, screen, darken, lighten;) = LIST OF (CASE OF animate; set_; END); feColorMatrix (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} type__ = matrix, saturate, hueRotate, luminanceToAlpha; values = text) = LIST OF (CASE OF animate; set_; END); feComponentTransfer (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_) {filter_primitive_attributes_with_in} = BEGIN ? feFuncR; ? feFuncG; ? feFuncB; ? feFuncA; END; feFuncR (ATTR type___ = identity, table, discrete, linear, gamma; {component_transfer_function_attributes} tableValues = text; {component_transfer_function_attributes} slope_ = text; {component_transfer_function_attributes} intercept = text; {component_transfer_function_attributes} amplitude = text; {component_transfer_function_attributes} exponent = text; {component_transfer_function_attributes} offset_ = text;) {component_transfer_function_attributes} = LIST OF (CASE OF animate; set_; END); feFuncG (ATTR type___; {component_transfer_function_attributes} tableValues; {component_transfer_function_attributes} slope_; {component_transfer_function_attributes} intercept; {component_transfer_function_attributes} amplitude; {component_transfer_function_attributes} exponent; {component_transfer_function_attributes} offset_) {component_transfer_function_attributes} = LIST OF (CASE OF animate; set_; END); feFuncB (ATTR type___; {component_transfer_function_attributes} tableValues; {component_transfer_function_attributes} slope_; {component_transfer_function_attributes} intercept; {component_transfer_function_attributes} amplitude; {component_transfer_function_attributes} exponent; {component_transfer_function_attributes} offset_) {component_transfer_function_attributes} = LIST OF (CASE OF animate; set_; END); feFuncA (ATTR type___; {component_transfer_function_attributes} tableValues; {component_transfer_function_attributes} slope_; {component_transfer_function_attributes} intercept; {component_transfer_function_attributes} amplitude; {component_transfer_function_attributes} exponent; {component_transfer_function_attributes} offset_) {component_transfer_function_attributes} = LIST OF (CASE OF animate; set_; END); feComposite (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} in2; operator = over, in__, out, atop, xor, arithmetic; k1 = text; k2 = text; k3 = text; k4 = text) = LIST OF (CASE OF animate; set_; END); feConvolveMatrix (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} order = text; kernelMatrix = text; divisor = text; bias = text; targetX = integer; targetY = integer; edgeMode = duplicate, wrap, none; kernelUnitLength = text; preserveAlpha = text) = LIST OF (CASE OF animate; set_; END); feDiffuseLighting (ATTR class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} color_interpolation_filters;{PresentationAttributes-FilterPrimitives} lighting_color; {PresentationAttributes-LightingEffects} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} surfaceScale = text; diffuseConstant = text; kernelUnitLength) = BEGIN CASE OF feDistantLight; fePointLight; feSpotLight; END; LIST OF (CASE OF animate; set_; animateColor; END); END; feDisplacementMap (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} in2; scale_ = text; xChannelSelector = R, G, B, A; yChannelSelector = R, G, B, A) = LIST OF (CASE OF animate; set_; END); feFlood (ATTR class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} flood_color; flood_opacity; {PresentationAttributes-feFlood} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_) {filter_primitive_attributes_with_in} = LIST OF (CASE OF animate; set_; animateColor; END); feGaussianBlur (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} stdDeviation = text) = LIST OF (CASE OF animate; set_; END); feImage (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow) {PresentationAttributes-Viewports} = LIST OF (CASE OF animate; set_; animateTransform; END); feMerge (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes} y; {filter_primitive_attributes} width_; {filter_primitive_attributes} height_; {filter_primitive_attributes} result) {filter_primitive_attributes} = LIST OF (feMergeNode); feMergeNode (ATTR in_) = LIST OF (CASE OF animate; set_; END); feMorphology (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} operator_ = erode, dilate; radius = text) = LIST OF (CASE OF animate; set_; END); feOffset (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} dx; dy) = LIST OF (CASE OF animate; set_; END); feSpecularLighting (ATTR class; style_; color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} color_interpolation_filters;{PresentationAttributes-FilterPrimitives} lighting_color; {PresentationAttributes-LightingEffects} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_; {filter_primitive_attributes_with_in} surfaceScale; specularConstant = text; specularExponent; kernelUnitLength) = BEGIN CASE OF feDistantLight; fePointLight; feSpotLight; END; LIST OF (CASE OF animate; set_; animateColor; END); END; feTile (ATTR color_interpolation_filters;{PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes_with_in} y; {filter_primitive_attributes_with_in} width_; {filter_primitive_attributes_with_in} height_; {filter_primitive_attributes_with_in} result; {filter_primitive_attributes_with_in} in_) {filter_primitive_attributes_with_in} = LIST OF (CASE OF animate; set_; END); feTurbulence (ATTR color_interpolation_filters; {PresentationAttributes-FilterPrimitives} x; {filter_primitive_attributes} y; {filter_primitive_attributes} width_; {filter_primitive_attributes} height_; {filter_primitive_attributes} result; {filter_primitive_attributes} baseFrequency = text; numOctaves = integer; seed = text; stitchTiles = stitch, noStitch; type____ = fractalNoise, turbulence) = LIST OF (CASE OF animate; set_; END); { Interactivity } cursor { not in SVG Tiny, not in SVG Basic} (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; x; y) = AGGREGATE desc; title; metadata; END; { Linking } a (ATTR xlink_href; requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} target_ = text) = LIST OF (CASE OF TEXT; GraphicsElement; END); view { not in SVG Tiny } (ATTR externalResourcesRequired; viewBox; preserveAspectRatio; zoomAndPan; viewTarget = text) = AGGREGATE desc; title; metadata; END; { Scripting } script_ { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; externalResourcesRequired; type) = TEXT; { Animation } animate (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; onbegin = text; {animationEvents} onend = text; {animationEvents} onrepeat = text; {animationEvents} xlink_type; xlink_role; xlink_arcrole; {animElementAttrs} xlink_title; xlink_show; xlink_actuate; {animElementAttrs} xlink_href; {animElementAttrs} attributeName_ = text; {animAttributeAttrs} attributeType = text; begin_ = text; {animTimingAttrs} dur = text; end_ = text; min_ = text; max_ = text; restart = always, never, whenNotActive; repeatCount = text; repeatDur = text; fill_ = remove_, freeze; calcMode = discrete, linear, paced, spline; {animValueAttrs} values; keyTimes = text; keySplines = text; from = text; to_ = text; by = text; additive = replace, sum; {animAdditionAttrs} accumulate = none_, sum;) = AGGREGATE desc; title; metadata; END; set_ (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; onbegin; onend; onrepeat; {animationEvents} xlink_type; xlink_role; xlink_arcrole; {animElementAttrs} xlink_title; xlink_show; xlink_actuate; {animElementAttrs} xlink_href; {animElementAttrs} attributeName_; attributeType; {animAttributeAttrs} begin_; dur; end_; min_; max_; restart; repeatCount; repeatDur; fill_; {animTimingAttrs} to_;) = AGGREGATE desc; title; metadata; END; animateMotion (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; onbegin; onend; onrepeat; {animationEvents} xlink_type; xlink_role; xlink_arcrole; {animElementAttrs} xlink_title; xlink_show; xlink_actuate; {animElementAttrs} xlink_href; {animElementAttrs} attributeName_; attributeType; {animAttributeAttrs} begin_; dur; end_; min_; max_; restart; repeatCount; repeatDur; fill_; {animTimingAttrs} calcMode; values; keyTimes; keySplines; from; to_; by; additive; accumulate; {animAdditionAttrs} path_ = text; keyPoints = text; rotate; origin = text;) = AGGREGATE desc; title; metadata; ? mpath; END; mpath (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href; {see XLink.S} externalResourcesRequired;) = AGGREGATE desc; title; metadata; END; animateColor (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; onbegin; onend; onrepeat; {animationEvents} xlink_type; xlink_role; xlink_arcrole; {animElementAttrs} xlink_title; xlink_show; xlink_actuate; {animElementAttrs} xlink_href; {animElementAttrs} attributeName_; attributeType; {animAttributeAttrs} begin_; dur; end_; min_; max_; restart; repeatCount; repeatDur; fill_; {animTimingAttrs} calcMode; values; keyTimes; keySplines; from; to_; by; {animValueAttrs} additive; accumulate;) {animAdditionAttrs} = AGGREGATE desc; title; metadata; END; animateTransform (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; onbegin; onend; onrepeat; {animationEvents} xlink_type; xlink_role; xlink_arcrole; {animElementAttrs} xlink_title; xlink_show; xlink_actuate; {animElementAttrs} xlink_href; {animElementAttrs} attributeName_; attributeType; {animAttributeAttrs} begin_; dur; end_; min_; max_; restart; repeatCount; repeatDur; fill_; {animTimingAttrs} calcMode; values; keyTimes; keySplines; from; to_; by; {animValueAttrs} additive; accumulate; {animAdditionAttrs} type_ = translate, scale, rotate_, skewX, skewY;) = AGGREGATE desc; title; metadata; END; { Fonts } font_ (ATTR externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} horiz_origin_x = text; horiz_origin_y = text; horiz_adv_x = text; vert_origin_x = text; vert_origin_y = text; vert_adv_y = text) = AGGREGATE desc; title; metadata; font_face; missing_glyph; LIST OF (CASE OF glyph; hkern; vkern; END); END; glyph (ATTR class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} unicode = text; glyph_name = text; d; orientation = text; arabic_form = text; lang = text; horiz_adv_x; vert_origin_x; vert_origin_y; vert_adv_y) = LIST OF (GraphicsElement); missing_glyph (ATTR class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} d; horiz_adv_x; vert_origin_x; vert_origin_y; vert_adv_y) = LIST OF (GraphicsElement); hkern (ATTR u1 = text; g1 = text; u2 = text; g2 = text; k = text) = CONSTANT C_Empty; vkern { not in SVG Tiny } (ATTR u1; g1; u2; g2; k) = CONSTANT C_Empty; font_face (ATTR font_family; font_style; font_variant; font_weight; font_size; font_stretch_ = text; unicode_range = text; units_per_em = text; panose_1 = text; stemv = text; stemh = text; slope = text; cap_height = text; x_height = text; accent_height = text; ascent = text; descent = text; widths = text; bbox = text; ideographic = text; alphabetic = text; mathematical = text; hanging = text; v_ideographic = text; v_alphabetic = text; v_mathematical = text; v_hanging = text; underline_position = text; underline_thickness = text; strikethrough_position = text; strikethrough_thickness = text; overline_position = text; overline_thickness = text) = AGGREGATE desc; title; metadata; ? font_face_src; ? definition_src; END; font_face_src = LIST OF (CASE OF font_face_uri; font_face_name; END); font_face_uri { not in SVG Tiny } (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href) = LIST OF (font_face_format); font_face_format { not in SVG Tiny } (ATTR string = text) = CONSTANT C_Empty; font_face_name (ATTR name) = CONSTANT C_Empty; definition_src (ATTR xlink_type; xlink_role; xlink_arcrole; {xlinkRefAttrs} xlink_title; xlink_show; xlink_actuate; {xlinkRefAttrs} xlink_href) = CONSTANT C_Empty; { Metadata } metadata = TEXT; { Extensibility } foreignObject { not in SVG Tiny } (ATTR requiredFeatures; requiredExtensions; systemLanguage; {testAttrs} externalResourcesRequired; class; style_; { PresentationAttributes-All } color; color_interpolation; {PresentationAttributes-Color} color_rendering; {PresentationAttributes-Color} enable_background; {PresentationAttributes-Containers} flood_color; flood_opacity; {PresentationAttributes-feFlood} fill; fill_opacity; {PresentationAttributes-FillStroke} fill_rule; stroke; {PresentationAttributes-FillStroke} stroke_dasharray; {PresentationAttributes-FillStroke} stroke_dashoffset; {PresentationAttributes-FillStroke} stroke_linecap; {PresentationAttributes-FillStroke} stroke_linejoin; {PresentationAttributes-FillStroke} stroke_miterlimit; {PresentationAttributes-FillStroke} stroke_opacity; stroke_width; {PresentationAttributes-FillStroke} color_interpolation_filters; {PresentationAttributes-FilterPrimitives} font_family; font_size;{PresentationAttributes-FontSpecification} font_size_adjust; {PresentationAttributes-FontSpecification} font_stretch; {PresentationAttributes-FontSpecification} font_style; {PresentationAttributes-FontSpecification} font_variant; {PresentationAttributes-FontSpecification} font_weight; {PresentationAttributes-FontSpecification} stop_color; stop_opacity; {PresentationAttributes-Gradients} clip_path; clip_rule; cursor_; {PresentationAttributes-Graphics} display_; filter_; {PresentationAttributes-Graphics} image_rendering; mask_; {PresentationAttributes-Graphics} opacity_; pointer_events; {PresentationAttributes-Graphics} shape_rendering; {PresentationAttributes-Graphics} text_rendering; visibility_; {PresentationAttributes-Graphics} color_profile_; {PresentationAttributes-Images} lighting_color; {PresentationAttributes-LightingEffects} marker_start; marker_mid; {PresentationAttributes-Markers} marker_end; {PresentationAttributes-Markers} alignment_baseline; {PresentationAttributes-TextContentElements} baseline_shift; {PresentationAttributes-TextContentElements} direction_; {PresentationAttributes-TextContentElements} dominant_baseline; {PresentationAttributes-TextContentElements} glyph_orientation_horizontal; {PresentationAttributes-TextContentElements} glyph_orientation_vertical; {PresentationAttributes-TextContentElements} kerning; {PresentationAttributes-TextContentElements} letter_spacing; {PresentationAttributes-TextContentElements} text_anchor; {PresentationAttributes-TextContentElements} text_decoration; {PresentationAttributes-TextContentElements} unicode_bidi; {PresentationAttributes-TextContentElements} word_spacing; {PresentationAttributes-TextContentElements} writing_mode; {PresentationAttributes-TextElements} clip; overflow; {PresentationAttributes-Viewports} transform; onfocusin; onfocusout; onactivate; {graphicsElementEvents} onclick; onmousedown; onmouseup; {graphicsElementEvents} onmouseover; onmousemove; onmouseout; {graphicsElementEvents} onload; {graphicsElementEvents} x; y; width_; height_; content_) {StructuredText} = BEGIN CASE OF HTML; MathML; TEXT; END; END; { The following elements are not defined in the SVG DTD } Timeline_cross (ATTR x; y; opacity_; width_; height_) = PICTURE; GraphicsElement = CASE OF desc; title; metadata; defs; path; text_; rect; circle_; ellipse; line_; polyline; polygon; use_; image; SVG; g; view; switch; a; altGlyphDef; script_; style__; symbol_; marker; clipPath; mask; linearGradient; radialGradient; pattern; filter; cursor; font_; animate; set_; animateMotion; animateColor; animateTransform; color_profile; font_face; Timeline_cross; END; EXCEPT { exceptions for elements } SVG: IsDraw, MoveResize, NoMove, ClickableSurface; g: NoMove, NoResize, NoCreate, IsGroup, NoShowBox; marker: IsMarker; defs: NoMove, NoResize, NoShowBox, NoCreate; linearGradient:NoMove, NoResize, NoShowBox, NoCreate; stop: NoMove, NoResize, NoShowBox, NoCreate; rect: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer; circle_: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer; ellipse: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer; line_: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UseMarkers; polyline: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer, UseMarkers; polygon: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer, UseMarkers; path: MoveResize, HighlightChildren, NoShowBox, NoCreate, EmptyGraphic, UsePaintServer, UseMarkers; text_: MoveResize, NoResize, NoShowBox, ReturnCreateWithin, NoCreate, UsePaintServer; tspan: NoShowBox, UsePaintServer; use_: NoMove, NoResize, HighlightChildren, NoShowBox, NoCreate, IsGroup, EmptyGraphic; tref: EmptyGraphic; image: MoveResize, HighlightChildren, NoShowBox, EmptyGraphic, IsImg; symbol_: NoMove, NoResize, HighlightChildren,NoShowBox, NoCreate; a: NoMove, NoResize, HighlightChildren, NoShowBox, NoCreate, ClickableSurface; script_: NoMove, NoResize, NoShowBox, NoCreate; style__: NoMove, NoResize, NoShowBox, NoCreate; switch: NoMove, NoResize, NoShowBox, NoCreate, HighlightChildren; foreignObject: MoveResize, HighlightChildren, NoCreate, NewRoot; SVG_Image: Hidden, SelectParent; GRAPHICS: SelectParent; PICTURE: MoveResize, SelectParent{NoMove, NoResize}; TEXT: NoMove, NoResize; Unknown_namespace: NoCreate; DOCTYPE: NoCut, NoSpellCheck, NotAnElementNode; DOCTYPE_line: Hidden, NoCut; XMLcomment_line: Hidden, MarkupPreserve; XMLPI_line: Hidden, MarkupPreserve; CDATA_line: Hidden, MarkupPreserve; XMLPI: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; XMLcomment: ReturnCreateNL, NoReplicate, NotAnElementNode; { exceptions for attributes } id: CssId; {Default id attribute} class: CssClass, DuplicateAttr; PseudoClass: Invisible, CssPseudoClass; Unknown_attribute: Invisible; Highlight: Invisible; Ghost_restruct: Invisible; Namespace: Invisible; RealLang: Invisible; Charset: Invisible; UnresolvedRef: Invisible; IsCopy: Invisible; Timeline_cross: MoveResize, NoResize, HighlightChildren, NoShowBox, NoCut; { the following attributes are made invisible to prevent the Attributes menu from becoming too long } xml_base: Invisible; requiredFeatures: Invisible; requiredExtensions:Invisible; baseProfile: Invisible; externalResourcesRequired: Invisible; color_interpolation: Invisible; color_rendering: Invisible; enable_background: Invisible; flood_color: Invisible; flood_opacity: Invisible; fill_rule: Invisible; stroke_dasharray: Invisible; stroke_dashoffset: Invisible; stroke_linecap: Invisible; stroke_linejoin: Invisible; stroke_miterlimit: Invisible; color_interpolation_filters: Invisible; font_size_adjust: Invisible; font_stretch: Invisible; font_variant: Invisible; stop_color: Invisible; stop_opacity: Invisible; clip_path: Invisible; clip_rule: Invisible; cursor_: Invisible; display_: Invisible; filter_: Invisible; image_rendering: Invisible; mask_: Invisible; pointer_events: Invisible; shape_rendering: Invisible; text_rendering: Invisible; color_profile_: Invisible; lighting_color: Invisible; marker_start: Invisible; marker_mid: Invisible; marker_end: Invisible; alignment_baseline: Invisible; baseline_shift: Invisible; dominant_baseline: Invisible; glyph_orientation_horizontal: Invisible; glyph_orientation_vertical: Invisible; kerning: Invisible; letter_spacing: Invisible; word_spacing: Invisible; writing_mode: Invisible; clip: Invisible; overflow: Invisible; preserveAspectRatio: Invisible; zoomAndPan: Invisible; onfocusin: Invisible; onfocusout: Invisible; onactivate: Invisible; onclick: Invisible; onmousedown: Invisible; onmouseup: Invisible; onmouseover: Invisible; onmousemove: Invisible; onmouseout: Invisible; onload: Invisible; onabort: Invisible; onerror: Invisible; onresize: Invisible; onscroll: Invisible; onzoom: Invisible; contentScriptType: Invisible; contentStyleType: Invisible; xlink_role: Invisible; xlink_arcrole: Invisible; xlink_title: Invisible; xlink_show: Invisible; xlink_actuate: Invisible; rotate: Invisible; textLength: Invisible; lengthAdjust: Invisible; startOffset: Invisible; method: Invisible; spacing: Invisible; format: Invisible; refX: Invisible; refY: Invisible; markerUnits: Invisible; markerWidth: Invisible; markerHeight: Invisible; orient: Invisible; local: Invisible; name: Invisible; rendering_intent: Invisible; gradientUnits: Invisible; gradientTransform: Invisible; spreadMethod: Invisible; fx: Invisible; fy: Invisible; offset: Invisible; patternUnits: Invisible; patternContentUnits: Invisible; patternTransform: Invisible; clipPathUnits: Invisible; maskUnits: Invisible; maskContentUnits: Invisible; target_: Invisible; viewTarget: Invisible; horiz_origin_x: Invisible; horiz_origin_y: Invisible; horiz_adv_x: Invisible; vert_origin_x: Invisible; vert_origin_y: Invisible; vert_adv_y: Invisible; orientation: Invisible; arabic_form: Invisible; lang: Invisible; font_stretch_: Invisible; unicode_range: Invisible; units_per_em: Invisible; panose_1: Invisible; stemv: Invisible; stemh: Invisible; slope: Invisible; cap_height: Invisible; x_height: Invisible; accent_height: Invisible; ascent: Invisible; descent: Invisible; widths: Invisible; bbox: Invisible; ideographic: Invisible; alphabetic: Invisible; mathematical: Invisible; hanging: Invisible; v_ideographic: Invisible; v_alphabetic: Invisible; underline_position: Invisible; underline_thickness: Invisible; strikethrough_position: Invisible; strikethrough_thickness: Invisible; overline_position: Invisible; overline_thickness: Invisible; xml_space: SpacePreserve; END
w3c/Amaya-Editor
46,386
amaya/HTML.S
{ . Vatton Nonember 1994-2002 } STRUCTURE HTML; DEFPRES HTMLP; ATTR { coreattrs } ID = Text; { id } Class = Text; { class } PseudoClass = Text; Style\240 = Text; { style } Title = Text; { title } { i18n } dir = ltr_, rtl_; { dir } { RDFa } about = Text; { about } property = Text; { property } resource = Text; { resource } datatype = Text; { datatype } typeof = Text; { typeof } REL = Text; { rel } REV = Text; { rev } { events } onclick = Text; { onclick } ondblclick = Text; { ondblclick } onmousedown = Text; { onmousedown } onmouseup = Text; { onmouseup } onmouseover = Text; { onmouseover } onmousemove = Text; { onmousemove } onmouseout = Text; { onmouseout } onkeypress = Text; { onkeypress } onkeydown = Text; { onkeydown } onkeyup = Text; { onkeyup } Invalid_attribute = Text; Unknown_attribute = Text; Ghost_restruct = Text; Highlight = Yes_; { to show the HTML element corresponding to the current selection in the source view } IntEntity = Yes_; { do not translate & into &amp; in output file } EntityName = Text; { the content of the element is the name of an entity } xmlid = Text; { xml:id } xml_space = xml_space_default, xml_space_preserve; { xml:space } NoImages = Yes_; NoObjects = Yes_; CONST C_Empty = ' '; C_Head = ' '; C_BR = '\12'; STRUCT HTML { HTML } (ATTR ShowAreas = Yes_; PrintURL = Yes_; PI = Text; Namespaces = Text; RealLang = Yes_; Charset = Text) = BEGIN HEAD; ? BODY; { only one of BODY, document type } ? FRAMESET; END + (Invalid_element, ASP_element, Unknown_namespace, XHTML_Unknown_namespace, Comment\240, XMLPI, CDATA); DOCTYPE = LIST OF (DOCTYPE_line = TEXT); Invalid_element = TEXT; ASP_element = LIST OF (ASP_line = TEXT); Unknown_namespace = TEXT; XHTML_Unknown_namespace = TEXT; Comment\240 = LIST OF (Comment_line = TEXT) - (Comment\240); XMLPI (ATTR is_css = Text) = LIST OF (PI_line = TEXT); CDATA = LIST OF (CDATA_line = TEXT); HEAD { HEAD } (ATTR profile = Text) = AGGREGATE Document_URL = TEXT - (STYLE_, SCRIPT_, META, LINK); TITLE = TEXT - (STYLE_, SCRIPT_, META, LINK); { TITLE } ? ISINDEX (ATTR Prompt = Text) = CONSTANT C_Empty; { ISINDEX } { prompt } ? BASE; { BASE } END + (Object, STYLE_, SCRIPT_, META, LINK); STYLE_ { STYLE } (ATTR !Notation = Text; media = Text) = { type media } TEXT - (STYLE_, SCRIPT_, META, LINK); SCRIPT_ { SCRIPT } (ATTR charset = Text; !content_type = Text; { charset type } script_language = Text; script_src = Text; { language src } defer = Yes_; event = Text; for_ = Text) = { defer event for } TEXT - (STYLE_, SCRIPT_, META, LINK) with content_type ?= 'text/javascript'; META { META } (ATTR http_equiv = Text; { http-equiv } meta_name = Text; meta_content = Text; { name content } scheme = Text) = { scheme } CONSTANT C_Empty; LINK { LINK } (ATTR charset; HREF_ = Text; hreflang = Text; { charset href hreflang } Link_type = Text; { type } media; target_ = Text) = { media target } CONSTANT C_Empty; BASE { BASE } (ATTR !HREF_; target_) = { href target } CONSTANT C_Empty; IMG { IMG } (ATTR !SRC = Text; !ALT = Text; longdesc = Text; { src alt longdesc } Height_ = Text; Width__ = Text; { height width } IntWidthPercent = Integer; IntWidthPxl = Integer; IntHeightPercent = Integer; IntHeightPxl = Integer; USEMAP = Text; ISAMAP = Yes_; { usemap ismap } Alignment = Top_, Middle_, Bottom_, Left_, Right_; { align top middle bottom left right } Img_border = Integer; { border } hspace = Integer; vspace = Integer) = { hspace vspace } BEGIN PICTURE (ATTR SRC); END; BODY { BODY } (ATTR onload = Text; onunload = Text; { onload onunload } background_ = Text; BackgroundColor = Text; { background bgcolor } TextColor = Text; LinkColor = Text; { text link } VisitedLinkColor = Text; ActiveLinkColor = Text) = { vlink alink } LIST OF (Element); Element = CASE OF { block } Paragraph; { P } Pseudo_paragraph; Heading; { heading } List_; { list + DL } Preformatted; { PRE preformatted } Division; { DIV } Center; { CENTER } SCRIPT_; { SCRIPT } NOSCRIPT = LIST OF (Element) - (SCRIPT_); { NOSCRIPT } Block_Quote; { BLOCKQUOTE } Form; { FORM } ISINDEX; { ISINDEX } Horizontal_Rule; { HR } Table_; { TABLE } FIELDSET; { FIELDSET } Address; { ADDRESS } IMG; { IMG } INS; DEL; Object; { OBJECT } Applet; { APPLET } MathML; { MATH } SVG; { SVG } XLink; { Annotations } External_Object { IMG type=svg} (ATTR SRC; { src } Height_; Width__; { height width } IntWidthPercent; IntWidthPxl; IntHeightPercent; IntHeightPxl; USEMAP; ISAMAP; { usemap ismap } NAME = Text; { name } Alignment; { align top middle bottom left right } Img_border; { border } hspace; vspace) = { hspace vspace } BEGIN External_Object_Content; END; Embed_ { EMBED } (ATTR SRC; Alignment; { align top bottom left right } Height_; Width__; { height width } EmbedHidden = Yes_, No_; { hidden yes no } EmbedName = Text; { name } hspace; vspace; { hspace vspace } Embed_type = Text; { type } pluginspage = Text; pluginurl = Text; ) = BEGIN Embed_Content; END; Template; { XTiger } END; HTMLfragment = LIST OF (Element); External_Object_Content = NATURE; Embed_Content = NATURE; Block_Quote { BLOCKQUOTE } (ATTR cite = Text; { cite } InternalLink = Reference(Any); ExternalLink = Yes_) = LIST OF (Element); Horizontal_Rule { HR } (ATTR Align = left_, center_, right_; { align left center right } NoShade = NoShade_; Size_ = Integer; Width__; { noshade size width } IntWidthPercent; IntWidthPxl) = CONSTANT C_Empty; Basic_Set = LIST OF (Basic_Elem); { Paragraph must be the first element defined as a Basic_Set, to make sure that the editor will create a Paragraph when the user wants to create a Basic_Elem } Paragraph { P } (ATTR TextAlign = left_, center_, right_, justify_) = { align left center right justify } Basic_Set; Address = Basic_Set; Pseudo_paragraph = Basic_Set; Heading = CASE OF { heading } H1 (ATTR TextAlign) = Basic_Set; { H1 } { align } H2 (ATTR TextAlign) = Basic_Set; { H2 } H3 (ATTR TextAlign) = Basic_Set; { H3 } H4 (ATTR TextAlign) = Basic_Set; { H4 } H5 (ATTR TextAlign) = Basic_Set; { H5 } H6 (ATTR TextAlign) = Basic_Set; { H6 } END; Preformatted { PRE } (ATTR Width__; IntWidthPercent; IntWidthPxl) = { width } Basic_Set - (IMG, Object, Applet, Big_text, Small_text, Subscript, Superscript, Font_, BaseFont, External_Object); Anchor { A } (ATTR charset; Link_type; NAME; { charset type name } HREF_; hreflang; target_; { href hreflang target} accesskey = Text; { accesskey } shape = rectangle, circle, polygon, default_; { shape rect cirecle poly default } coords = Text; tabindex = Integer; { coords tabindex } onfocus = Text; onblur = Text; { onfocus onblur } InternalLink; ExternalLink; { InternalLink ExternalLink }) = Basic_Set; Basic_Elem = CASE OF { special } TEXT; Font; { fontstyle } Phrase; { phrase } Form_Element; { formctrl } Anchor; { A } IMG; { IMG } Applet; { APPLET } Font_; { FONT } BaseFont; { BASEFONT } BR; { BR } SCRIPT_; { SCRIPT } Quotation; { Q } Subscript = Basic_Set; { SUB } Superscript = Basic_Set; { SUP } Span = Basic_Set; { SPAN } map; MAP; { MAP } BDO (ATTR !dir) = Basic_Set; { BDO } Object; { OBJECT } Embed_; { EMBED } IFRAME; { IFRAME } ruby; { ruby } MathML; { MATH } XLink; { Annotations } Template; { XTiger } External_Object; { External Object } END; BaseFont { BASEFONT } (ATTR !BaseFontSize = Integer; BaseFontColor = Text; { size color } BaseFontFace = Text) = { face } CONSTANT C_Empty; BR { BR } (ATTR Clear_ = Left_, Right_, All_, None_) = { clear left right all none } CONSTANT C_BR; Quotation { Q } (ATTR cite; InternalLink; ExternalLink) = { cite } Basic_Set; Font = CASE OF { fontstyle } Teletype_text = Basic_Set; { TT } Italic_text = Basic_Set; { I } Bold_text = Basic_Set; { B } Underlined_text = Basic_Set; { U } Struck_text = Basic_Set; { S or STRIKE } Big_text = Basic_Set; { BIG } Small_text = Basic_Set; { SMALL } END; Phrase = CASE OF { phrase } Emphasis = Basic_Set; { EM } Strong = Basic_Set; { STRONG } Def = Basic_Set; { DFN } Code = Basic_Set; { CODE } Sample = Basic_Set; { SAMP } Keyboard = Basic_Set; { KBD } Variable_ = Basic_Set; { VAR } Cite = Basic_Set; { CITE } ABBR = Basic_Set; { ABBR } ACRONYM = Basic_Set; { ACRONYM } ins; { INS } del; { DEL } END; Font_ { FONT } (ATTR Font_size = Text; color = Text; face = Text; { size color face } IntSizeIncr = Integer; IntSizeDecr = Integer; IntSizeRel = Integer) = Basic_Set; Applet { APPLET } (ATTR codebase = Text; archive = Text; code = Text; { codebase archive code } object = Text; alt = Text; applet_name = Text; { object alt name } !Width__; IntWidthPercent; IntWidthPxl; { width } !Height_; IntHeightPercent; IntHeightPxl; { height } Alignment; hspace; vspace) = { align hspace vspace } LIST OF (Applet_Content = CASE OF Parameter; { PARAM } Basic_Set; END); Parameter { PARAM } (ATTR !Param_name = Text; Param_value = Text; { name value } valuetype = data_, ref, object_; { valuetype data ref object } Param_type = Text) = { type } CONSTANT C_Empty; Object { OBJECT } (ATTR declare = declare_; classid = Text; codebase; { declare classid codebase } data = Text; Object_type = Text; { data type } codetype = Text; archive; standby = Text; { codetype archive standby } Height_; Width__; IntWidthPercent; IntWidthPxl; IntHeightPercent; IntHeightPxl; { height width } USEMAP; NAME; tabindex; Alignment; Img_border; { usemap name tabindex align border } hspace; vspace) = { hspace vspace } BEGIN PICTURE; Object_Content = LIST OF (ElemOrParam = CASE OF Element; Parameter; END); { PARAM } END; INS { INS } (ATTR cite; datetime = Text; InternalLink; ExternalLink) = { cite datetime } LIST OF (Element); DEL { DEL } (ATTR cite; datetime; InternalLink; ExternalLink) = { cite datetime } LIST OF (Element); ins { INS } (ATTR cite; datetime; InternalLink; ExternalLink) = { cite datetime } Basic_Set; del { DEL } (ATTR cite; datetime; InternalLink; ExternalLink) = { cite datetime } Basic_Set; Block = CASE OF {Block} Paragraph; Pseudo_paragraph; Heading; List_; Preformatted; Division; Center; Block_Quote; Form; Horizontal_Rule; Table_; Address; IMG; Object; Applet; MathML; SVG; XLink; External_Object; Embed_; INS; DEL; END; Division { DIV } (ATTR TextAlign) = { align } LIST OF (Element); Center = { CENTER } LIST OF (Element); List_ = CASE OF { list } Unnumbered_List; { UL } Numbered_List; { OL } Directory; { DIR } Menu; { MENU } Definition_List; { DL } END; Unnumbered_List { UL } (ATTR BulletStyle = disc_, circle_, square_; { type disc circle square } COMPACT = Yes_) = { compact } LIST OF (List_Item); Numbered_List { OL } (ATTR NumberStyle = Arabic_, LowerAlpha, UpperAlpha, { type 1 a A } LowerRoman_, UpperRoman_; { i I } Start = Integer; COMPACT) = { start compact } LIST OF (List_Item); Directory { DIR } (ATTR COMPACT) = { compact } LIST OF (List_Item); Menu { MENU } (ATTR COMPACT) = { compact } LIST OF (List_Item); List_Item { LI } (ATTR ItemStyle = disc_, circle_, square_, Arabic_, { type disc circle square 1 } LowerAlpha, UpperAlpha, LowerRoman_, UpperRoman_; { a A i I } ItemValue = Integer) = { value } LIST OF (Block); Definition_List { DL } (ATTR COMPACT) = { compact } LIST OF (Definition_Item); Definition_Item = BEGIN Term_List = LIST OF (Term = Basic_Set); { DT } ? Definitions = LIST OF (Definition = LIST OF (Block)); { DD } END; Form { FORM } (ATTR !Script_URL = Text; METHOD = Get_, Post_; { action method } ENCTYPE = Text; onsubmit = Text; onreset = Text; { enctype onsubmit onreset } target_; accept_charset = Text) = { target accept-charset } LIST OF (Element) + (Input) - (Form); Form_Element = CASE OF Input; { INPUT } Option_Menu; { SELECT } Text_Area; { TEXTAREA } LABEL; { LABEL } BUTTON_; { BUTTON } END; Option_Menu { SELECT } (ATTR NAME; MenuSize = Integer; Multiple = Yes_; { name size multiple } disabled = Yes_; tabindex; onfocus; onblur; { disabled tabindex onfocus onblur} onchange = Text) = { onchange } LIST OF (Option_item = CASE OF Option; OptGroup; END) - (Input); Option { OPTION } (ATTR Selected = Yes_; DefaultSelected = Yes_; ShowMe = Yes_; { selected } disabled; label = Text; Value_ = Text) = { disabled label value } TEXT; OptGroup { OPTGROUP } (ATTR disabled; !label) = { disabled label } LIST OF (Option); Text_Area { TEXTAREA } (ATTR NAME; !Rows = Integer; !Columns = Integer; { name rows cols } disabled; readonly = Yes_; tabindex; accesskey; { disabled readonly tabindex accesskey } onfocus; onblur; onselect = Text; onchange; { onfocus onblur onselect onchange } Default_Value = Text) = Input_Text - (Input) {with Rows ?= 4, Columns ?= 20}; FIELDSET = { FIELDSET } BEGIN LEGEND; Fieldset_Content = LIST OF (Element); END; LEGEND { LEGEND } (ATTR accesskey; LAlign = Top_, Bottom_, Left_, Right_) = { accesskey align top bottom left right } Basic_Set; Input = CASE OF { formctrl } Text_Input { INPUT / TEXT } (ATTR type = Text; NAME; Value_; disabled; readonly; { type name value disabled readonly } Area_Size = Integer; MaxLength = Integer; { size maxlength } IntAreaSize = Integer; tabindex; accesskey; { tabindex accesskey } onfocus; onblur; onselect; onchange; { onfocus onblur onselect onchange } Default_Value) = Input_Text - (Input) with type = 'text'; Password_Input { INPUT / PASSWORD } (ATTR type; NAME; Value_; disabled; readonly; ALT; { type name value disabled readonly alt} Area_Size; IntAreaSize; MaxLength; { size maxlength } tabindex; accesskey; { tabindex accesskey } onfocus; onblur; onselect; onchange; { onfocus onblur onselect onchange } Default_Value) = Input_Text - (Input) with type = 'password'; File_Input { INPUT / FILE } (ATTR type; NAME; Value_; disabled; readonly; ALT; { type name value disabled readonly alt } Area_Size; IntAreaSize; MaxLength; { size maxlength } tabindex; accesskey; { tabindex accesskey } onfocus; onblur; accept = Text; { onfocus onblur } Default_Value) = Input_Text - (Input) with type = 'file'; Checkbox_Input { INPUT / CHECKBOX } (ATTR type; NAME; Value_; Checked = Yes_, No_; ALT; { type name value checked alt } disabled; readonly; { disabled readonly } tabindex; accesskey; onfocus; onblur; { tabindex accesskey onfocus onblur } DefaultChecked = Yes_, No_) = CONSTANT C_Empty with Checked ?= No_, type = 'checkbox'; Image_Input { INPUT / IMAGE } (ATTR type; NAME; Value_; !SRC; ALT; { type name value src alt } Area_Size; IntWidthPxl; { size } USEMAP; ISAMAP; { usemap ismap } disabled; readonly; tabindex; accesskey; { disabled readonly tabindex accesskey } onfocus; onblur;) = { onfocus onblur } BEGIN PICTURE; END with NAME ?= 'radio', type = 'image'; Radio_Input { INPUT / RADIO } (ATTR type; NAME; Value_; Checked; ALT; { type name value checked disabled alt } disabled; readonly; tabindex; accesskey; { disabled readonly tabindex accesskey } onfocus; onblur; { onfocus onblur } DefaultChecked) = CONSTANT C_Empty with Checked ?= No_, NAME ?= 'radio', type = 'radio'; Submit_Input { INPUT / SUBMIT } (ATTR type; NAME; Value_; disabled; readonly; ALT; { type name value disabled; readonly alt } tabindex; accesskey; { tabindex accesskey } onfocus; onblur) = { onfocus onblur } BEGIN CONSTANT C_Empty; END with Value_ ?= 'Submit', type = 'submit'; Reset_Input { INPUT / RESET } (ATTR type; NAME; Value_; disabled; readonly; ALT; { type name value disabled readonly alt } tabindex; accesskey; { tabindex accesskey } onfocus; onblur) = { onfocus onblur } BEGIN CONSTANT C_Empty; END - (Input) with NAME ?= 'Reset', Value_ ?= 'Reset', type = 'reset'; Button_Input { INPUT / BUTTON } (ATTR type; NAME; Value_; disabled; readonly; ALT; { type name value disabled readonly alt } tabindex; accesskey; { tabindex accesskey } onfocus; onblur) = { onfocus onblur } BEGIN CONSTANT C_Empty; END with type = 'button'; Hidden_Input { INPUT / HIDDEN } (ATTR type; NAME; Value_; disabled; ALT; { type name value disabled alt } tabindex; accesskey; { tabindex accesskey } onfocus; onblur) = { onfocus onblur } CONSTANT C_Empty with type = 'hidden'; BUTTON_ { BUTTON } (ATTR NAME; Value_; { name value } Button_type = button, submit, reset; { button submit reset } disabled; tabindex; accesskey; { disabled tabindex accesskey } onfocus; onblur) = { onfocus onblur } Basic_Set - (Anchor, Input, Form, FIELDSET, IFRAME); LABEL { LABEL } (ATTR Associated_control = TEXT; { for } accesskey; onfocus; onblur) = { accesskey onfocus onblur } Basic_Set; Option_Menu; { SELECT } Text_Area; { TEXTAREA } END; Input_Text = BEGIN Inserted_Text = TEXT; END; Table_ { TABLE } (ATTR summary = Text; Width__; Border = Integer; { summary width border } frame = void, above, below, hsides, lhs, rhs, { frame void above below hsides lhs rhs } vsides, box, border; { vsides box border } rules_ = none_, groups, rows, cols, all; { rules none groups rows cols all } cellspacing = Integer; cellpadding = Integer; { cellspacing cellpadding } Align; BackgroundColor; { align bgcolor } datapagesize = Text; IntWidthPxl; IntWidthPercent) = { datapagesize } BEGIN ? CAPTION; { CAPTION } ? ColStruct = CASE OF Cols = LIST OF (COL); { COL } Colgroups = LIST OF (COLGROUP); { COLGROUP } END; Table_head = LIST OF (Column_head); Table_content = BEGIN ? thead; { THEAD } Table_body = LIST OF (tbody); ? tfoot; { TFOOT } END; END; CAPTION { CAPTION } (ATTR Position = Position_top, Position_bottom, { align top bottom } Position_left, Position_right) = { left right } Basic_Set; COLGROUP { COLGROUP } (ATTR Cell_align = Cell_left, Cell_center, Cell_right, { align left center right } Cell_justify, Cell_char; { justify char } Cell_valign = Cell_top, Cell_middle, Cell_bottom, Cell_baseline; { valign top middle bottom baseline } Width__; span_ = Integer) { width span } = LIST [0..*] OF (COL); COL { COL } (ATTR Cell_align; Cell_valign; Width__; span_) { align valign width span } = CONSTANT C_Empty; ColColgroup = CASE OF { alias for reference Ref_ColColgroup } COL; COLGROUP; END; Column_head (ATTR IntWidthPercent; IntWidthPxl; IntWidthRelative = Integer; { IntWidthForced indicates that IntWidthPercent, IntWidthPxl or IntWidthRelative comes from a COL or COLGROUP element } IntWidthForced = IntWidthForced_; Ref_ColColgroup = REFERENCE(ColColgroup)) = CONSTANT C_Head; thead { THEAD } (ATTR Cell_align; char = Text; charoff = Text; Row_valign = Row_top, Row_middle, Row_bottom, Row_baseline) = { valign top middle bottom baseline } LIST OF (Table_row); tbody { TBODY } (ATTR Cell_align; char; charoff; Row_valign) = LIST OF (Table_row); tfoot { TFOOT } (ATTR Cell_align; char; charoff; Row_valign) = LIST OF (Table_row); Table_row { TR } (ATTR Cell_align; char; charoff; Row_valign; { align char charoff valign } BackgroundColor; IntHeightPxl) = { bgcolor Special attribute to control row span } LIST OF (Table_cell); Table_cell = CASE OF Data_cell; { TD } Heading_cell; { TH } END; Data_cell { TD } (ATTR Ref_column = REFERENCE(Column_head); ColExt = REFERENCE(Column_head); RowExt = REFERENCE(Table_row); abbr = Text; axis = Text; headers = Text; scope = Text; { abbr axis headers scope } rowspan_ = INTEGER; colspan_ = INTEGER; { rowspan colspan } Cell_align; char; charoff; Cell_valign; { align char charoff valign } IntCellAlign = IntCellLeft, IntCellCenter, IntCellRight, IntCellJustify, IntCellChar; No_wrap = no_wrap; BackgroundColor; { nowrap bgcolor } Width__; IntWidthPxl; IntWidthPercent; Height_; IntHeightPercent; IntHeightPxl;) = { width height } LIST OF (Element); Heading_cell { TH } (ATTR Ref_column; ColExt; RowExt; abbr; axis; headers; scope; { abbr axis headers scope } rowspan_; colspan_; { rowspan colspan } Cell_align; char; charoff; Cell_valign; IntCellAlign; { align char charoff valign } No_wrap; BackgroundColor; { nowrap bgcolor } Width__; IntWidthPxl; IntWidthPercent; Height_; IntHeightPercent; IntHeightPxl) = { width height } LIST OF (Element); MAP { MAP } (ATTR NAME; Ref_IMG = REFERENCE(Any)) = { name linked to an image} LIST OF (ElemOrArea = CASE OF Element; AREA; END); map { MAP } (ATTR NAME) = { name } LIST OF (Element); AREA { AREA } (ATTR shape; coords; HREF_; target_; nohref = Yes_; !ALT; { shape coords href target nohref alt } tabindex; accesskey; onfocus; onblur; { tabindex accesskey onfocus onblur } x_coord = Integer; y_coord = Integer; IntWidthPxl; IntHeightPxl; AreaRef_IMG = REFERENCE(Any)) = GRAPHICS with x_coord ?= 0, y_coord ?= 0, IntWidthPxl ?= 25, IntHeightPxl ?= 10; FRAMESET { FRAMESET } (ATTR RowHeight = Text; ColWidth = Text; { rows cols } onload; onunload) = { onload onunload } AGGREGATE Frames = LIST [1 .. *] OF (FrameElem = CASE OF FRAME; FRAMESET; END - (NOFRAMES)); ? NOFRAMES = BODY; { NOFRAMES } END; FRAME { FRAME } (ATTR longdesc; NAME; FrameSrc = Text; { longdesc name src } frameborder = Border1, Border0; { frameborder 1 0 } marginwidth = Integer; marginheight = Integer; { marginwidth marginheight } no_resize = Yes_; scrolling = Yes_, No_, auto_) = { noresize scrolling yes no auto } CONSTANT C_Empty; IFRAME { IFRAME } (ATTR longdesc; NAME; FrameSrc; frameborder; { longdesc name src frameborder } marginwidth; marginheight; scrolling; { marginwidth marginheight scrolling } Alignment; Width__; Height_) = { align width height } BEGIN Iframe_Src_Content= NATURE; Iframe_Content = LIST OF (Element); { flow } END; ruby = { ruby } CASE OF simple_ruby; complex_ruby; END; simple_ruby = { ruby } BEGIN rb = Basic_Set - (simple_ruby, complex_ruby); RtOrRtWithPar = CASE OF rt (ATTR rbspan = Integer) = Basic_Set - (simple_ruby, complex_ruby); RtWithPar = BEGIN rp = TEXT; rt; rp; END; END; END; complex_ruby = { ruby } BEGIN rbc = LIST OF (rb); rtc1 = LIST OF (rt); ? rtc2 = LIST OF (rt); END; { AnyLink is an alias for all elements with an attribute of type URI. Only elements to be shown in the Links view are taken into account } AnyLink = CASE OF Anchor; { HREF_ } Block_Quote; { cite } Quotation; { cite } ins; { cite } del; { cite } END; { ParagEquiv is an alias for elements that are usually formatted like paragraphs } ParagEquiv = CASE OF Paragraph; Pseudo_paragraph; H1; H2; H3; H4; H5; H6; Term; Address; Preformatted; CAPTION; END; EXCEPT HTML: NoMove, NoResize; BODY: NoCut, CssBackground, NoMove, NoResize, SetWindowBackground, NoBreakByReturn; HEAD: NoCut; TITLE: NoCut, NoSpellCheck; Document_URL: Hidden, NoSpellCheck, NoCut; C_Empty: Hidden, NoSpellCheck, NoSelect; C_BR: SelectParent; Frames: Hidden; FRAMESET: NoCreate; { prevent a Return at the end of the document from creating a FRAMESET } Inserted_Text: Hidden, NoCut, NoSpellCheck, CheckAllChars; Basic_Set: Hidden; Definition_Item:Hidden; Term_List: Hidden, CanCut; Definitions: Hidden; XMLPI: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; Comment\240: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; Comment_line: Hidden, MarkupPreserve; ASP_element: ReturnCreateNL, NoSpellCheck, NoReplicate, NotAnElementNode; ASP_line: Hidden, MarkupPreserve; PI_line: Hidden, MarkupPreserve; DOCTYPE: NoCut, NoSpellCheck, NotAnElementNode; DOCTYPE_line: Hidden, NoCut; CDATA_line: Hidden, MarkupPreserve; GRAPHICS: NoMove, NoResize, SelectParent; TEXT: NoMove, NoResize; PICTURE: MoveResize; Invalid_element:NoCreate; Unknown_namespace:NoCreate; XHTML_Unknown_namespace:NoCreate; BR: IsBreak; Pseudo_paragraph: ParagraphBreak, Hidden; Basic_Elem: Hidden; Paragraph: ParagraphBreak; H1: ParagraphBreak; H2: ParagraphBreak; H3: ParagraphBreak; H4: ParagraphBreak; H5: ParagraphBreak; H6: ParagraphBreak; Address: ParagraphBreak; Term: ParagraphBreak; List_Item: ListItemBreak; Definition: ListItemBreak; MAP: IsDraw, IsMap, NoReplicate; IMG: IsImg, NoReplicate; AREA: MoveResize, ClickableSurface, HighlightChildren; Anchor: ClickableSurface; Horizontal_Rule: ClickableSurface; Form: NoReplicate; Image_Input: IsImg, NoReplicate; Password_Input: Shadow, NoReplicate; Text_Input: NoReplicate; File_Input: NoReplicate; Checkbox_Input: NoReplicate; Radio_Input: NoReplicate; Submit_Input: NoReplicate; Reset_Input: NoReplicate; Hidden_Input: NoReplicate; Button_Input: NoReplicate; BUTTON_: NoReplicate; Preformatted: ReturnCreateNL, NoReplicate; STYLE_: ReturnCreateNL, NoSpellCheck, NoReplicate; SCRIPT_: ReturnCreateNL, NoReplicate, MarkupPreserve; Text_Area: ReturnCreateNL, NoReplicate; HTMLfragment: NoMove, NoResize, Hidden, NoBreakByReturn; Division: NoMove, NoResize, NoBreakByReturn; INS: NoReplicate; DEL: NoReplicate; ins: NoReplicate; del: NoReplicate; ExternalLink: Invisible; InternalLink: Invisible; IntWidthPercent:NewPercentWidth, Invisible; IntWidthPxl: NewWidth, Invisible; IntWidthRelative:NewWidth, Invisible; IntWidthForced: Invisible; IntHeightPercent:Invisible; IntHeightPxl: NewHeight, Invisible; IntAreaSize: Invisible; IntSizeIncr: Invisible; IntSizeDecr: Invisible; IntSizeRel: Invisible; IntCellAlign: Invisible; x_coord: Invisible, NewHPos; y_coord: Invisible, NewVPos; Ref_IMG: Invisible; AreaRef_IMG: Invisible; Invalid_attribute: Invisible; Unknown_attribute: Invisible; Highlight: Invisible; PseudoClass: Invisible, CssPseudoClass; Default_Value: Invisible; DefaultSelected:Invisible; ShowMe: Invisible; DefaultChecked: Invisible; ShowAreas: Invisible; PrintURL: Invisible; NoImages: Invisible; NoObjects: Invisible; Namespaces: Invisible; RealLang: Invisible; Charset: Invisible; PI: Invisible; shape: Invisible; Data_cell: IsCell, NoMove, NoResize, NoBreakByReturn; Heading_cell: IsCell, NoMove, NoResize, NoBreakByReturn; Table_cell: IsCell, NoMove, NoResize, NoBreakByReturn; Table_: IsTable, PageBreak, NoReplicate, NoBreakByReturn; CAPTION: IsCaption; Column_head: IsColHead, NoCut, Hidden, NoBreakByReturn; Table_head: NoCut, Hidden, NoSelect, NoBreakByReturn; C_Head: Hidden, NoSelect; ColStruct: Hidden, NoSelect, NoCreate, NoBreakByReturn; Cols: Hidden, NoSelect, NoCreate, NoBreakByReturn; Colgroups: Hidden, NoSelect, NoCreate, NoBreakByReturn; Table_content: PageBreakAllowed, Hidden, NoBreakByReturn; Table_body: PageBreakAllowed, Hidden, NoBreakByReturn; thead: NoBreakByReturn; tbody: NoBreakByReturn; tfoot: NoBreakByReturn; Table_row: IsRow, PageBreakPlace, NoBreakByReturn; rbc: Hidden; rtc1: Hidden; rtc2: Hidden; ColExt: Invisible; RowExt: Invisible; Ref_column: ColRef, Invisible; Ref_ColColgroup:ColColRef; colspan_: ColSpan; rowspan_: RowSpan; Ghost_restruct: Invisible; IntEntity: Invisible; EntityName: Invisible; onclick: EventAttr; ondblclick: EventAttr; onmousedown: EventAttr; onmouseup: EventAttr; onmouseover: EventAttr; onmousemove: EventAttr; onmouseout: EventAttr; onkeypress: EventAttr; onkeydown: EventAttr; onkeyup: EventAttr; onload: EventAttr; onunload: EventAttr; onfocus: EventAttr; onblur: EventAttr; onsubmit: EventAttr; onreset: EventAttr; onchange: EventAttr; onselect: EventAttr; ID : CssId; {Default id attribute} Class: CssClass, DuplicateAttr; External_Object: Hidden; External_Object_Content: Hidden, NoSpellCheck, NewRoot; Embed_: NoBreakByReturn, NoReplicate, NoSpellCheck; Embed_Content: Hidden, NoSelect, NewRoot; Object: NoBreakByReturn, NoReplicate, IsImg; Object_Content: Hidden, NoSelect, NoCreate, NoCut, NoBreakByReturn; Applet: NoBreakByReturn, NoReplicate; Applet_Content: Hidden, NoSelect, NoCreate, NoCut, NoBreakByReturn; IFRAME: NoBreakByReturn, NoReplicate, NoSpellCheck; Iframe_Content: Hidden, NoSelect, NoCut, NoBreakByReturn; Iframe_Src_Content: Hidden, NoCut, NoSelect, NewRoot; Fieldset_Content: Hidden, NoSelect, NoCut, NoBreakByReturn; is_css: Invisible; Start: StartCounter; ItemValue: SetCounter; xml_space: SpacePreserve; END
w600/sdk
7,978
platform/boot/iccarm/startup_iar.s
;******************************************************************************** ;* @file startup.s ;* @version V1.00 ;* @date 1/16/2019 ;* @brief CMSIS Cortex-M3 Core Device Startup File for the W60X ;* ;* @note Copyright (C) 2019 WinnerMicro Inc. All rights reserved. ;* ;* <h2><center>&copy; COPYRIGHT 2019 WinnerMicro</center></h2> ;* ;******************************************************************************** MODULE ?cstartup ;; Forward declaration of sections. SECTION CSTACK:DATA:NOROOT(3) SECTION .intvec:CODE:NOROOT(2) EXTERN pxCurrentTCB EXTERN vTaskSwitchContext EXTERN __iar_program_start ; EXTERN SystemInit PUBLIC __vector_table ;******************************************************************************* ; Fill-up the Vector Table entries with the exceptions ISR address ;******************************************************************************* DATA __vector_table DCD sfe(CSTACK) ; Top address of Stack DCD Reset_Handler ; Reset Handler DCD NMI_Handler ; NMI Handler DCD HardFault_Handler ; Hard Fault Handler DCD MemManage_Handler ; Memory Management Fault Handler DCD BusFault_Handler ; Bus Fault Handler DCD UsageFault_Handler ; Usage Fault Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD SVC_Handler ; SVC Handler DCD DebugMon_Handler ; Debug Monitor Handler DCD 0 ; Reserved DCD PendSV_Handler ; PendSV Handler DCD OS_CPU_SysTickHandler ; SysTick Handler ; External Interrupt Handler DCD SDIO_RX_IRQHandler DCD SDIO_TX_IRQHandler DCD SDIO_RX_CMD_IRQHandler DCD SDIO_TX_CMD_IRQHandler DCD tls_wl_mac_isr DCD 0 DCD tls_wl_rx_isr DCD tls_wl_mgmt_tx_isr DCD tls_wl_data_tx_isr DCD PMU_TIMER1_IRQHandler DCD PMU_TIMER0_IRQHandler DCD PMU_GPIO_WAKE_IRQHandler DCD PMU_SDIO_WAKE_IRQHandler DCD DMA_Channel0_IRQHandler DCD DMA_Channel1_IRQHandler DCD DMA_Channel2_IRQHandler DCD DMA_Channel3_IRQHandler DCD DMA_Channel4_7_IRQHandler DCD DMA_BRUST_IRQHandler DCD I2C_IRQHandler DCD ADC_IRQHandler DCD SPI_LS_IRQHandler DCD SPI_HS_IRQHandler DCD UART0_IRQHandler DCD UART1_IRQHandler DCD GPIOA_IRQHandler DCD TIM0_IRQHandler DCD TIM1_IRQHandler DCD TIM2_IRQHandler DCD TIM3_IRQHandler DCD TIM4_IRQHandler DCD TIM5_IRQHandler DCD WDG_IRQHandler DCD PMU_IRQHandler DCD FLASH_IRQHandler DCD PWM_IRQHandler DCD I2S_IRQHandler DCD PMU_RTC_IRQHandler DCD RSA_IRQHandler DCD CRYPTION_IRQHandler DCD GPIOB_IRQHandler DCD UART2_IRQHandler DCD 0 THUMB PUBWEAK Reset_Handler SECTION .text:CODE:REORDER:NOROOT(2) Reset_Handler ; LDR R0, =SystemInit ; BLX R0 LDR R0, =__iar_program_start BX R0 PUBWEAK NMI_Handler SECTION .text:CODE:REORDER:NOROOT(1) NMI_Handler B NMI_Handler PUBWEAK HardFault_Handler SECTION .text:CODE:REORDER:NOROOT(1) HardFault_Handler B HardFault_Handler PUBWEAK MemManage_Handler SECTION .text:CODE:REORDER:NOROOT(1) MemManage_Handler B MemManage_Handler PUBWEAK BusFault_Handler SECTION .text:CODE:REORDER:NOROOT(1) BusFault_Handler B BusFault_Handler PUBWEAK UsageFault_Handler SECTION .text:CODE:REORDER:NOROOT(1) UsageFault_Handler B UsageFault_Handler PUBWEAK SVC_Handler SECTION .text:CODE:REORDER:NOROOT(1) SVC_Handler ldr r3, =pxCurrentTCB ldr r1, [r3] ldr r0, [r1] ldmia r0!, {r4-r11} msr psp, r0 mov r0, #0 msr basepri, r0 orr r14, r14, #0xd bx r14 PUBWEAK DebugMon_Handler SECTION .text:CODE:REORDER:NOROOT(1) DebugMon_Handler B DebugMon_Handler PUBWEAK PendSV_Handler SECTION .text:CODE:REORDER:NOROOT(1) PendSV_Handler CPSID I mrs r0, psp ldr r3, =pxCurrentTCB ldr r2, [r3] stmdb r0!, {r4-r11} str r0, [r2] stmdb sp!, {r3, r14} bl vTaskSwitchContext ldmia sp!, {r3, r14} ldr r1, [r3] ldr r0, [r1] ldmia r0!, {r4-r11} msr psp, r0 CPSIE I bx r14 nop ; PUBWEAK SysTick_Handler ; SECTION .text:CODE:REORDER:NOROOT(1) ;SysTick_Handler ; B SysTick_Handler ; PUBWEAK PendSV_Handler PUBWEAK OS_CPU_SysTickHandler PUBWEAK SDIO_RX_IRQHandler PUBWEAK SDIO_TX_IRQHandler PUBWEAK SDIO_RX_CMD_IRQHandler PUBWEAK SDIO_TX_CMD_IRQHandler PUBWEAK tls_wl_mac_isr PUBWEAK tls_wl_rx_isr PUBWEAK tls_wl_data_tx_isr PUBWEAK tls_wl_mgmt_tx_isr PUBWEAK RSV_IRQHandler PUBWEAK PMU_RTC_IRQHandler PUBWEAK PMU_TIMER1_IRQHandler PUBWEAK PMU_TIMER0_IRQHandler PUBWEAK PMU_GPIO_WAKE_IRQHandler PUBWEAK PMU_SDIO_WAKE_IRQHandler PUBWEAK DMA_Channel0_IRQHandler PUBWEAK DMA_Channel1_IRQHandler PUBWEAK DMA_Channel2_IRQHandler PUBWEAK DMA_Channel3_IRQHandler PUBWEAK DMA_Channel4_7_IRQHandler PUBWEAK DMA_BRUST_IRQHandler PUBWEAK I2C_IRQHandler PUBWEAK ADC_IRQHandler PUBWEAK SPI_LS_IRQHandler PUBWEAK SPI_HS_IRQHandler PUBWEAK UART0_IRQHandler PUBWEAK UART1_IRQHandler PUBWEAK GPIOA_IRQHandler PUBWEAK TIM0_IRQHandler PUBWEAK TIM1_IRQHandler PUBWEAK TIM2_IRQHandler PUBWEAK TIM3_IRQHandler PUBWEAK TIM4_IRQHandler PUBWEAK TIM5_IRQHandler PUBWEAK WDG_IRQHandler PUBWEAK PMU_IRQHandler PUBWEAK FLASH_IRQHandler PUBWEAK PWM_IRQHandler PUBWEAK I2S_IRQHandler PUBWEAK PMU_6IRQHandler PUBWEAK RSA_IRQHandler PUBWEAK CRYPTION_IRQHandler PUBWEAK GPIOB_IRQHandler PUBWEAK UART2_IRQHandler SECTION .text:CODE:REORDER:NOROOT(1) ;PendSV_Handler OS_CPU_SysTickHandler SDIO_RX_IRQHandler SDIO_TX_IRQHandler SDIO_RX_CMD_IRQHandler SDIO_TX_CMD_IRQHandler tls_wl_mac_isr tls_wl_rx_isr tls_wl_data_tx_isr tls_wl_mgmt_tx_isr RSV_IRQHandler ;SEC_RX_IRQHandler ;SEC_TX_MNGT_IRQHandler ;SEC_TX_DAT_IRQHandler PMU_RTC_IRQHandler PMU_TIMER1_IRQHandler PMU_TIMER0_IRQHandler PMU_GPIO_WAKE_IRQHandler PMU_SDIO_WAKE_IRQHandler DMA_Channel0_IRQHandler DMA_Channel1_IRQHandler DMA_Channel2_IRQHandler DMA_Channel3_IRQHandler DMA_Channel4_7_IRQHandler DMA_BRUST_IRQHandler I2C_IRQHandler ADC_IRQHandler SPI_LS_IRQHandler SPI_HS_IRQHandler UART0_IRQHandler UART1_IRQHandler GPIOA_IRQHandler TIM0_IRQHandler TIM1_IRQHandler TIM2_IRQHandler TIM3_IRQHandler TIM4_IRQHandler TIM5_IRQHandler WDG_IRQHandler PMU_IRQHandler FLASH_IRQHandler PWM_IRQHandler I2S_IRQHandler PMU_6IRQHandler RSA_IRQHandler CRYPTION_IRQHandler GPIOB_IRQHandler UART2_IRQHandler B . END
w600/sdk
8,831
platform/boot/gcc/startup.s
/* File: startup_ARMCM3.S * Purpose: startup file for Cortex-M3 devices. Should use with * GCC for ARM Embedded Processors * Version: V2.0 * Date: 16 August 2013 * /* Copyright (c) 2011 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ .syntax unified .arch armv7-m .section .stack .align 3 #ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE #else .equ Stack_Size, 0xc00 #endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 #ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE #else .equ Heap_Size, 0x1A000 #endif .globl __heap_base .globl __HeapLimit __heap_base: .if Heap_Size .space Heap_Size .endif .size __heap_base, . - __heap_base __HeapLimit: .size __HeapLimit, . - __HeapLimit .section .isr_vector .align 2 .globl __isr_vector __isr_vector: .long __StackTop /* Top of Stack */ .long Reset_Handler /* Reset Handler */ .long NMI_Handler /* NMI Handler */ .long HardFault_Handler /* Hard Fault Handler */ .long MemManage_Handler /* MPU Fault Handler */ .long BusFault_Handler /* Bus Fault Handler */ .long UsageFault_Handler /* Usage Fault Handler */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long SVC_Handler /* SVCall Handler */ .long DebugMon_Handler /* Debug Monitor Handler */ .long 0 /* Reserved */ .long PendSV_Handler /* PendSV Handler */ .long OS_CPU_SysTickHandler /* SysTick Handler */ /* External interrupts */ .long SDIO_RX_IRQHandler /*HSPI&SDIO SLAVE Trasmit*/ .long SDIO_TX_IRQHandler /*HSPI & SDIO SLAVE Receive Data*/ .long 0 /*Not Used*/ .long SDIO_TX_CMD_IRQHandler /*HSPI & SDIO SLAVE Receive Command*/ .long tls_wl_mac_isr /*MAC isr*/ .long 0 /*Not Used*/ .long tls_wl_rx_isr /*Wi-Fi Rx isr*/ .long tls_wl_mgmt_tx_isr /*Wi-Fi Managment tx isr*/ .long tls_wl_data_tx_isr /*Wi-Fi Data Tx isr*/ .long PMU_TIMER1_IRQHandler /*PMU Timer1*/ .long PMU_TIMER0_IRQHandler /*PMU Timer0*/ .long PMU_GPIO_WAKE_IRQHandler /*PMU Wakeup pin isr*/ .long PMU_SDIO_WAKE_IRQHandler /*SDIO Wakeup isr*/ .long DMA_Channel0_IRQHandler /*DMA Channel 0*/ .long DMA_Channel1_IRQHandler /*DMA Channel 1*/ .long DMA_Channel2_IRQHandler /*DMA Channel 2*/ .long DMA_Channel3_IRQHandler /*DMA Channel 3*/ .long DMA_Channel4_7_IRQHandler /*DMA Channel 4-7*/ .long DMA_BURST_IRQHandler /*DMA Burst isr*/ .long I2C_IRQHandler /*I2C isr*/ .long ADC_IRQHandler /*ADC isr*/ .long SPI_LS_IRQHandler /*Master SPI isr*/ .long SPI_HS_IRQHandler /*HSPI isr, not used*/ .long UART0_IRQHandler /*UART0 isr*/ .long UART1_IRQHandler /*UART1 isr*/ .long GPIOA_IRQHandler /*GPIOA isr*/ .long TIM0_IRQHandler /*TIM0 isr*/ .long TIM1_IRQHandler /*TIM1 isr*/ .long TIM2_IRQHandler /*TIM2 isr*/ .long TIM3_IRQHandler /*TIM3 isr*/ .long TIM4_IRQHandler /*TIM4 isr*/ .long TIM5_IRQHandler /*TIM5 isr*/ .long WDG_IRQHandler /*Watchdog isr*/ .long 0 /*Not Used*/ .long 0 /*Not Used*/ .long PWM_IRQHandler /*PWM isr*/ .long I2S_IRQHandler /*I2S isr*/ .long PMU_RTC_IRQHandler /*PMU RTC isr*/ .long RSA_IRQHandler /*RSA isr*/ .long CRYPTION_IRQHandler /*CRYPTION isr*/ .long GPIOB_IRQHandler /*GPIOB isr*/ .long UART2_IRQHandler /*UART2&7816 isr*/ .size __isr_vector, . - __isr_vector .text .thumb .thumb_func .align 2 .globl Reset_Handler .type Reset_Handler, %function Reset_Handler: /* Firstly it copies data from read only memory to RAM. * * The ranges of copy from/to are specified by following symbols * __etext: LMA of start of the section to copy from. Usually end of text * __data_start__: VMA of start of the section to copy to * __data_end__: VMA of end of the section to copy to * * All addresses must be aligned to 4 bytes boundary. */ ldr r1, =__etext ldr r2, =__data_start__ ldr r3, =__data_end__ .L_loop1: cmp r2, r3 ittt lt ldrlt r0, [r1], #4 strlt r0, [r2], #4 blt .L_loop1 /* Single BSS section scheme. * * The BSS section is specified by following symbols * __bss_start__: start of the BSS section. * __bss_end__: end of the BSS section. * * Both addresses must be aligned to 4 bytes boundary. */ ldr r1, =__bss_start__ ldr r2, =__bss_end__ movs r0, 0 .L_loop3: cmp r1, r2 itt lt strlt r0, [r1], #4 blt .L_loop3 /* #ifndef __NO_SYSTEM_INIT bl SystemInit #endif */ bl main .pool .size Reset_Handler, . - Reset_Handler .align 1 .thumb_func .weak Default_Handler .type Default_Handler, %function Default_Handler: b . .size Default_Handler, . - Default_Handler /* Macro to define default handlers. Default handler * will be weak symbol and just dead loops. They can be * overwritten by other handlers */ .macro def_irq_handler handler_name .weak \handler_name .set \handler_name, Default_Handler .endm def_irq_handler NMI_Handler def_irq_handler HardFault_Handler def_irq_handler MemManage_Handler def_irq_handler BusFault_Handler def_irq_handler UsageFault_Handler def_irq_handler SVC_Handler def_irq_handler DebugMon_Handler def_irq_handler PendSV_Handler def_irq_handler OS_CPU_SysTickHandler def_irq_handler SDIO_RX_IRQHandler def_irq_handler SDIO_TX_IRQHandler def_irq_handler SDIO_TX_CMD_IRQHandler def_irq_handler tls_wl_mac_isr def_irq_handler tls_wl_rx_isr def_irq_handler tls_wl_mgmt_tx_isr def_irq_handler tls_wl_data_tx_isr /*def_irq_handler PMU_TIMER1_IRQHandler*/ /*def_irq_handler PMU_TIMER0_IRQHandler*/ /*def_irq_handler PMU_GPIO_WAKE_IRQHandler*/ def_irq_handler PMU_SDIO_WAKE_IRQHandler def_irq_handler DMA_Channel0_IRQHandler def_irq_handler DMA_Channel1_IRQHandler def_irq_handler DMA_Channel2_IRQHandler def_irq_handler DMA_Channel3_IRQHandler def_irq_handler DMA_Channel4_7_IRQHandler def_irq_handler DMA_BURST_IRQHandler /*def_irq_handler I2C_IRQHandler*/ def_irq_handler ADC_IRQHandler def_irq_handler SPI_LS_IRQHandler def_irq_handler SPI_HS_IRQHandler def_irq_handler UART0_IRQHandler def_irq_handler UART1_IRQHandler def_irq_handler GPIOA_IRQHandler def_irq_handler TIM0_IRQHandler def_irq_handler TIM1_IRQHandler def_irq_handler TIM2_IRQHandler def_irq_handler TIM3_IRQHandler def_irq_handler TIM4_IRQHandler def_irq_handler TIM5_IRQHandler def_irq_handler WDG_IRQHandler /*def_irq_handler PWM_IRQHandler*/ /*def_irq_handler I2S_IRQHandler*/ /*def_irq_handler PMU_RTC_IRQHandler*/ def_irq_handler RSA_IRQHandler def_irq_handler CRYPTION_IRQHandler def_irq_handler GPIOB_IRQHandler def_irq_handler UART2_IRQHandler .end
w600/sdk
11,190
platform/boot/armcc/startup.s
;******************** Copyright (c) 2014 Winner Micro Electronic Design Co., Ltd. ******************** ;* File Name : startup_venus.s ;* Author : ;* Version : ;* Date : ;* Description : ; <h> Stack Configuration ; <o> Stack Size (in Bytes) ; </h> Stack_Size EQU 0x00000400 AREA |.bss|, BSS, NOINIT, READWRITE, ALIGN=3 Stack_Mem SPACE Stack_Size __initial_sp ; <h> Heap Configuration ; <o> Heap Size (in Bytes):at least 80Kbyte ; </h> Heap_Size EQU 0x001A000 AREA HEAP, NOINIT, READWRITE, ALIGN=3 __heap_base Heap_Mem SPACE Heap_Size __heap_limit PRESERVE8 THUMB ; Vector Table Mapped to Address 0 at Reset AREA RESET, DATA, READONLY EXPORT __Vectors EXPORT __Vectors_End EXPORT __Vectors_Size IMPORT PendSV_Handler IMPORT OS_CPU_SysTickHandler IMPORT UART0_IRQHandler IMPORT UART1_IRQHandler IMPORT tls_wl_rx_isr IMPORT tls_wl_mgmt_tx_isr IMPORT tls_wl_data_tx_isr IMPORT tls_wl_mac_isr IMPORT TIM0_IRQHandler IMPORT TIM1_IRQHandler IMPORT TIM2_IRQHandler IMPORT TIM3_IRQHandler IMPORT TIM4_IRQHandler IMPORT TIM5_IRQHandler IMPORT WDG_IRQHandler IMPORT tls_exception_handler __Vectors DCD __initial_sp ; Top of Stack DCD Reset_Handler ; Reset Handler DCD NMI_Handler ; NMI Handler DCD HardFault_Handler ; Hard Fault Handler DCD MemManage_Handler ; MPU Fault Handler DCD BusFault_Handler ; Bus Fault Handler DCD UsageFault_Handler ; Usage Fault Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD SVC_Handler ; SVCall Handler DCD DebugMon_Handler ; Debug Monitor Handler DCD 0 ; Reserved DCD PendSV_Handler ; PendSV Handler DCD OS_CPU_SysTickHandler ; SysTick Handler ; External Interrupts DCD SDIO_RX_IRQHandler ; HSPI&SDIO SLAVE Trasmit DCD SDIO_TX_IRQHandler ; HSPI & SDIO SLAVE Receive Data DCD 0 ; Not Used DCD SDIO_TX_CMD_IRQHandler ; HSPI & SDIO SLAVE Receive Command DCD tls_wl_mac_isr ; MAC isr DCD 0 ; Not Used DCD tls_wl_rx_isr ; Wi-Fi Rx isr DCD tls_wl_mgmt_tx_isr ; Wi-Fi Managment tx isr DCD tls_wl_data_tx_isr ; Wi-Fi Data Tx isr DCD PMU_TIMER1_IRQHandler ; PMU Timer1 DCD PMU_TIMER0_IRQHandler ; PMU Timer0 DCD PMU_GPIO_WAKE_IRQHandler ; PMU Wakeup pin isr DCD PMU_SDIO_WAKE_IRQHandler ; SDIO Wakeup isr DCD DMA_Channel0_IRQHandler ; DMA Channel 0 DCD DMA_Channel1_IRQHandler ; DMA Channel 1 DCD DMA_Channel2_IRQHandler ; DMA Channel 2 DCD DMA_Channel3_IRQHandler ; DMA Channel 3 DCD DMA_Channel4_7_IRQHandler ; DMA Channel 4-7 DCD DMA_BURST_IRQHandler ; DMA Burst isr DCD I2C_IRQHandler ; I2C isr DCD ADC_IRQHandler ; ADC isr DCD SPI_LS_IRQHandler ; Master SPI isr DCD SPI_HS_IRQHandler ; HSPI isr, not used DCD UART0_IRQHandler ; UART0 isr DCD UART1_IRQHandler ; UART1 isr DCD GPIOA_IRQHandler ; GPIOA isr DCD TIM0_IRQHandler ; TIM0 isr DCD TIM1_IRQHandler ; TIM1 isr DCD TIM2_IRQHandler ; TIM2 isr DCD TIM3_IRQHandler ; TIM3 isr DCD TIM4_IRQHandler ; TIM4 isr DCD TIM5_IRQHandler ; TIM5 isr DCD WDG_IRQHandler ; Watchdog isr DCD 0 ; Not Used DCD 0 ; Not Used DCD PWM_IRQHandler ; PWM isr DCD I2S_IRQHandler ; I2S isr DCD PMU_RTC_IRQHandler ; PMU RTC isr DCD RSA_IRQHandler ; RSA isr DCD CRYPTION_IRQHandler ; CRYPTION isr DCD GPIOB_IRQHandler ; GBIOB isr DCD UART2_IRQHandler ; UART2&7816 isr DCD 0 ; Not Used __Vectors_End __Vectors_Size EQU __Vectors_End - __Vectors AREA |.text|, CODE, READONLY ; Reset handler Reset_Handler PROC EXPORT Reset_Handler [WEAK] IMPORT __main MOV R0, #0 MSR PRIMASK,R0 LDR R0, =__main BX R0 ENDP ; Dummy Exception Handlers (infinite loops which can be modified) NMI_Handler PROC EXPORT NMI_Handler [WEAK] B . ENDP HardFault_Handler\ PROC EXPORT HardFault_Handler [WEAK] TST LR, #4 ITE EQ MRSEQ R0, MSP MRSNE R0, PSP MOV R1, #0 B tls_exception_handler ENDP MemManage_Handler\ PROC EXPORT MemManage_Handler [WEAK] TST LR, #4 ITE EQ MRSEQ R0, MSP MRSNE R0, PSP MOV R1, #1 B tls_exception_handler ENDP BusFault_Handler\ PROC EXPORT BusFault_Handler [WEAK] TST LR, #4 ITE EQ MRSEQ R0, MSP MRSNE R0, PSP MOV R1, #2 B tls_exception_handler ENDP UsageFault_Handler\ PROC EXPORT UsageFault_Handler [WEAK] TST LR, #4 ITE EQ MRSEQ R0, MSP MRSNE R0, PSP MOV R1, #3 B tls_exception_handler ENDP SVC_Handler PROC EXPORT SVC_Handler [WEAK] B . ENDP DebugMon_Handler\ PROC EXPORT DebugMon_Handler [WEAK] B . ENDP ;PendSV_Handler PROC ; EXPORT PendSV_Handler [WEAK] ; B . ; ENDP ;SysTick_Handler PROC ; EXPORT SysTick_Handler [WEAK] ; B . ; ENDP Default_Handler PROC EXPORT SDIO_RX_IRQHandler [WEAK] EXPORT SDIO_TX_IRQHandler [WEAK] EXPORT SDIO_TX_CMD_IRQHandler [WEAK] EXPORT RSV_IRQHandler [WEAK] EXPORT PMU_RTC_IRQHandler [WEAK] EXPORT PMU_TIMER1_IRQHandler [WEAK] EXPORT PMU_TIMER0_IRQHandler [WEAK] EXPORT PMU_GPIO_WAKE_IRQHandler [WEAK] EXPORT PMU_SDIO_WAKE_IRQHandler [WEAK] EXPORT DMA_Channel0_IRQHandler [WEAK] EXPORT DMA_Channel1_IRQHandler [WEAK] EXPORT DMA_Channel2_IRQHandler [WEAK] EXPORT DMA_Channel3_IRQHandler [WEAK] EXPORT DMA_Channel4_7_IRQHandler [WEAK] EXPORT DMA_BURST_IRQHandler [WEAK] EXPORT I2C_IRQHandler [WEAK] EXPORT ADC_IRQHandler [WEAK] EXPORT SPI_LS_IRQHandler [WEAK] EXPORT SPI_HS_IRQHandler [WEAK] ; EXPORT UART0_IRQHandler [WEAK] ; EXPORT UART1_IRQHandler [WEAK] EXPORT GPIOA_IRQHandler [WEAK] ; EXPORT TIM0_IRQHandler [WEAK] ; EXPORT TIM1_IRQHandler [WEAK] ; EXPORT TIM2_IRQHandler [WEAK] ; EXPORT TIM3_IRQHandler [WEAK] ; EXPORT TIM4_IRQHandler [WEAK] ; EXPORT TIM5_IRQHandler [WEAK] ; EXPORT WDG_IRQHandler [WEAK] EXPORT PWM_IRQHandler [WEAK] EXPORT I2S_IRQHandler [WEAK] EXPORT RSA_IRQHandler [WEAK] EXPORT CRYPTION_IRQHandler [WEAK] EXPORT GPIOB_IRQHandler [WEAK] EXPORT UART2_IRQHandler [WEAK] SDIO_RX_IRQHandler SDIO_TX_IRQHandler SDIO_TX_CMD_IRQHandler ;MAC_IRQHandler RSV_IRQHandler ;SEC_RX_IRQHandler ;SEC_TX_MNGT_IRQHandler ;SEC_TX_DAT_IRQHandler PMU_RTC_IRQHandler PMU_TIMER1_IRQHandler PMU_TIMER0_IRQHandler PMU_GPIO_WAKE_IRQHandler PMU_SDIO_WAKE_IRQHandler DMA_Channel0_IRQHandler DMA_Channel1_IRQHandler DMA_Channel2_IRQHandler DMA_Channel3_IRQHandler DMA_Channel4_7_IRQHandler DMA_BURST_IRQHandler I2C_IRQHandler ADC_IRQHandler SPI_LS_IRQHandler SPI_HS_IRQHandler ;UART0_IRQHandler ;UART1_IRQHandler GPIOA_IRQHandler ;TIM0_IRQHandler ;TIM1_IRQHandler ;TIM2_IRQHandler ;TIM3_IRQHandler ;TIM4_IRQHandler ;TIM5_IRQHandler ;WDG_IRQHandler PWM_IRQHandler I2S_IRQHandler RSA_IRQHandler CRYPTION_IRQHandler GPIOB_IRQHandler UART2_IRQHandler B . ENDP ALIGN ;******************************************************************************* ; User Stack and Heap initialization ;******************************************************************************* IF :DEF:__MICROLIB EXPORT __initial_sp EXPORT __heap_base EXPORT __heap_limit ELSE IMPORT __use_two_region_memory EXPORT __user_initial_stackheap __user_initial_stackheap LDR R0, = Heap_Mem LDR R1, =(Stack_Mem + Stack_Size) LDR R2, = (Heap_Mem + Heap_Size) LDR R3, = Stack_Mem BX LR ALIGN ENDIF END ;******************* Copyright (c) 2014 Winner Micro Electronic Design Co., Ltd. *****END OF FILE*****
Wack0/maciNTosh
3,599
arcgrackle/source/crtresxgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for restoring integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer restore area. */ CFI_STARTPROC CFI_DEF_CFA_REGISTER (11) CFI_OFFSET (65, 4) CFI_OFFSET (14, -72) CFI_OFFSET (15, -68) CFI_OFFSET (16, -64) CFI_OFFSET (17, -60) CFI_OFFSET (18, -56) CFI_OFFSET (19, -52) CFI_OFFSET (20, -48) CFI_OFFSET (21, -44) CFI_OFFSET (22, -40) CFI_OFFSET (23, -36) CFI_OFFSET (24, -32) CFI_OFFSET (25, -28) CFI_OFFSET (26, -24) CFI_OFFSET (27, -20) CFI_OFFSET (28, -16) CFI_OFFSET (29, -12) CFI_OFFSET (30, -8) CFI_OFFSET (31, -4) HIDDEN_FUNC(_restgpr_14_x) lwz 14,-72(11) /* restore gp registers */ CFI_RESTORE (14) HIDDEN_FUNC(_restgpr_15_x) lwz 15,-68(11) CFI_RESTORE (15) HIDDEN_FUNC(_restgpr_16_x) lwz 16,-64(11) CFI_RESTORE (16) HIDDEN_FUNC(_restgpr_17_x) lwz 17,-60(11) CFI_RESTORE (17) HIDDEN_FUNC(_restgpr_18_x) lwz 18,-56(11) CFI_RESTORE (18) HIDDEN_FUNC(_restgpr_19_x) lwz 19,-52(11) CFI_RESTORE (19) HIDDEN_FUNC(_restgpr_20_x) lwz 20,-48(11) CFI_RESTORE (20) HIDDEN_FUNC(_restgpr_21_x) lwz 21,-44(11) CFI_RESTORE (21) HIDDEN_FUNC(_restgpr_22_x) lwz 22,-40(11) CFI_RESTORE (22) HIDDEN_FUNC(_restgpr_23_x) lwz 23,-36(11) CFI_RESTORE (23) HIDDEN_FUNC(_restgpr_24_x) lwz 24,-32(11) CFI_RESTORE (24) HIDDEN_FUNC(_restgpr_25_x) lwz 25,-28(11) CFI_RESTORE (25) HIDDEN_FUNC(_restgpr_26_x) lwz 26,-24(11) CFI_RESTORE (26) HIDDEN_FUNC(_restgpr_27_x) lwz 27,-20(11) CFI_RESTORE (27) HIDDEN_FUNC(_restgpr_28_x) lwz 28,-16(11) CFI_RESTORE (28) HIDDEN_FUNC(_restgpr_29_x) lwz 29,-12(11) CFI_RESTORE (29) HIDDEN_FUNC(_restgpr_30_x) lwz 30,-8(11) CFI_RESTORE (30) HIDDEN_FUNC(_restgpr_31_x) lwz 0,4(11) lwz 31,-4(11) CFI_RESTORE (31) mtlr 0 CFI_RESTORE (65) mr 1,11 CFI_DEF_CFA_REGISTER (1) blr FUNC_END(_restgpr_31_x) FUNC_END(_restgpr_30_x) FUNC_END(_restgpr_29_x) FUNC_END(_restgpr_28_x) FUNC_END(_restgpr_27_x) FUNC_END(_restgpr_26_x) FUNC_END(_restgpr_25_x) FUNC_END(_restgpr_24_x) FUNC_END(_restgpr_23_x) FUNC_END(_restgpr_22_x) FUNC_END(_restgpr_21_x) FUNC_END(_restgpr_20_x) FUNC_END(_restgpr_19_x) FUNC_END(_restgpr_18_x) FUNC_END(_restgpr_17_x) FUNC_END(_restgpr_16_x) FUNC_END(_restgpr_15_x) FUNC_END(_restgpr_14_x) CFI_ENDPROC #endif
Wack0/maciNTosh
1,667
arcgrackle/source/exhandler_low.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern ArcBugcheck .extern RegisterSpace .globl BugcheckTrampoline BugcheckTrampoline: mtspr SPRG3, r31 lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l clrlwi r31, r31, 2 stw r0, 0(r31) mfsrr0 r0 stw r0, 128(r31) mfsrr1 r0 stw r0, 132(r31) lis r31, BugcheckHandler@h ori r31, r31, BugcheckHandler@l mtsrr0 r31 mfmsr r31 ori r31,r31,MSR_IR|MSR_DR mtsrr1 r31 mfspr r31, SPRG3 rfi .globl BugcheckHandler BugcheckHandler: lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l //stw r0, 0(r31) stw r1, 4(r31) stw r2, 8(r31) stw r3, 12(r31) stw r4, 16(r31) stw r5, 20(r31) stw r6, 24(r31) stw r7, 28(r31) stw r8, 32(r31) stw r9, 36(r31) stw r10, 40(r31) stw r11, 44(r31) stw r12, 48(r31) stw r13, 52(r31) stw r14, 56(r31) stw r15, 60(r31) stw r16, 64(r31) stw r17, 68(r31) stw r18, 72(r31) stw r19, 76(r31) stw r20, 80(r31) stw r21, 84(r31) stw r22, 88(r31) stw r23, 92(r31) stw r24, 96(r31) stw r25, 100(r31) stw r26, 104(r31) stw r27, 108(r31) stw r28, 112(r31) stw r29, 116(r31) stw r30, 120(r31) stw r31, 124(r31) //mfspr r4, 26 //stw r4, 128(r31) //mfspr r4, 27 //stw r4, 132(r31) //mfspr r4, CR //stw r4, 136(r31) mfspr r4, 8 stw r4, 140(r31) mfspr r4, 9 stw r4, 144(r31) mfspr r4, 1 stw r4, 148(r31) mfspr r4, 19 stw r4, 152(r31) mfspr r4, 18 stw r4, 156(r31) mfspr r4, 25 stw r4, 160(r31) mr r3, r31 b ArcBugcheck
Wack0/maciNTosh
4,945
arcgrackle/source/floatctx.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .set FP_SIZE, 8 .set GP_SRR0, (SRR0_OFFSET - 8) .set GP_SRR1, (GP_SRR0 + 4) .set GP_1, (GPR1_OFFSET - 8) .set GP_2, (GP_1 + 4) #ifdef _DEBUG .set GP_5, (GPR5_OFFSET - 8) .set GP_6, (GP_5 + 4) #endif .set GP_13, (GPR13_OFFSET - 8) .set GP_14, (GP_13 + 4) .set GP_15, (GP_14 + 4) .set GP_16, (GP_15 + 4) .set GP_17, (GP_16 + 4) .set GP_18, (GP_17 + 4) .set GP_19, (GP_18 + 4) .set GP_20, (GP_19 + 4) .set GP_21, (GP_20 + 4) .set GP_22, (GP_21 + 4) .set GP_23, (GP_22 + 4) .set GP_24, (GP_23 + 4) .set GP_25, (GP_24 + 4) .set GP_26, (GP_25 + 4) .set GP_27, (GP_26 + 4) .set GP_28, (GP_27 + 4) .set GP_29, (GP_28 + 4) .set GP_30, (GP_29 + 4) .set GP_31, (GP_30 + 4) .set GQ_0, (GP_31 + 4) .set GQ_1, (GQ_0 + 4) .set GQ_2, (GQ_1 + 4) .set GQ_3, (GQ_2 + 4) .set GQ_4, (GQ_3 + 4) .set GQ_5, (GQ_4 + 4) .set GQ_6, (GQ_5 + 4) .set GQ_7, (GQ_6 + 4) .set GP_CR, (GQ_7 + 4) .set GP_LR, (GP_CR + 4) .set GP_CTR, (GP_LR + 4) .set GP_XER, (GP_CTR + 4) .set GP_MSR, (GP_XER + 4) .set GP_DAR, (GP_MSR + 4) .set STATE, (GP_DAR + 4) .set MODE, (STATE + 2) .set FP_0, (FPR0_OFFSET - 8) .set FP_1, (FP_0 + FP_SIZE) .set FP_2, (FP_1 + FP_SIZE) .set FP_3, (FP_2 + FP_SIZE) .set FP_4, (FP_3 + FP_SIZE) .set FP_5, (FP_4 + FP_SIZE) .set FP_6, (FP_5 + FP_SIZE) .set FP_7, (FP_6 + FP_SIZE) .set FP_8, (FP_7 + FP_SIZE) .set FP_9, (FP_8 + FP_SIZE) .set FP_10, (FP_9 + FP_SIZE) .set FP_11, (FP_10 + FP_SIZE) .set FP_12, (FP_11 + FP_SIZE) .set FP_13, (FP_12 + FP_SIZE) .set FP_14, (FP_13 + FP_SIZE) .set FP_15, (FP_14 + FP_SIZE) .set FP_16, (FP_15 + FP_SIZE) .set FP_17, (FP_16 + FP_SIZE) .set FP_18, (FP_17 + FP_SIZE) .set FP_19, (FP_18 + FP_SIZE) .set FP_20, (FP_19 + FP_SIZE) .set FP_21, (FP_20 + FP_SIZE) .set FP_22, (FP_21 + FP_SIZE) .set FP_23, (FP_22 + FP_SIZE) .set FP_24, (FP_23 + FP_SIZE) .set FP_25, (FP_24 + FP_SIZE) .set FP_26, (FP_25 + FP_SIZE) .set FP_27, (FP_26 + FP_SIZE) .set FP_28, (FP_27 + FP_SIZE) .set FP_29, (FP_28 + FP_SIZE) .set FP_30, (FP_29 + FP_SIZE) .set FP_31, (FP_30 + FP_SIZE) .set FP_FPSCR, (FP_31 + FP_SIZE) .set PSFP_0, (FP_FPSCR + FP_SIZE) .set PSFP_1, (PSFP_0 + FP_SIZE) .set PSFP_2, (PSFP_1 + FP_SIZE) .set PSFP_3, (PSFP_2 + FP_SIZE) .set PSFP_4, (PSFP_3 + FP_SIZE) .set PSFP_5, (PSFP_4 + FP_SIZE) .set PSFP_6, (PSFP_5 + FP_SIZE) .set PSFP_7, (PSFP_6 + FP_SIZE) .set PSFP_8, (PSFP_7 + FP_SIZE) .set PSFP_9, (PSFP_8 + FP_SIZE) .set PSFP_10, (PSFP_9 + FP_SIZE) .set PSFP_11, (PSFP_10 + FP_SIZE) .set PSFP_12, (PSFP_11 + FP_SIZE) .set PSFP_13, (PSFP_12 + FP_SIZE) .set PSFP_14, (PSFP_13 + FP_SIZE) .set PSFP_15, (PSFP_14 + FP_SIZE) .set PSFP_16, (PSFP_15 + FP_SIZE) .set PSFP_17, (PSFP_16 + FP_SIZE) .set PSFP_18, (PSFP_17 + FP_SIZE) .set PSFP_19, (PSFP_18 + FP_SIZE) .set PSFP_20, (PSFP_19 + FP_SIZE) .set PSFP_21, (PSFP_20 + FP_SIZE) .set PSFP_22, (PSFP_21 + FP_SIZE) .set PSFP_23, (PSFP_22 + FP_SIZE) .set PSFP_24, (PSFP_23 + FP_SIZE) .set PSFP_25, (PSFP_24 + FP_SIZE) .set PSFP_26, (PSFP_25 + FP_SIZE) .set PSFP_27, (PSFP_26 + FP_SIZE) .set PSFP_28, (PSFP_27 + FP_SIZE) .set PSFP_29, (PSFP_28 + FP_SIZE) .set PSFP_30, (PSFP_29 + FP_SIZE) .set PSFP_31, (PSFP_30 + FP_SIZE) .align 5 .globl _cpu_context_save_fp _cpu_context_save_fp: lhz r4,STATE(r3) ori r4,r4,0x0001 sth r4,STATE(r3) stfd fr0, FP_0(r3) stfd fr1, FP_1(r3) stfd fr2, FP_2(r3) stfd fr3, FP_3(r3) stfd fr4, FP_4(r3) stfd fr5, FP_5(r3) stfd fr6, FP_6(r3) stfd fr7, FP_7(r3) stfd fr8, FP_8(r3) stfd fr9, FP_9(r3) stfd fr10, FP_10(r3) stfd fr11, FP_11(r3) stfd fr12, FP_12(r3) stfd fr13, FP_13(r3) stfd fr14, FP_14(r3) stfd fr15, FP_15(r3) stfd fr16, FP_16(r3) stfd fr17, FP_17(r3) stfd fr18, FP_18(r3) stfd fr19, FP_19(r3) stfd fr20, FP_20(r3) stfd fr21, FP_21(r3) stfd fr22, FP_22(r3) stfd fr23, FP_23(r3) stfd fr24, FP_24(r3) stfd fr25, FP_25(r3) stfd fr26, FP_26(r3) stfd fr27, FP_27(r3) stfd fr28, FP_28(r3) stfd fr29, FP_29(r3) stfd fr30, FP_30(r3) stfd fr31, FP_31(r3) mffs fr0 stfd fr0, FP_FPSCR(r3) lfd fr0, FP_0(r3) 1: blr .align 5 .globl _cpu_context_restore_fp _cpu_context_restore_fp: lhz r4,STATE(r3) clrlwi. r4,r4,31 beq 2f lfd fr0, FP_FPSCR(r3) mtfsf 255, fr0 lfd fr0, FP_0(r3) lfd fr1, FP_1(r3) lfd fr2, FP_2(r3) lfd fr3, FP_3(r3) lfd fr4, FP_4(r3) lfd fr5, FP_5(r3) lfd fr6, FP_6(r3) lfd fr7, FP_7(r3) lfd fr8, FP_8(r3) lfd fr9, FP_9(r3) lfd fr10, FP_10(r3) lfd fr11, FP_11(r3) lfd fr12, FP_12(r3) lfd fr13, FP_13(r3) lfd fr14, FP_14(r3) lfd fr15, FP_15(r3) lfd fr16, FP_16(r3) lfd fr17, FP_17(r3) lfd fr18, FP_18(r3) lfd fr19, FP_19(r3) lfd fr20, FP_20(r3) lfd fr21, FP_21(r3) lfd fr22, FP_22(r3) lfd fr23, FP_23(r3) lfd fr24, FP_24(r3) lfd fr25, FP_25(r3) lfd fr26, FP_26(r3) lfd fr27, FP_27(r3) lfd fr28, FP_28(r3) lfd fr29, FP_29(r3) lfd fr30, FP_30(r3) lfd fr31, FP_31(r3) 2: blr
Wack0/maciNTosh
1,163
arcgrackle/source/arcinvoke.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global __ArcInvokeImpl __ArcInvokeImpl: mflr r0 stwu r0, -4(r1) mtctr r3 mr r2, r4 mr r3, r5 mr r4, r6 mr r5, r7 bctrl lwzu r0, 0(r1) addi r1, r1, 4 mtlr r0 blr .globl DCFlushRangeNoSync DCFlushRangeNoSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b blr .globl ICInvalidateRange ICInvalidateRange: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: icbi r0, r3 addi r3, r3, 0x20 bdnz 2b sync isync blr .globl DCFlushRangeInlineSync DCFlushRangeInlineSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b mfspr r3,HID0 ori r4,r3,0x0008 mtspr HID0,r4 isync sync mtspr HID0,r3 blr
Wack0/maciNTosh
2,977
arcgrackle/source/crt0.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern FwMain .extern __executable_start .globl _start _start: // We are currently in little endian mode, // in non-translated mode, // with interrupts disabled. // quick debug test. are we getting here? // r28=ffff_ffff, r30=physaddr of framebuffer //stw r28, 0(r30) //stw r28, 4(r30) //stw r28, 8(r30) //stw r28, 0xc(r30) // r3 is the physical address of our hardware description struct. // Do not bother touching it right now. // In fact, save it in a higher register: mr r31, r3 // Following init code comes from libogc: // clear all BATs li r0,0 mtspr IBAT0U,r0; mtspr IBAT1U,r0; mtspr IBAT2U,r0; mtspr IBAT3U,r0 // IBAT0...3 mtspr DBAT0U,r0; mtspr DBAT1U,r0; mtspr DBAT2U,r0; mtspr DBAT3U,r0 // DBAT0...3 isync // Invalidate all TLBs // Comes from mario kart wii forum - ppc pagetable tutorial // Open Firmware used pagetables so TLBs have been used so invalidate them: li r0,64 li r3,0 // Wipe SDR1 here: sync mtspr 25, r3 isync mtctr r0 invalidate_tlb_loop: tlbie r3 addi r3, r3, 0x1000 bdnz+ invalidate_tlb_loop after_invalidate_tlb: tlbsync // clear all SRs lis r0,0x8000 mtsr 0,r0; mtsr 1,r0; mtsr 2,r0; mtsr 3,r0; mtsr 4,r0; mtsr 5,r0; mtsr 6,r0 mtsr 7,r0; mtsr 8,r0; mtsr 9,r0; mtsr 10,r0; mtsr 11,r0; mtsr 12,r0; mtsr 13,r0 mtsr 14,r0; mtsr 15,r0 isync // set DBAT0 and IBAT0: // 0x8000_0000 + 256MB => physical 0x0000_0000 (cached, r+w) li r3,2 lis r4,0x8000 ori r4,r4,0x1fff mtspr IBAT0L,r3 mtspr IBAT0U,r4 mtspr DBAT0L,r3 mtspr DBAT0U,r4 isync // Grackle can in theory address up to 1GB, but that would use all available BATs. // A BAT has been set to map the first 256MB, that should be more than enough for ARC firmware purposes. // When the ARC firmware memory map, just set any memory above 256MB if present as firmware temporary, // In this case, boot loaders will not use it; but NT kernel indeed can. // set DBAT1: // 0xc000_0000 + 256MB => physical 0x8000_0000 (uncached, r+w) lis r3, 0x8000 ori r3, r3, 0x2a lis r4, 0xc000 ori r4, r4, 0x1fff mtspr DBAT1L, r3 mtspr DBAT1U, r4 isync // set DBAT2: // 0xf000_0000 + 256MB => physical 0xf000_0000 (uncached, r+w) // Grackle PCI configuration space is here, map the entire 256MB. lis r3, 0xf000 ori r3, r3, 0x2a lis r4, 0xf000 ori r4, r4, 0x1fff mtspr DBAT2L, r3 mtspr DBAT2U, r4 isync // set DBAT3: // 0x9000_0000 + 256MB => physical 0x0000_0000 (uncached, r+w) li r3, 0x2a lis r4, 0x9000 ori r4, r4, 0x1fff mtspr DBAT3L, r3 mtspr DBAT3U, r4 isync // set up a stack: // we are at 9MB, use ram before it for stack. // this way we can set up 1MB at 8MB as firmware temporary. lis r1, __executable_start@h ori r1, r1, __executable_start@l subi r1, r1, 8 // switch into translated mode and jump to FwMain mr r3, r31 oris r3, r3, 0x8000 lis r5, FwMain@h ori r5, r5, FwMain@l mtsrr0 r5 mfmsr r4 ori r4, r4, MSR_DR|MSR_IR mtsrr1 r4 rfi
Wack0/maciNTosh
2,709
arcgrackle/source/crtsavgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for saving integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer save area. */ CFI_STARTPROC HIDDEN_FUNC(_savegpr_14) stw 14,-72(11) /* save gp registers */ HIDDEN_FUNC(_savegpr_15) stw 15,-68(11) HIDDEN_FUNC(_savegpr_16) stw 16,-64(11) HIDDEN_FUNC(_savegpr_17) stw 17,-60(11) HIDDEN_FUNC(_savegpr_18) stw 18,-56(11) HIDDEN_FUNC(_savegpr_19) stw 19,-52(11) HIDDEN_FUNC(_savegpr_20) stw 20,-48(11) HIDDEN_FUNC(_savegpr_21) stw 21,-44(11) HIDDEN_FUNC(_savegpr_22) stw 22,-40(11) HIDDEN_FUNC(_savegpr_23) stw 23,-36(11) HIDDEN_FUNC(_savegpr_24) stw 24,-32(11) HIDDEN_FUNC(_savegpr_25) stw 25,-28(11) HIDDEN_FUNC(_savegpr_26) stw 26,-24(11) HIDDEN_FUNC(_savegpr_27) stw 27,-20(11) HIDDEN_FUNC(_savegpr_28) stw 28,-16(11) HIDDEN_FUNC(_savegpr_29) stw 29,-12(11) HIDDEN_FUNC(_savegpr_30) stw 30,-8(11) HIDDEN_FUNC(_savegpr_31) stw 31,-4(11) blr FUNC_END(_savegpr_31) FUNC_END(_savegpr_30) FUNC_END(_savegpr_29) FUNC_END(_savegpr_28) FUNC_END(_savegpr_27) FUNC_END(_savegpr_26) FUNC_END(_savegpr_25) FUNC_END(_savegpr_24) FUNC_END(_savegpr_23) FUNC_END(_savegpr_22) FUNC_END(_savegpr_21) FUNC_END(_savegpr_20) FUNC_END(_savegpr_19) FUNC_END(_savegpr_18) FUNC_END(_savegpr_17) FUNC_END(_savegpr_16) FUNC_END(_savegpr_15) FUNC_END(_savegpr_14) CFI_ENDPROC #endif
Wack0/maciNTosh
1,178
arcloader_unin/source/modeswitch.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global ModeSwitchEntry ModeSwitchEntry: // (ArcFirmEntry Start, PHW_DESCRIPTION HwDesc) // save our arguments // r3 (le entrypoint) into srr0 mr r29, r3 // r4 (argument) into r31 mr r31, r4 mr r30, r5 li r28,-1 //lwz r27, 0(r30) // Disable interrupts. mfmsr r7 rlwinm r8, r7, 0, 17, 15 mtmsr r8 isync // mark that we are here //stw r28, 0(r30) //stw r28, 4(r30) //stw r28, 8(r30) //stw r28, 0xc(r30) // All exceptions lead to infinite loop. No exceptions. li r0,0x10 mtctr r0 li r7,0 lis r8, 0x4800 // b . exception_wipe_loop: stw r8, 4(r7) addi r7, r7, 0x100 bdnz+ exception_wipe_loop // Set MSR_ILE mfmsr r7 lis r8, 1 or r7, r7, r8 mtmsr r7 isync // set up srr1 ready to set MSR_LE, disable MSR_IR|MSR_DR ori r7, r7, 1 rlwinm r7, r7, 0, 28, 25 mtsrr1 r7 mtsrr0 r29 // srr0 already set up // set the hwdesc arg (vaddr): oris r3, r31, 0x8000 // put the top 4 bits of the framebuffer address into r4 rlwinm r4, r30, 0, 0, 3 // turn that into 0x9000_0000 if it's 0x8000_0000 lis r9, 0x8000 cmpw 0, r4, r9 bne+ 0, not_bat0 lis r4, 0x9000 not_bat0: // and rfi into le entrypoint rfi
Wack0/maciNTosh
1,329
arcloader_grackle/source/modeswitch.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global ModeSwitchEntry ModeSwitchEntry: // (ArcFirmEntry Start, PHW_DESCRIPTION HwDesc) // save our arguments // r3 (le entrypoint) into srr0 mr r29, r3 // r4 (argument) into r31 mr r31, r4 mr r30, r5 li r28,-1 // Disable interrupts. mfmsr r7 rlwinm r8, r7, 0, 17, 15 mtmsr r8 isync // r4 = CONFIG_ADDR lis r4, 0xFEC0 ori r4, r4, 4 // r5 = CONFIG_DATA addis r5, r4, 0x20 // r6 = PICR1 addr lis r6, 0x8000 ori r6, r6, 0x00A8 // Ensure we can access grackle pci config registers through the MMU: lwbrx r0,0,r4 lwbrx r0,0,r5 // All exceptions lead to infinite loop. No exceptions. li r0,0x10 mtctr r0 li r7,0 lis r8, 0x4800 // b . exception_wipe_loop: stw r8, 4(r7) addi r7, r7, 0x100 bdnz+ exception_wipe_loop // Set up grackle to r/w PICR1 stwbrx r6,0,r4 eieio sync lwbrx r0,0,r4 sync // Set PICR1_LE_MODE in PICR1 lwbrx r7,0,r5 sync ori r7,r7,0x20 stwbrx r7,0,r5 eieio sync // Set MSR_ILE now PCI bus is endian swapping and interrupts are disabled mfmsr r7 lis r8, 1 or r7, r7, r8 mtmsr r7 isync // set up srr1 ready to set MSR_LE, disable MSR_IR|MSR_DR ori r7, r7, 1 rlwinm r7, r7, 0, 28, 25 mtsrr1 r7 mtsrr0 r29 // srr0 already set up // set the hwdesc arg (vaddr): oris r3, r31, 0x8000 // and rfi into le entrypoint rfi
Wack0/maciNTosh
3,599
arcunin/source/crtresxgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for restoring integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer restore area. */ CFI_STARTPROC CFI_DEF_CFA_REGISTER (11) CFI_OFFSET (65, 4) CFI_OFFSET (14, -72) CFI_OFFSET (15, -68) CFI_OFFSET (16, -64) CFI_OFFSET (17, -60) CFI_OFFSET (18, -56) CFI_OFFSET (19, -52) CFI_OFFSET (20, -48) CFI_OFFSET (21, -44) CFI_OFFSET (22, -40) CFI_OFFSET (23, -36) CFI_OFFSET (24, -32) CFI_OFFSET (25, -28) CFI_OFFSET (26, -24) CFI_OFFSET (27, -20) CFI_OFFSET (28, -16) CFI_OFFSET (29, -12) CFI_OFFSET (30, -8) CFI_OFFSET (31, -4) HIDDEN_FUNC(_restgpr_14_x) lwz 14,-72(11) /* restore gp registers */ CFI_RESTORE (14) HIDDEN_FUNC(_restgpr_15_x) lwz 15,-68(11) CFI_RESTORE (15) HIDDEN_FUNC(_restgpr_16_x) lwz 16,-64(11) CFI_RESTORE (16) HIDDEN_FUNC(_restgpr_17_x) lwz 17,-60(11) CFI_RESTORE (17) HIDDEN_FUNC(_restgpr_18_x) lwz 18,-56(11) CFI_RESTORE (18) HIDDEN_FUNC(_restgpr_19_x) lwz 19,-52(11) CFI_RESTORE (19) HIDDEN_FUNC(_restgpr_20_x) lwz 20,-48(11) CFI_RESTORE (20) HIDDEN_FUNC(_restgpr_21_x) lwz 21,-44(11) CFI_RESTORE (21) HIDDEN_FUNC(_restgpr_22_x) lwz 22,-40(11) CFI_RESTORE (22) HIDDEN_FUNC(_restgpr_23_x) lwz 23,-36(11) CFI_RESTORE (23) HIDDEN_FUNC(_restgpr_24_x) lwz 24,-32(11) CFI_RESTORE (24) HIDDEN_FUNC(_restgpr_25_x) lwz 25,-28(11) CFI_RESTORE (25) HIDDEN_FUNC(_restgpr_26_x) lwz 26,-24(11) CFI_RESTORE (26) HIDDEN_FUNC(_restgpr_27_x) lwz 27,-20(11) CFI_RESTORE (27) HIDDEN_FUNC(_restgpr_28_x) lwz 28,-16(11) CFI_RESTORE (28) HIDDEN_FUNC(_restgpr_29_x) lwz 29,-12(11) CFI_RESTORE (29) HIDDEN_FUNC(_restgpr_30_x) lwz 30,-8(11) CFI_RESTORE (30) HIDDEN_FUNC(_restgpr_31_x) lwz 0,4(11) lwz 31,-4(11) CFI_RESTORE (31) mtlr 0 CFI_RESTORE (65) mr 1,11 CFI_DEF_CFA_REGISTER (1) blr FUNC_END(_restgpr_31_x) FUNC_END(_restgpr_30_x) FUNC_END(_restgpr_29_x) FUNC_END(_restgpr_28_x) FUNC_END(_restgpr_27_x) FUNC_END(_restgpr_26_x) FUNC_END(_restgpr_25_x) FUNC_END(_restgpr_24_x) FUNC_END(_restgpr_23_x) FUNC_END(_restgpr_22_x) FUNC_END(_restgpr_21_x) FUNC_END(_restgpr_20_x) FUNC_END(_restgpr_19_x) FUNC_END(_restgpr_18_x) FUNC_END(_restgpr_17_x) FUNC_END(_restgpr_16_x) FUNC_END(_restgpr_15_x) FUNC_END(_restgpr_14_x) CFI_ENDPROC #endif
Wack0/maciNTosh
1,667
arcunin/source/exhandler_low.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern ArcBugcheck .extern RegisterSpace .globl BugcheckTrampoline BugcheckTrampoline: mtspr SPRG3, r31 lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l clrlwi r31, r31, 2 stw r0, 0(r31) mfsrr0 r0 stw r0, 128(r31) mfsrr1 r0 stw r0, 132(r31) lis r31, BugcheckHandler@h ori r31, r31, BugcheckHandler@l mtsrr0 r31 mfmsr r31 ori r31,r31,MSR_IR|MSR_DR mtsrr1 r31 mfspr r31, SPRG3 rfi .globl BugcheckHandler BugcheckHandler: lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l //stw r0, 0(r31) stw r1, 4(r31) stw r2, 8(r31) stw r3, 12(r31) stw r4, 16(r31) stw r5, 20(r31) stw r6, 24(r31) stw r7, 28(r31) stw r8, 32(r31) stw r9, 36(r31) stw r10, 40(r31) stw r11, 44(r31) stw r12, 48(r31) stw r13, 52(r31) stw r14, 56(r31) stw r15, 60(r31) stw r16, 64(r31) stw r17, 68(r31) stw r18, 72(r31) stw r19, 76(r31) stw r20, 80(r31) stw r21, 84(r31) stw r22, 88(r31) stw r23, 92(r31) stw r24, 96(r31) stw r25, 100(r31) stw r26, 104(r31) stw r27, 108(r31) stw r28, 112(r31) stw r29, 116(r31) stw r30, 120(r31) stw r31, 124(r31) //mfspr r4, 26 //stw r4, 128(r31) //mfspr r4, 27 //stw r4, 132(r31) //mfspr r4, CR //stw r4, 136(r31) mfspr r4, 8 stw r4, 140(r31) mfspr r4, 9 stw r4, 144(r31) mfspr r4, 1 stw r4, 148(r31) mfspr r4, 19 stw r4, 152(r31) mfspr r4, 18 stw r4, 156(r31) mfspr r4, 25 stw r4, 160(r31) mr r3, r31 b ArcBugcheck
Wack0/maciNTosh
4,945
arcunin/source/floatctx.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .set FP_SIZE, 8 .set GP_SRR0, (SRR0_OFFSET - 8) .set GP_SRR1, (GP_SRR0 + 4) .set GP_1, (GPR1_OFFSET - 8) .set GP_2, (GP_1 + 4) #ifdef _DEBUG .set GP_5, (GPR5_OFFSET - 8) .set GP_6, (GP_5 + 4) #endif .set GP_13, (GPR13_OFFSET - 8) .set GP_14, (GP_13 + 4) .set GP_15, (GP_14 + 4) .set GP_16, (GP_15 + 4) .set GP_17, (GP_16 + 4) .set GP_18, (GP_17 + 4) .set GP_19, (GP_18 + 4) .set GP_20, (GP_19 + 4) .set GP_21, (GP_20 + 4) .set GP_22, (GP_21 + 4) .set GP_23, (GP_22 + 4) .set GP_24, (GP_23 + 4) .set GP_25, (GP_24 + 4) .set GP_26, (GP_25 + 4) .set GP_27, (GP_26 + 4) .set GP_28, (GP_27 + 4) .set GP_29, (GP_28 + 4) .set GP_30, (GP_29 + 4) .set GP_31, (GP_30 + 4) .set GQ_0, (GP_31 + 4) .set GQ_1, (GQ_0 + 4) .set GQ_2, (GQ_1 + 4) .set GQ_3, (GQ_2 + 4) .set GQ_4, (GQ_3 + 4) .set GQ_5, (GQ_4 + 4) .set GQ_6, (GQ_5 + 4) .set GQ_7, (GQ_6 + 4) .set GP_CR, (GQ_7 + 4) .set GP_LR, (GP_CR + 4) .set GP_CTR, (GP_LR + 4) .set GP_XER, (GP_CTR + 4) .set GP_MSR, (GP_XER + 4) .set GP_DAR, (GP_MSR + 4) .set STATE, (GP_DAR + 4) .set MODE, (STATE + 2) .set FP_0, (FPR0_OFFSET - 8) .set FP_1, (FP_0 + FP_SIZE) .set FP_2, (FP_1 + FP_SIZE) .set FP_3, (FP_2 + FP_SIZE) .set FP_4, (FP_3 + FP_SIZE) .set FP_5, (FP_4 + FP_SIZE) .set FP_6, (FP_5 + FP_SIZE) .set FP_7, (FP_6 + FP_SIZE) .set FP_8, (FP_7 + FP_SIZE) .set FP_9, (FP_8 + FP_SIZE) .set FP_10, (FP_9 + FP_SIZE) .set FP_11, (FP_10 + FP_SIZE) .set FP_12, (FP_11 + FP_SIZE) .set FP_13, (FP_12 + FP_SIZE) .set FP_14, (FP_13 + FP_SIZE) .set FP_15, (FP_14 + FP_SIZE) .set FP_16, (FP_15 + FP_SIZE) .set FP_17, (FP_16 + FP_SIZE) .set FP_18, (FP_17 + FP_SIZE) .set FP_19, (FP_18 + FP_SIZE) .set FP_20, (FP_19 + FP_SIZE) .set FP_21, (FP_20 + FP_SIZE) .set FP_22, (FP_21 + FP_SIZE) .set FP_23, (FP_22 + FP_SIZE) .set FP_24, (FP_23 + FP_SIZE) .set FP_25, (FP_24 + FP_SIZE) .set FP_26, (FP_25 + FP_SIZE) .set FP_27, (FP_26 + FP_SIZE) .set FP_28, (FP_27 + FP_SIZE) .set FP_29, (FP_28 + FP_SIZE) .set FP_30, (FP_29 + FP_SIZE) .set FP_31, (FP_30 + FP_SIZE) .set FP_FPSCR, (FP_31 + FP_SIZE) .set PSFP_0, (FP_FPSCR + FP_SIZE) .set PSFP_1, (PSFP_0 + FP_SIZE) .set PSFP_2, (PSFP_1 + FP_SIZE) .set PSFP_3, (PSFP_2 + FP_SIZE) .set PSFP_4, (PSFP_3 + FP_SIZE) .set PSFP_5, (PSFP_4 + FP_SIZE) .set PSFP_6, (PSFP_5 + FP_SIZE) .set PSFP_7, (PSFP_6 + FP_SIZE) .set PSFP_8, (PSFP_7 + FP_SIZE) .set PSFP_9, (PSFP_8 + FP_SIZE) .set PSFP_10, (PSFP_9 + FP_SIZE) .set PSFP_11, (PSFP_10 + FP_SIZE) .set PSFP_12, (PSFP_11 + FP_SIZE) .set PSFP_13, (PSFP_12 + FP_SIZE) .set PSFP_14, (PSFP_13 + FP_SIZE) .set PSFP_15, (PSFP_14 + FP_SIZE) .set PSFP_16, (PSFP_15 + FP_SIZE) .set PSFP_17, (PSFP_16 + FP_SIZE) .set PSFP_18, (PSFP_17 + FP_SIZE) .set PSFP_19, (PSFP_18 + FP_SIZE) .set PSFP_20, (PSFP_19 + FP_SIZE) .set PSFP_21, (PSFP_20 + FP_SIZE) .set PSFP_22, (PSFP_21 + FP_SIZE) .set PSFP_23, (PSFP_22 + FP_SIZE) .set PSFP_24, (PSFP_23 + FP_SIZE) .set PSFP_25, (PSFP_24 + FP_SIZE) .set PSFP_26, (PSFP_25 + FP_SIZE) .set PSFP_27, (PSFP_26 + FP_SIZE) .set PSFP_28, (PSFP_27 + FP_SIZE) .set PSFP_29, (PSFP_28 + FP_SIZE) .set PSFP_30, (PSFP_29 + FP_SIZE) .set PSFP_31, (PSFP_30 + FP_SIZE) .align 5 .globl _cpu_context_save_fp _cpu_context_save_fp: lhz r4,STATE(r3) ori r4,r4,0x0001 sth r4,STATE(r3) stfd fr0, FP_0(r3) stfd fr1, FP_1(r3) stfd fr2, FP_2(r3) stfd fr3, FP_3(r3) stfd fr4, FP_4(r3) stfd fr5, FP_5(r3) stfd fr6, FP_6(r3) stfd fr7, FP_7(r3) stfd fr8, FP_8(r3) stfd fr9, FP_9(r3) stfd fr10, FP_10(r3) stfd fr11, FP_11(r3) stfd fr12, FP_12(r3) stfd fr13, FP_13(r3) stfd fr14, FP_14(r3) stfd fr15, FP_15(r3) stfd fr16, FP_16(r3) stfd fr17, FP_17(r3) stfd fr18, FP_18(r3) stfd fr19, FP_19(r3) stfd fr20, FP_20(r3) stfd fr21, FP_21(r3) stfd fr22, FP_22(r3) stfd fr23, FP_23(r3) stfd fr24, FP_24(r3) stfd fr25, FP_25(r3) stfd fr26, FP_26(r3) stfd fr27, FP_27(r3) stfd fr28, FP_28(r3) stfd fr29, FP_29(r3) stfd fr30, FP_30(r3) stfd fr31, FP_31(r3) mffs fr0 stfd fr0, FP_FPSCR(r3) lfd fr0, FP_0(r3) 1: blr .align 5 .globl _cpu_context_restore_fp _cpu_context_restore_fp: lhz r4,STATE(r3) clrlwi. r4,r4,31 beq 2f lfd fr0, FP_FPSCR(r3) mtfsf 255, fr0 lfd fr0, FP_0(r3) lfd fr1, FP_1(r3) lfd fr2, FP_2(r3) lfd fr3, FP_3(r3) lfd fr4, FP_4(r3) lfd fr5, FP_5(r3) lfd fr6, FP_6(r3) lfd fr7, FP_7(r3) lfd fr8, FP_8(r3) lfd fr9, FP_9(r3) lfd fr10, FP_10(r3) lfd fr11, FP_11(r3) lfd fr12, FP_12(r3) lfd fr13, FP_13(r3) lfd fr14, FP_14(r3) lfd fr15, FP_15(r3) lfd fr16, FP_16(r3) lfd fr17, FP_17(r3) lfd fr18, FP_18(r3) lfd fr19, FP_19(r3) lfd fr20, FP_20(r3) lfd fr21, FP_21(r3) lfd fr22, FP_22(r3) lfd fr23, FP_23(r3) lfd fr24, FP_24(r3) lfd fr25, FP_25(r3) lfd fr26, FP_26(r3) lfd fr27, FP_27(r3) lfd fr28, FP_28(r3) lfd fr29, FP_29(r3) lfd fr30, FP_30(r3) lfd fr31, FP_31(r3) 2: blr
Wack0/maciNTosh
1,163
arcunin/source/arcinvoke.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global __ArcInvokeImpl __ArcInvokeImpl: mflr r0 stwu r0, -4(r1) mtctr r3 mr r2, r4 mr r3, r5 mr r4, r6 mr r5, r7 bctrl lwzu r0, 0(r1) addi r1, r1, 4 mtlr r0 blr .globl DCFlushRangeNoSync DCFlushRangeNoSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b blr .globl ICInvalidateRange ICInvalidateRange: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: icbi r0, r3 addi r3, r3, 0x20 bdnz 2b sync isync blr .globl DCFlushRangeInlineSync DCFlushRangeInlineSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b mfspr r3,HID0 ori r4,r3,0x0008 mtspr HID0,r4 isync sync mtspr HID0,r3 blr
Wack0/maciNTosh
6,162
arcunin/source/crt0.S
// Startup code. // Exception handlers are adapted from OpenBIOS: /* * Creation Date: <2001/06/16 21:30:18 samuel> * Time-stamp: <2003/04/04 16:32:06 samuel> * * <init.S> * * Asm glue for ELF images run inside MOL * * Copyright (C) 2001, 2002, 2003 Samuel Rydh (samuel@ibrium.se) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation * */ #define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern FwMain .extern __executable_start .globl _start _start: // We are currently in little endian mode, // in non-translated mode, // with interrupts disabled. // quick debug test. are we getting here? // r28=ffff_ffff, r30=physaddr of framebuffer //stw r28, 0(r30) //stw r28, 4(r30) //stw r28, 8(r30) //stw r28, 0xc(r30) // r3 is the physical address of our hardware description struct. // Do not bother touching it right now. // In fact, save it in a higher register: mr r31, r3 // Same for framebuffer physical address (top 4 bits): mr r30, r4 // Following init code comes from libogc: // clear all BATs li r0,0 mtspr IBAT0U,r0; mtspr IBAT1U,r0; mtspr IBAT2U,r0; mtspr IBAT3U,r0 // IBAT0...3 mtspr DBAT0U,r0; mtspr DBAT1U,r0; mtspr DBAT2U,r0; mtspr DBAT3U,r0 // DBAT0...3 isync // Invalidate all TLBs // Comes from mario kart wii forum - ppc pagetable tutorial // Open Firmware used pagetables so TLBs have been used so invalidate them: li r0,64 li r3,0 // Wipe SDR1 here: sync mtspr 25, r3 isync mtctr r0 invalidate_tlb_loop: tlbie r3 addi r3, r3, 0x1000 bdnz+ invalidate_tlb_loop after_invalidate_tlb: tlbsync // clear all SRs lis r0,0x8000 mtsr 0,r0; mtsr 1,r0; mtsr 2,r0; mtsr 3,r0; mtsr 4,r0; mtsr 5,r0; mtsr 6,r0 mtsr 7,r0; mtsr 8,r0; mtsr 9,r0; mtsr 10,r0; mtsr 11,r0; mtsr 12,r0; mtsr 13,r0 mtsr 14,r0; mtsr 15,r0 isync // set DBAT0 and IBAT0: // 0x8000_0000 + 256MB => physical 0x0000_0000 (cached, r+w) li r3,2 lis r4,0x8000 ori r4,r4,0x1fff mtspr IBAT0L,r3 mtspr IBAT0U,r4 mtspr DBAT0L,r3 mtspr DBAT0U,r4 isync // A BAT has been set to map the first 256MB, that should be more than enough for ARC firmware purposes. // When the ARC firmware memory map, just set any memory above 256MB if present as firmware temporary, // In this case, boot loaders will not use it; but NT kernel indeed can. // set DBAT1: // 0x7000_0000 + 256MB => physical 0x0000_0000 (uncached, r+w) li r3, 0x2a lis r4, 0x7000 ori r4, r4, 0x1fff mtspr DBAT1L, r3 mtspr DBAT1U, r4 isync // set DBAT2: // 0x6000_0000 + 256MB => physical 0x8000_0000 (uncached, r+w) lis r3, 0x8000 ori r3, r3, 0x2a lis r4, 0x6000 ori r4, r4, 0x1fff mtspr DBAT2L, r3 mtspr DBAT2U, r4 isync // DBAT3 is used for whatever PCI access, set up by DSI exception handler. // Map the 256MB of physical memory containing the framebuffer using DBAT3. // Any system that doesn't use MMIO outside of these mapped BATs will therefore not need to use the DSI exception handler at all. mr r3, r30 ori r3, r3, 0x2a mr r4, r30 ori r4, r4, 0x1fff mtspr DBAT3L, r3 mtspr DBAT3U, r4 isync // set up a stack: // we are at 9MB, use ram before it for stack. // this way we can set up 1MB at 8MB as firmware temporary. lis r1, __executable_start@h ori r1, r1, __executable_start@l subi r1, r1, 8 // copy vector_dsi to 0x300 li r0, (vector_dsi_end - vector_dsi) / 4 lis r3, vector_dsi@h ori r3, r3, vector_dsi@l rlwinm r3, r3, 0, 1, 31 li r4, 0x300 bl copy_32 li r0, (vector_dsi_end - vector_dsi) / 32 li r3, 0x300 bl cache_invalidate #if 0 // ISI isn't needed, we only want to map PCI address space for data, not for instruction. // copy vector_isi to 0x400 li r0, (vector_isi_end - vector_isi) / 4 lis r3, vector_isi@h ori r3, r3, vector_isi@l rlwinm r3, r3, 0, 1, 31 li r4, 0x400 bl copy_32 li r0, (vector_isi_end - vector_isi) / 32 li r3, 0x400 bl cache_invalidate #endif // switch into translated mode and jump to FwMain mr r3, r31 oris r3, r3, 0x8000 lis r5, FwMain@h ori r5, r5, FwMain@l mtsrr0 r5 mfmsr r4 ori r4, r4, MSR_DR|MSR_IR mtsrr1 r4 rfi copy_32: // r0=length, r3=src, r4=dest mtctr r0 copy_loop: lwz r0,0(r3) stw r0,0(r4) addi r3,r3,4 addi r4,r4,4 bdnz+ copy_loop blr cache_invalidate: // r0=length, r3=dest mtctr r0 cache_loop: dcbst 0, r3 sync icbi 0, r3 addi r3,r3,32 bdnz+ cache_loop blr // DSI and ISI exceptions .extern dsi_exception #if 0 .extern isi_exception #endif exception_return: addi r1,r1,16 // pop ABI frame lwz r0,52(r1) mtlr r0 lwz r0,56(r1) mtcr r0 lwz r0,60(r1) mtctr r0 lwz r0,64(r1) mtxer r0 lwz r0,0(r1) // restore r0 lwz r2,8(r1) // restore r2 lwz r3,12(r1) // restore r3 lwz r4,16(r1) lwz r5,20(r1) lwz r6,24(r1) lwz r7,28(r1) lwz r8,32(r1) lwz r9,36(r1) lwz r10,40(r1) lwz r11,44(r1) lwz r12,48(r1) lwz r1,4(r1) // restore r1 rfi #define EXCEPTION_PROLOGUE \ mtsprg1 r1 ; /* scratch */ \ rlwinm r1, r1, 0,1,31 ; /* convert stack pointer to physical address */ \ addi r1,r1,-80 ; /* push exception frame */ \ \ stw r0,0(r1) ; /* save r0 */ \ mfsprg1 r0 ; \ stw r0,4(r1) ; /* save r1 */ \ stw r2,8(r1) ; /* save r2 */ \ stw r3,12(r1) ; /* save r3 */ \ stw r4,16(r1) ; \ stw r5,20(r1) ; \ stw r6,24(r1) ; \ stw r7,28(r1) ; \ stw r8,32(r1) ; \ stw r9,36(r1) ; \ stw r10,40(r1) ; \ stw r11,44(r1) ; \ stw r12,48(r1) ; \ \ mflr r0 ; \ stw r0,52(r1) ; \ mfcr r0 ; \ stw r0,56(r1) ; \ mfctr r0 ; \ stw r0,60(r1) ; \ mfxer r0 ; \ stw r0,64(r1) ; \ \ /* 76(r1) unused */ \ addi r1,r1,-16 ; /* call conventions uses 0(r1) and 4(r1)... */ #define EXCEPTION_EPILOGUE \ lis r3, exception_return@h ; \ ori r3, r3, exception_return@l ; \ rlwinm r3, r3, 0, 1, 31 ; \ mtctr r3 ; \ bctr ; vector_dsi: EXCEPTION_PROLOGUE lis r3, dsi_exception@h ori r3, r3, dsi_exception@l rlwinm r3, r3, 0, 1, 31 mtctr r3 bctrl EXCEPTION_EPILOGUE vector_dsi_end: #if 0 vector_isi: EXCEPTION_PROLOGUE lis r3, isi_exception@h ori r3, r3, isi_exception@l rlwinm r3, r3, 0, 1, 31 mtctr r3 bctrl EXCEPTION_EPILOGUE vector_isi_end: #endif
Wack0/maciNTosh
2,709
arcunin/source/crtsavgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for saving integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer save area. */ CFI_STARTPROC HIDDEN_FUNC(_savegpr_14) stw 14,-72(11) /* save gp registers */ HIDDEN_FUNC(_savegpr_15) stw 15,-68(11) HIDDEN_FUNC(_savegpr_16) stw 16,-64(11) HIDDEN_FUNC(_savegpr_17) stw 17,-60(11) HIDDEN_FUNC(_savegpr_18) stw 18,-56(11) HIDDEN_FUNC(_savegpr_19) stw 19,-52(11) HIDDEN_FUNC(_savegpr_20) stw 20,-48(11) HIDDEN_FUNC(_savegpr_21) stw 21,-44(11) HIDDEN_FUNC(_savegpr_22) stw 22,-40(11) HIDDEN_FUNC(_savegpr_23) stw 23,-36(11) HIDDEN_FUNC(_savegpr_24) stw 24,-32(11) HIDDEN_FUNC(_savegpr_25) stw 25,-28(11) HIDDEN_FUNC(_savegpr_26) stw 26,-24(11) HIDDEN_FUNC(_savegpr_27) stw 27,-20(11) HIDDEN_FUNC(_savegpr_28) stw 28,-16(11) HIDDEN_FUNC(_savegpr_29) stw 29,-12(11) HIDDEN_FUNC(_savegpr_30) stw 30,-8(11) HIDDEN_FUNC(_savegpr_31) stw 31,-4(11) blr FUNC_END(_savegpr_31) FUNC_END(_savegpr_30) FUNC_END(_savegpr_29) FUNC_END(_savegpr_28) FUNC_END(_savegpr_27) FUNC_END(_savegpr_26) FUNC_END(_savegpr_25) FUNC_END(_savegpr_24) FUNC_END(_savegpr_23) FUNC_END(_savegpr_22) FUNC_END(_savegpr_21) FUNC_END(_savegpr_20) FUNC_END(_savegpr_19) FUNC_END(_savegpr_18) FUNC_END(_savegpr_17) FUNC_END(_savegpr_16) FUNC_END(_savegpr_15) FUNC_END(_savegpr_14) CFI_ENDPROC #endif
Wack0/maciNTosh
1,400
arcloaderold_grackle/source/modeswitch.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global .ModeSwitchEntry .csect .text[PR] .skip 0x800 .ModeSwitchEntry: // (ArcFirmEntry Start, PHW_DESCRIPTION HwDesc) // save our arguments // r3 (le entrypoint) into srr0 mr r29, r3 // r4 (argument) into r31 mr r31, r4 mr r30, r5 li r28,-1 #if 0 // Already done by privesc. // Disable interrupts. mfmsr r7 rlwinm r8, r7, 0, 17, 15 mtmsr r8 isync #endif // r4 = CONFIG_ADDR lis r4, 0xFEC0 ori r4, r4, 4 // r5 = CONFIG_DATA addis r5, r4, 0x20 // r6 = PICR1 addr lis r6, 0x8000 ori r6, r6, 0x00A8 // Ensure we can access grackle pci config registers through the MMU: lwbrx r0,0,r4 lwbrx r0,0,r5 // All exceptions lead to infinite loop. No exceptions. li r0,0x10 mtctr r0 li r7,0 lis r8, 0x4800 // b . exception_wipe_loop: stw r8, 4(r7) addi r7, r7, 0x100 bdnz+ exception_wipe_loop // Set up grackle to r/w PICR1 stwbrx r6,0,r4 eieio sync lwbrx r0,0,r4 sync // Set PICR1_LE_MODE in PICR1 lwbrx r7,0,r5 sync ori r7,r7,0x20 stwbrx r7,0,r5 eieio sync // Set MSR_ILE now PCI bus is endian swapping and interrupts are disabled mfmsr r7 lis r8, 1 or r7, r7, r8 mtmsr r7 isync // set up srr1 ready to set MSR_LE, disable MSR_IR|MSR_DR ori r7, r7, 1 rlwinm r7, r7, 0, 28, 25 mtsrr1 r7 mtsrr0 r29 // srr0 already set up // set the hwdesc arg (vaddr): oris r3, r31, 0x8000 // and rfi into le entrypoint rfi
Wack0/paid-the-beak
3,413
exploit2dev.s
.arm.big .create "exploit2dev.bin", 0 .incbin "header.ancast" .align 0x80000 ; Toucan image header .word 0xfd9b5b7a ; magic .word 3 ; section count .word 0x01808000, 0x01808800 ; some space in Napa to clobber .word 0 ; flags .word 0 ; syscfg1 (unused as flag for that is unset) .word 0, 0 ; unused ; Section headers .word 0x0d400700 ; address of code to overwrite in boot1 based at 0x0d400000 .word section1end-section1 ; size .word 0x08000500 ; address of code to overwrite in boot1 based at 0x08000000 .word section2end-section2 ; size .word 0 ; address of payload .word section3end-section3 ; size .align 0x20 ; Section data .thumb section1: ; Overwrite 0x100 bytes with blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 section1end: .align 0x20 section2: ; Overwrite 0x100 bytes with blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 section2end: .align 0x20 section3: .thumb ldr r0, =0x01000200 ldr r1, [r0] ; load HdrSize add r0, r0, r1 ; r0 = ancast body + HdrSize blx r0 ; jump .pool section3end: .align 0x10000 .close
Wack0/paid-the-beak
3,411
exploit2.s
.arm.big .create "exploit2.bin", 0 .incbin "sdboot1.ancast" .align 0x80000 ; Toucan image header .word 0xfd9b5b7a ; magic .word 3 ; section count .word 0x01808000, 0x01808800 ; some space in Napa to clobber .word 0 ; flags .word 0 ; syscfg1 (unused as flag for that is unset) .word 0, 0 ; unused ; Section headers .word 0x0d400700 ; address of code to overwrite in boot1 based at 0x0d400000 .word section1end-section1 ; size .word 0x08000500 ; address of code to overwrite in boot1 based at 0x08000000 .word section2end-section2 ; size .word 0 ; address of payload .word section3end-section3 ; size .align 0x20 ; Section data .thumb section1: ; Overwrite 0x100 bytes with blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 section1end: .align 0x20 section2: ; Overwrite 0x100 bytes with blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 :: blx r0 section2end: .align 0x20 section3: .thumb ldr r0, =0x01000200 ldr r1, [r0] ; load HdrSize add r0, r0, r1 ; r0 = ancast body + HdrSize blx r0 ; jump .pool section3end: .align 0x10000 .close
Wack0/entii-for-workcubes
3,228
arcldr/source/modeswitch.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text ConfigBATsForArcImpl: // clear all BATs li r0,0 mtspr IBAT0U,r0; mtspr IBAT1U,r0; mtspr IBAT2U,r0; mtspr IBAT3U,r0 // IBAT0...3 mtspr DBAT0U,r0; mtspr DBAT1U,r0; mtspr DBAT2U,r0; mtspr DBAT3U,r0 // DBAT0...3 #ifdef HW_RVL mtspr IBAT4U,r0; mtspr IBAT5U,r0; mtspr IBAT6U,r0; mtspr IBAT7U,r0 // IBAT4...7 mtspr DBAT4U,r0; mtspr DBAT5U,r0; mtspr DBAT6U,r0; mtspr DBAT7U,r0 // DBAT4...7 #endif isync // Invalidate all TLBs // Comes from mario kart wii forum - ppc pagetable tutorial // Invalidate TLBs: li r0,64 li r3,0 // Wipe SDR1 here: sync mtspr 25, r3 isync mtctr r0 invalidate_tlb_loop: tlbie r3 addi r3, r3, 0x1000 bdnz+ invalidate_tlb_loop after_invalidate_tlb: tlbsync // clear all SRs lis r0,0x8000 mtsr 0,r0; mtsr 1,r0; mtsr 2,r0; mtsr 3,r0; mtsr 4,r0; mtsr 5,r0; mtsr 6,r0 mtsr 7,r0; mtsr 8,r0; mtsr 9,r0; mtsr 10,r0; mtsr 11,r0; mtsr 12,r0; mtsr 13,r0 mtsr 14,r0; mtsr 15,r0 isync // set DBAT0 and IBAT0: // 0x8000_0000 + 256MB => physical 0x0000_0000 (cached, r+w) li r3,2 lis r4,0x8000 ori r4,r4,0x1fff mtspr IBAT0L,r3 mtspr IBAT0U,r4 mtspr DBAT0L,r3 mtspr DBAT0U,r4 isync // set DBAT1 and IBAT1: // 0x9000_0000 + 256MB => physical 0x1000_0000 (cached, r+w) lis r3, 0x1000 ori r3, r3, 0x2 lis r4, 0x9000 ori r4, r4, 0x1fff mtspr IBAT1L,r3 mtspr IBAT1U,r4 mtspr DBAT1L,r3 mtspr DBAT1U,r4 isync // set DBAT2: // 0x6000_0000 + 256MB => physical 0x0000_0000 (uncached, r+w) li r3, 0x2a lis r4, 0x6000 ori r4, r4, 0x1fff mtspr DBAT2L, r3 mtspr DBAT2U, r4 isync // set DBAT3: // 0x7000_0000 + 256MB => physical 0x1000_0000 (uncached, r+w) lis r3, 0x1000 ori r3, r3, 0x2a lis r4, 0x7000 ori r4, r4, 0x1fff mtspr DBAT3L, r3 mtspr DBAT3U, r4 isync // disable upper BATS on wii #ifdef HW_RVL mfspr r3, HID4 rlwinm r3, r3, 0, 7, 5 mtspr HID4, r3 #endif mfmsr r3 ori r3,r3,MSR_DR|MSR_IR mtsrr1 r3 mflr r3 oris r3,r3,0x8000 mtsrr0 r3 rfi .extern __realmode ConfigBATsForArc: mflr r28 oris r28, r28, 0x8000 lis r3, ConfigBATsForArcImpl@h ori r3, r3, ConfigBATsForArcImpl@l bl __realmode mtlr r28 blr .global ModeSwitchEntry ModeSwitchEntry: // (ArcFirmEntry Start, PHW_DESCRIPTION HwDesc) // save our arguments // r3 (le entrypoint) into srr0 mr r29, r3 // r4 (argument) into r31 mr r31, r4 li r28,-1 // Disable interrupts. mfmsr r7 rlwinm r8, r7, 0, 17, 15 mtmsr r8 isync // Disable paired singles instructions. // Disable load/store quantized instructions. mfspr r7, HID2 rlwinm r8, r7, 0, 3, 1 rlwinm r8, r8, 0, 1, 31 mtspr HID2, r8 isync // All exceptions lead to infinite loop. No exceptions. li r0,0x10 mtctr r0 lis r7,0xc000 lis r8, 0x4800 // b . exception_wipe_loop: stw r8, 4(r7) addi r7, r7, 0x100 bdnz+ exception_wipe_loop // Hopefully we can get away with this: bl ConfigBATsForArc // Set MSR_ILE mfmsr r7 lis r8, 1 or r7, r7, r8 mtmsr r7 isync // set up srr1 ready to set MSR_LE, disable MSR_IR|MSR_DR ori r7, r7, 1 //rlwinm r7, r7, 0, 28, 25 mtsrr1 r7 oris r29, r29, 0x8000 mtsrr0 r29 // srr0 already set up // set the hwdesc arg (vaddr): oris r3, r31, 0x8000 mr r4, r30 // and rfi into le entrypoint rfi
Wack0/entii-for-workcubes
4,500
halartx/source/stall.s
// Timer SPR stuff #include "kxppc.h" #include "halasm.h" .extern HalpPerformanceFrequency // Registers // KeStallExecutionProcessor argument .set Microsecs, r.3 // READ_TB() reads the timebase registers to this pair of registers .set TimerLow32, r.4 .set TimerHigh32, r.5 // KeStallExecutionProcessor stores the timebase compare value to this pair of registers .set EndTimerLow32, r.6 .set EndTimerHigh32, r.7 // Two scratch registers used across this entire file .set Scratch, r.8 .set Scratch2, r.9 // KeQueryPerformanceCounter arguments .set RetPtr, r.3 .set Freq, r.4 // Timebase special purpose registers, used in HalpZeroPerformanceCounter .set TBLW, 284 .set TBUW, 285 // Reads the timebase registers. Clobbers scratch register. #define READ_TB() \ /* read timer registers */ \ mftbu TimerHigh32 ; \ mftb TimerLow32 ; \ /* ensure TimerHigh32 didn't tick over */ \ mftbu Scratch ; \ cmplw Scratch, TimerHigh32 ; \ bne- $ - (4*4) ; /* the things to do to not specify a label here */ // Puts HalpPerformanceFrequency into scratch register #define GET_PERF_FREQ() \ /* read address */ \ lwz Scratch, [toc]HalpPerformanceFrequency(r.toc) ; \ lwz Scratch, 0(Scratch) // Stalls execution for at least the specified number of microseconds: // void KeStallExecutionProcessor(ULONG Microseconds) LEAF_ENTRY(KeStallExecutionProcessor) // if Microsecs == 0 then do nothing cmplwi Microsecs, 0 beqlr- READ_TB() GET_PERF_FREQ() // Microsecs * PerformanceFrequency mullw EndTimerLow32,Microsecs,Scratch mulhwu. EndTimerHigh32,Microsecs,Scratch bne StallDiv64 // divided by 1000000 (high bits are zero, so just do 32-bit div) LWI(Scratch, 1000000) divwu EndTimerLow32,EndTimerLow32,Scratch b StallAfterDiv // High bits are non-zero, use the optimisation present in other powerpc HALs // Basically, instead of expensive 64-bit div, // shift right by 20 (ie, divide by 0x100000) // and add (shifted value / 16) // Sacrifices accuracy for speed (computed value is ~1% higher than expected), // but this function is specified to stall for "at least" the passed in value // ("waits for at least the specified usecs count, but not significantly longer") // and is only meant to be called for small values anyway // ("you must minimize the stall interval, typically to less than 50 usecs") // so this is fine. StallDiv64: mr Scratch, EndTimerHigh32 srwi EndTimerLow32, EndTimerLow32, 20 srwi EndTimerHigh32, EndTimerHigh32, 20 insrwi EndTimerLow32, Scratch, 20, 0 srwi Scratch2, EndTimerLow32, 4 srwi Scratch, EndTimerHigh32, 4 insrwi Scratch2, EndTimerHigh32, 4, 0 addc EndTimerLow32, EndTimerLow32, Scratch2 adde EndTimerHigh32, EndTimerHigh32, Scratch // Add to the read timebase registers StallAfterDiv: addc EndTimerLow32,EndTimerLow32,TimerLow32 adde EndTimerHigh32,EndTimerHigh32,TimerHigh32 // And spin until timebase reaches that value StallSpinLoop: READ_TB() cmplw TimerHigh32, EndTimerHigh32 blt- StallSpinLoop bgt+ StallDone cmplw TimerLow32, EndTimerLow32 blt StallSpinLoop StallDone: LEAF_EXIT(KeStallExecutionProcessor) // Supplies a 64-bit realtime counter. // void KeQueryPerformanceCounter(PULARGE_INTEGER RetPtr, PLARGE_INTEGER PerformanceFrequency) LEAF_ENTRY(KeQueryPerformanceCounter) // If PerformanceFrequency pointer is NULL don't try to write there cmplwi Freq, 0 beq QueryWrittenPerfFreq GET_PERF_FREQ() li Scratch2, 0 stw Scratch, 0(Freq) stw Scratch2, 4(Freq) // Read the timebase registers and write to RetPtr QueryWrittenPerfFreq: READ_TB() stw TimerLow32, 0(RetPtr) stw TimerHigh32, 4(RetPtr) LEAF_EXIT(KeQueryPerformanceCounter) // Zero the timebase registers LEAF_ENTRY(HalpZeroPerformanceCounter) li r.3, 0 mtspr TBLW, r.3 mtspr TBUW, r.3 LEAF_EXIT(HalpZeroPerformanceCounter) // Read the timebase registers and return in r3-r4 LEAF_ENTRY(HalpReadTimeBase) READ_TB() mr r.3, TimerLow32 mr r.4, TimerHigh32 LEAF_EXIT(HalpReadTimeBase)
Wack0/entii-for-workcubes
4,214
halartx/source/cache.s
// Implement cache flushing on Arthur derivatives // (Gekko, Broadway, Espresso) #include <kxppc.h> // Override the workaround for a different processor's errata #undef DISABLE_INTERRUPTS #undef ENABLE_INTERRUPTS #define DISABLE_INTERRUPTS(p0, s0) \ mfmsr p0 ; \ rlwinm s0,p0,0,~MASK_SPR(MSR_EE,1) ; \ mtmsr s0 ; #define ENABLE_INTERRUPTS(p0) \ mtmsr p0 .set HID0_ICFI, 0x0800 .set HID0, 1008 .set BLOCK_SIZE, 32 .set BLOCK_LOG2, 5 .set DCACHE_LINES, (32 * 1024) >> 5 // Data cache size in lines .set BASE, 0x80000000 // valid cached virtual address // HalSweepDcache(): flush the entire dcache LEAF_ENTRY(HalSweepDcache) li r.4, DCACHE_LINES // Get a valid virtual address LWI (r.3, BASE) // Read memory on block sizes to make sure it all ends up in the cache mtctr r.4 DISABLE_INTERRUPTS(r.10,r.12) sync subi r.6, r.3, BLOCK_SIZE FillLoop: lbzu r.0, BLOCK_SIZE(r.6) bdnz FillLoop ENABLE_INTERRUPTS(r.10) // And flush it out of dcache mtctr r.4 FlushRange: dcbf r.0, r.3 addi r.3, r.3, 0x20 bdnz FlushRange subi r.3, r.3, 0x20 dcbf r.0, r.3 sync eieio LEAF_EXIT(HalSweepDcache) // HalSweepDcacheRange(PVOID address, ULONG length): flush dcache for address range LEAF_ENTRY(HalSweepDcacheRange) andi. r.5, r.3, BLOCK_SIZE-1 or. r.4, r.4, r.4 addi r.4, r.4, BLOCK_SIZE-1 add r.4, r.4, r.5 srwi r.4, r.4, BLOCK_LOG2 // if length is zero, do nothing beqlr- mtctr r.4 sync b FlushRange LEAF_EXIT(HalSweepDcacheRange) // Invalidate dcache for given range. // Same args as for HalSweepDcacheRange. LEAF_ENTRY(HalpInvalidateDcacheRange) andi. r.5, r.3, BLOCK_SIZE-1 or. r.4, r.4, r.4 addi r.4, r.4, BLOCK_SIZE-1 add r.4, r.4, r.5 srwi r.4, r.4, BLOCK_LOG2 // if length is zero, do nothing beqlr- mtctr r.4 sync InvalidateRange: dcbi r.0, r.3 addi r.3, r.3, 0x20 bdnz InvalidateRange LEAF_EXIT(HalpInvalidateDcacheRange) // HalSweepIcache: invalidate all of icache LEAF_ENTRY(HalSweepIcache) FlashInvalidateIcache: mfspr r.3, HID0 ori r.4, r.3, HID0_ICFI isync mtspr HID0, r.4 LEAF_EXIT(HalSweepIcache) // HalSweepIcacheRange(PVOID address, ULONG length): // invalidate icache for given range LEAF_ENTRY(HalSweepIcacheRange) andi. r.5, r.3, BLOCK_SIZE-1 or. r.4, r.4, r.4 addi r.4, r.4, BLOCK_SIZE-1 add r.4, r.4, r.5 srwi r.4, r.4, BLOCK_LOG2 // if length is zero, do nothing beqlr- mtctr r.4 DISABLE_INTERRUPTS(r.10,r.12) InvalidateIcache: icbi 0, r.3 sync addi r.3, r.3, BLOCK_SIZE bdnz InvalidateIcache sync isync ENABLE_INTERRUPTS(r.10) LEAF_EXIT(HalSweepIcacheRange) // Flush physaddr+length to caches. // r3 = start physical page // r4 = start offset within page // r5 = bytelength // r6 = TRUE if should also flush dcache .set PAGE_SHIFT, 12 LEAF_ENTRY(HalpSweepPhysicalRange) // Convert from page number and offset to physical address. rlwimi r.4, r.3, PAGE_SHIFT, 0xfffff000 // Align to cache block. addi r.5, r.5, 31 srwi r.5, r.5, 5 // Save return address and set loop count. mflr r.0 mtctr r.5 // Disable interrupts, we need srr0 and srr1 DISABLE_INTERRUPTS(r.12, r.11) // Turn off virtual memory. bl hspr hspr: // Get physical address of hspr into a register. mflr r.7 rlwinm r.7, r.7, 0, 0x7fffffff // Add the offset to return address (in physical memory) addi r.7, r.7, hspr.phys - hspr // Ensure everything above here is complete. sync // Far jump to physical address. mtsrr0 r.7 rlwinm r.11, r.11, 0, ~0x30 // turn off MSR[IR] and MSR[DR] mtsrr1 r.11 rfi hspr.phys: mtsrr0 r.0 // set return address mtsrr1 r.12 // set old MSR // Do the comparison early, the cr won't change. cmpli 0, 0, r.6, 0 hspr.loop: // If caller didn't want dcache flush, branch past it. beq hspr.afterdcache dcbst 0, r.4 // flush dcache hspr.afterdcache: icbi 0, r.4 // invalidate icache addi r.4, r.4, 32 // next block bdnz hspr.loop // continue loop // memory + speculation barrier sync isync // return back to caller with translation on rfi DUMMY_EXIT(HalpSweepPhysicalRange)
Wack0/entii-for-workcubes
1,141
halartx/source/procreset.s
// Initialise other processor coming out of reset. #include <kxppc.h> .text .align 2 .globl HalpProcessorReset HalpProcessorReset: // Write to HW_VISOLID (a value without bit 0 set so it doesn't enable it) // to tell CPU 0 that this processor is running. lis r.6, 0x0d80 stw r.6, 0x20(r.6) // 0x24 swizzle for 32-bit == 0x24 ^ 4 == 0x20 sync // Set HID0 lis r.6, 0x0011 ori r.6, r.6, 0x0024 mtspr 1008, r.6 // set HID4 lis r.6, 0xb1b0 mtspr 1011, r.6 sync // set HID5 lis r.6, 0xE7FD ori r.6, r.6, 0xC000 mtspr 944, r.6 sync // enable caches lis r.6, 0x0011 ori r.6, r.6, 0xC024 mtspr 1008, r.6 isync // Initialise unused registers. r1 to r6 all got set by the code at the boot vector. li r.0, 0 li r.7, 0 li r.8, 0 li r.9, 0 li r.10, 0 li r.11, 0 li r.12, 0 li r.13, 0 li r.14, 0 li r.16, 0 li r.17, 0 li r.18, 0 li r.19, 0 li r.20, 0 li r.21, 0 li r.22, 0 li r.23, 0 li r.24, 0 li r.25, 0 li r.26, 0 li r.27, 0 li r.28, 0 li r.29, 0 li r.30, 0 li r.31, 0 // set MSR_ILE mfmsr r.6 oris r.6, r.6, 1 mtmsr r.6 isync // Long jump to kernel init. mtsrr0 r.2 mtsrr1 r.5 rfi
Wack0/entii-for-workcubes
1,145
halartx/source/bat.s
// Function to set an unused BAT. #include "kxppc.h" // NT only allocates IBAT/DBAT for the actual MEM1 size rounded up. // So for all of dol/rvl/cafe it would allocate 32MB cached BAT. // However, the entire 0x8xxxxxxx address space is reserved. // The rest of this 256MB range is unused. // Therefore, we can use a BAT to map PA 0x0c000000-0x0e000000 (32MB MMIO) uncached, // at 0x8C000000. // We also need to map the EFB by BAT. // Therefore, we can also map PA 0x08000000-0x08400000 (4MB MMIO) uncached, // at 0x88000000. // This function is used to set DBAT1 and DBAT2 to allow for this. LEAF_ENTRY(HalpSetMmioDbat) LWI(r.7, 0x8800007E) // base at 0x88000000, size = 4MB, kernel mode only LWI(r.6, 0x0800002A) // phys at 0x08000000, uncached, guarded, readwrite LWI(r.5, 0x8C0003FE) // base at 0x8C000000, size = 32MB, kernel mode only LWI(r.4, 0x0C00002A) // phys at 0x0C000000, uncached, guarded, readwrite // set invalid first just in case li r.3, 0 mtdbatu 1, r.3 mtdbatu 2, r.3 isync // set lower part first mtdbatl 1, r.4 mtdbatl 2, r.6 mtdbatu 1, r.5 mtdbatu 2, r.7 // barrier isync LEAF_EXIT(HalpSetMmioDbat)
Wack0/entii-for-workcubes
3,599
arcfw/source/crtresxgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for restoring integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer restore area. */ CFI_STARTPROC CFI_DEF_CFA_REGISTER (11) CFI_OFFSET (65, 4) CFI_OFFSET (14, -72) CFI_OFFSET (15, -68) CFI_OFFSET (16, -64) CFI_OFFSET (17, -60) CFI_OFFSET (18, -56) CFI_OFFSET (19, -52) CFI_OFFSET (20, -48) CFI_OFFSET (21, -44) CFI_OFFSET (22, -40) CFI_OFFSET (23, -36) CFI_OFFSET (24, -32) CFI_OFFSET (25, -28) CFI_OFFSET (26, -24) CFI_OFFSET (27, -20) CFI_OFFSET (28, -16) CFI_OFFSET (29, -12) CFI_OFFSET (30, -8) CFI_OFFSET (31, -4) HIDDEN_FUNC(_restgpr_14_x) lwz 14,-72(11) /* restore gp registers */ CFI_RESTORE (14) HIDDEN_FUNC(_restgpr_15_x) lwz 15,-68(11) CFI_RESTORE (15) HIDDEN_FUNC(_restgpr_16_x) lwz 16,-64(11) CFI_RESTORE (16) HIDDEN_FUNC(_restgpr_17_x) lwz 17,-60(11) CFI_RESTORE (17) HIDDEN_FUNC(_restgpr_18_x) lwz 18,-56(11) CFI_RESTORE (18) HIDDEN_FUNC(_restgpr_19_x) lwz 19,-52(11) CFI_RESTORE (19) HIDDEN_FUNC(_restgpr_20_x) lwz 20,-48(11) CFI_RESTORE (20) HIDDEN_FUNC(_restgpr_21_x) lwz 21,-44(11) CFI_RESTORE (21) HIDDEN_FUNC(_restgpr_22_x) lwz 22,-40(11) CFI_RESTORE (22) HIDDEN_FUNC(_restgpr_23_x) lwz 23,-36(11) CFI_RESTORE (23) HIDDEN_FUNC(_restgpr_24_x) lwz 24,-32(11) CFI_RESTORE (24) HIDDEN_FUNC(_restgpr_25_x) lwz 25,-28(11) CFI_RESTORE (25) HIDDEN_FUNC(_restgpr_26_x) lwz 26,-24(11) CFI_RESTORE (26) HIDDEN_FUNC(_restgpr_27_x) lwz 27,-20(11) CFI_RESTORE (27) HIDDEN_FUNC(_restgpr_28_x) lwz 28,-16(11) CFI_RESTORE (28) HIDDEN_FUNC(_restgpr_29_x) lwz 29,-12(11) CFI_RESTORE (29) HIDDEN_FUNC(_restgpr_30_x) lwz 30,-8(11) CFI_RESTORE (30) HIDDEN_FUNC(_restgpr_31_x) lwz 0,4(11) lwz 31,-4(11) CFI_RESTORE (31) mtlr 0 CFI_RESTORE (65) mr 1,11 CFI_DEF_CFA_REGISTER (1) blr FUNC_END(_restgpr_31_x) FUNC_END(_restgpr_30_x) FUNC_END(_restgpr_29_x) FUNC_END(_restgpr_28_x) FUNC_END(_restgpr_27_x) FUNC_END(_restgpr_26_x) FUNC_END(_restgpr_25_x) FUNC_END(_restgpr_24_x) FUNC_END(_restgpr_23_x) FUNC_END(_restgpr_22_x) FUNC_END(_restgpr_21_x) FUNC_END(_restgpr_20_x) FUNC_END(_restgpr_19_x) FUNC_END(_restgpr_18_x) FUNC_END(_restgpr_17_x) FUNC_END(_restgpr_16_x) FUNC_END(_restgpr_15_x) FUNC_END(_restgpr_14_x) CFI_ENDPROC #endif
Wack0/entii-for-workcubes
1,667
arcfw/source/exhandler_low.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern ArcBugcheck .extern RegisterSpace .globl BugcheckTrampoline BugcheckTrampoline: mtspr SPRG3, r31 lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l clrlwi r31, r31, 2 stw r0, 0(r31) mfsrr0 r0 stw r0, 128(r31) mfsrr1 r0 stw r0, 132(r31) lis r31, BugcheckHandler@h ori r31, r31, BugcheckHandler@l mtsrr0 r31 mfmsr r31 ori r31,r31,MSR_IR|MSR_DR mtsrr1 r31 mfspr r31, SPRG3 rfi .globl BugcheckHandler BugcheckHandler: lis r31, RegisterSpace@h ori r31, r31, RegisterSpace@l //stw r0, 0(r31) stw r1, 4(r31) stw r2, 8(r31) stw r3, 12(r31) stw r4, 16(r31) stw r5, 20(r31) stw r6, 24(r31) stw r7, 28(r31) stw r8, 32(r31) stw r9, 36(r31) stw r10, 40(r31) stw r11, 44(r31) stw r12, 48(r31) stw r13, 52(r31) stw r14, 56(r31) stw r15, 60(r31) stw r16, 64(r31) stw r17, 68(r31) stw r18, 72(r31) stw r19, 76(r31) stw r20, 80(r31) stw r21, 84(r31) stw r22, 88(r31) stw r23, 92(r31) stw r24, 96(r31) stw r25, 100(r31) stw r26, 104(r31) stw r27, 108(r31) stw r28, 112(r31) stw r29, 116(r31) stw r30, 120(r31) stw r31, 124(r31) //mfspr r4, 26 //stw r4, 128(r31) //mfspr r4, 27 //stw r4, 132(r31) //mfspr r4, CR //stw r4, 136(r31) mfspr r4, 8 stw r4, 140(r31) mfspr r4, 9 stw r4, 144(r31) mfspr r4, 1 stw r4, 148(r31) mfspr r4, 19 stw r4, 152(r31) mfspr r4, 18 stw r4, 156(r31) mfspr r4, 25 stw r4, 160(r31) mr r3, r31 b ArcBugcheck
Wack0/entii-for-workcubes
4,945
arcfw/source/floatctx.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .set FP_SIZE, 8 .set GP_SRR0, (SRR0_OFFSET - 8) .set GP_SRR1, (GP_SRR0 + 4) .set GP_1, (GPR1_OFFSET - 8) .set GP_2, (GP_1 + 4) #ifdef _DEBUG .set GP_5, (GPR5_OFFSET - 8) .set GP_6, (GP_5 + 4) #endif .set GP_13, (GPR13_OFFSET - 8) .set GP_14, (GP_13 + 4) .set GP_15, (GP_14 + 4) .set GP_16, (GP_15 + 4) .set GP_17, (GP_16 + 4) .set GP_18, (GP_17 + 4) .set GP_19, (GP_18 + 4) .set GP_20, (GP_19 + 4) .set GP_21, (GP_20 + 4) .set GP_22, (GP_21 + 4) .set GP_23, (GP_22 + 4) .set GP_24, (GP_23 + 4) .set GP_25, (GP_24 + 4) .set GP_26, (GP_25 + 4) .set GP_27, (GP_26 + 4) .set GP_28, (GP_27 + 4) .set GP_29, (GP_28 + 4) .set GP_30, (GP_29 + 4) .set GP_31, (GP_30 + 4) .set GQ_0, (GP_31 + 4) .set GQ_1, (GQ_0 + 4) .set GQ_2, (GQ_1 + 4) .set GQ_3, (GQ_2 + 4) .set GQ_4, (GQ_3 + 4) .set GQ_5, (GQ_4 + 4) .set GQ_6, (GQ_5 + 4) .set GQ_7, (GQ_6 + 4) .set GP_CR, (GQ_7 + 4) .set GP_LR, (GP_CR + 4) .set GP_CTR, (GP_LR + 4) .set GP_XER, (GP_CTR + 4) .set GP_MSR, (GP_XER + 4) .set GP_DAR, (GP_MSR + 4) .set STATE, (GP_DAR + 4) .set MODE, (STATE + 2) .set FP_0, (FPR0_OFFSET - 8) .set FP_1, (FP_0 + FP_SIZE) .set FP_2, (FP_1 + FP_SIZE) .set FP_3, (FP_2 + FP_SIZE) .set FP_4, (FP_3 + FP_SIZE) .set FP_5, (FP_4 + FP_SIZE) .set FP_6, (FP_5 + FP_SIZE) .set FP_7, (FP_6 + FP_SIZE) .set FP_8, (FP_7 + FP_SIZE) .set FP_9, (FP_8 + FP_SIZE) .set FP_10, (FP_9 + FP_SIZE) .set FP_11, (FP_10 + FP_SIZE) .set FP_12, (FP_11 + FP_SIZE) .set FP_13, (FP_12 + FP_SIZE) .set FP_14, (FP_13 + FP_SIZE) .set FP_15, (FP_14 + FP_SIZE) .set FP_16, (FP_15 + FP_SIZE) .set FP_17, (FP_16 + FP_SIZE) .set FP_18, (FP_17 + FP_SIZE) .set FP_19, (FP_18 + FP_SIZE) .set FP_20, (FP_19 + FP_SIZE) .set FP_21, (FP_20 + FP_SIZE) .set FP_22, (FP_21 + FP_SIZE) .set FP_23, (FP_22 + FP_SIZE) .set FP_24, (FP_23 + FP_SIZE) .set FP_25, (FP_24 + FP_SIZE) .set FP_26, (FP_25 + FP_SIZE) .set FP_27, (FP_26 + FP_SIZE) .set FP_28, (FP_27 + FP_SIZE) .set FP_29, (FP_28 + FP_SIZE) .set FP_30, (FP_29 + FP_SIZE) .set FP_31, (FP_30 + FP_SIZE) .set FP_FPSCR, (FP_31 + FP_SIZE) .set PSFP_0, (FP_FPSCR + FP_SIZE) .set PSFP_1, (PSFP_0 + FP_SIZE) .set PSFP_2, (PSFP_1 + FP_SIZE) .set PSFP_3, (PSFP_2 + FP_SIZE) .set PSFP_4, (PSFP_3 + FP_SIZE) .set PSFP_5, (PSFP_4 + FP_SIZE) .set PSFP_6, (PSFP_5 + FP_SIZE) .set PSFP_7, (PSFP_6 + FP_SIZE) .set PSFP_8, (PSFP_7 + FP_SIZE) .set PSFP_9, (PSFP_8 + FP_SIZE) .set PSFP_10, (PSFP_9 + FP_SIZE) .set PSFP_11, (PSFP_10 + FP_SIZE) .set PSFP_12, (PSFP_11 + FP_SIZE) .set PSFP_13, (PSFP_12 + FP_SIZE) .set PSFP_14, (PSFP_13 + FP_SIZE) .set PSFP_15, (PSFP_14 + FP_SIZE) .set PSFP_16, (PSFP_15 + FP_SIZE) .set PSFP_17, (PSFP_16 + FP_SIZE) .set PSFP_18, (PSFP_17 + FP_SIZE) .set PSFP_19, (PSFP_18 + FP_SIZE) .set PSFP_20, (PSFP_19 + FP_SIZE) .set PSFP_21, (PSFP_20 + FP_SIZE) .set PSFP_22, (PSFP_21 + FP_SIZE) .set PSFP_23, (PSFP_22 + FP_SIZE) .set PSFP_24, (PSFP_23 + FP_SIZE) .set PSFP_25, (PSFP_24 + FP_SIZE) .set PSFP_26, (PSFP_25 + FP_SIZE) .set PSFP_27, (PSFP_26 + FP_SIZE) .set PSFP_28, (PSFP_27 + FP_SIZE) .set PSFP_29, (PSFP_28 + FP_SIZE) .set PSFP_30, (PSFP_29 + FP_SIZE) .set PSFP_31, (PSFP_30 + FP_SIZE) .align 5 .globl _cpu_context_save_fp _cpu_context_save_fp: lhz r4,STATE(r3) ori r4,r4,0x0001 sth r4,STATE(r3) stfd fr0, FP_0(r3) stfd fr1, FP_1(r3) stfd fr2, FP_2(r3) stfd fr3, FP_3(r3) stfd fr4, FP_4(r3) stfd fr5, FP_5(r3) stfd fr6, FP_6(r3) stfd fr7, FP_7(r3) stfd fr8, FP_8(r3) stfd fr9, FP_9(r3) stfd fr10, FP_10(r3) stfd fr11, FP_11(r3) stfd fr12, FP_12(r3) stfd fr13, FP_13(r3) stfd fr14, FP_14(r3) stfd fr15, FP_15(r3) stfd fr16, FP_16(r3) stfd fr17, FP_17(r3) stfd fr18, FP_18(r3) stfd fr19, FP_19(r3) stfd fr20, FP_20(r3) stfd fr21, FP_21(r3) stfd fr22, FP_22(r3) stfd fr23, FP_23(r3) stfd fr24, FP_24(r3) stfd fr25, FP_25(r3) stfd fr26, FP_26(r3) stfd fr27, FP_27(r3) stfd fr28, FP_28(r3) stfd fr29, FP_29(r3) stfd fr30, FP_30(r3) stfd fr31, FP_31(r3) mffs fr0 stfd fr0, FP_FPSCR(r3) lfd fr0, FP_0(r3) 1: blr .align 5 .globl _cpu_context_restore_fp _cpu_context_restore_fp: lhz r4,STATE(r3) clrlwi. r4,r4,31 beq 2f lfd fr0, FP_FPSCR(r3) mtfsf 255, fr0 lfd fr0, FP_0(r3) lfd fr1, FP_1(r3) lfd fr2, FP_2(r3) lfd fr3, FP_3(r3) lfd fr4, FP_4(r3) lfd fr5, FP_5(r3) lfd fr6, FP_6(r3) lfd fr7, FP_7(r3) lfd fr8, FP_8(r3) lfd fr9, FP_9(r3) lfd fr10, FP_10(r3) lfd fr11, FP_11(r3) lfd fr12, FP_12(r3) lfd fr13, FP_13(r3) lfd fr14, FP_14(r3) lfd fr15, FP_15(r3) lfd fr16, FP_16(r3) lfd fr17, FP_17(r3) lfd fr18, FP_18(r3) lfd fr19, FP_19(r3) lfd fr20, FP_20(r3) lfd fr21, FP_21(r3) lfd fr22, FP_22(r3) lfd fr23, FP_23(r3) lfd fr24, FP_24(r3) lfd fr25, FP_25(r3) lfd fr26, FP_26(r3) lfd fr27, FP_27(r3) lfd fr28, FP_28(r3) lfd fr29, FP_29(r3) lfd fr30, FP_30(r3) lfd fr31, FP_31(r3) 2: blr
Wack0/entii-for-workcubes
1,163
arcfw/source/arcinvoke.S
#define _LANGUAGE_ASSEMBLY #include "asm.h" .text .global __ArcInvokeImpl __ArcInvokeImpl: mflr r0 stwu r0, -4(r1) mtctr r3 mr r2, r4 mr r3, r5 mr r4, r6 mr r5, r7 bctrl lwzu r0, 0(r1) addi r1, r1, 4 mtlr r0 blr .globl DCFlushRangeNoSync DCFlushRangeNoSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b blr .globl ICInvalidateRange ICInvalidateRange: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: icbi r0, r3 addi r3, r3, 0x20 bdnz 2b sync isync blr .globl DCFlushRangeInlineSync DCFlushRangeInlineSync: cmplwi r4, 0 # zero or negative size? blelr clrlwi. r5, r3, 27 # check for lower bits set in address beq 1f addi r4, r4, 0x20 1: addi r4, r4, 0x1f srwi r4, r4, 5 mtctr r4 2: dcbf r0, r3 addi r3, r3, 0x20 bdnz 2b mfspr r3,HID0 ori r4,r3,0x0008 mtspr HID0,r4 isync sync mtspr HID0,r3 blr
Wack0/entii-for-workcubes
2,546
arcfw/source/crt0.S
// Startup code. // Exception handlers are adapted from OpenBIOS: /* * Creation Date: <2001/06/16 21:30:18 samuel> * Time-stamp: <2003/04/04 16:32:06 samuel> * * <init.S> * * Asm glue for ELF images run inside MOL * * Copyright (C) 2001, 2002, 2003 Samuel Rydh (samuel@ibrium.se) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation * */ #define _LANGUAGE_ASSEMBLY #include "asm.h" .text .extern FwMain .extern __executable_start .globl _start _start: // We are currently in little endian mode, // in translated mode, // with interrupts disabled. // The BATs set up are as follows: // [DI]BAT0: 0x8000_0000 + 256MB => physical 0x0000_0000 (cached, r+w) // [DI]BAT1: 0x9000_0000 + 256MB => physical 0x1000_0000 (cached, r+w) // DBAT2: 0x6000_0000 + 256MB => physical 0x0000_0000 (uncached, r+w) // DBAT3: 0x7000_0000 + 256MB => physical 0x1000_0000 (uncached, r+w) // The physical memory of each system is as follows: // Prod DOL => 24MB at 0 // Dev DOL => 48MB at 0 // Prod RVL => 24MB at 0, 64MB at 0x1000_0000 // Dev RVL => 24MB at 0, 128MB at 0x1000_0000 // For Cafe, first 256MB of DDR is mapped by a BAT as well as all other memory: // Prod Cafe => 32MB at 0, ~3MB at 0x0800_0000, 2GB at 0x1000_0000 // Dev Cafe => 32MB at 0, ~3MB at 0x0800_0000, 3GB at 0x1000_0000 // r3 is the physical address of our hardware description struct. // Do not bother touching it right now. // In fact, save it in a higher register: nop mr r31, r3 #if 0 // do we get here nop lis r7, 0x6d80 nop ori r7, r7, 0x00c0 nop mfmsr r6 nop rlwinm r6, r6, 2, 29, 29 // MSR_LE ? 4 : 0 nop or r7, r7, r6 // MSR_LE ? 0d80_00c4 : 0d80_00c0 nop lwz r6, 0(r7) nop sync nop ori r6, r6, 0x20 nop stw r6, 0(r7) nop eieio nop b . #endif // set up a stack: // we are at 9MB, use ram before it for stack. // this way we can set up 1MB at 8MB as firmware temporary. lis r1, __executable_start@h ori r1, r1, __executable_start@l subi r1, r1, 8 // switch into translated mode and jump to FwMain mr r3, r31 oris r3, r3, 0x8000 #if 0 lis r5, FwMain@h ori r5, r5, FwMain@l mtsrr0 r5 mfmsr r4 ori r4, r4, MSR_DR|MSR_IR mtsrr1 r4 rfi #endif b FwMain #if 0 .globl ReturnToLoader ReturnToLoader: lis r3, 0x8000 ori r3, r3, 0x1800 mtsrr0 r3 mfmsr r3 // disable MSR_ILE rlwinm r3,r3,0,16,14 mtmsr r3 // disable MSR_LE into srr1 rlwinm r3,r3,0,0,30 mtsrr1 r3 rfi #endif
Wack0/entii-for-workcubes
2,709
arcfw/source/crtsavgpr.S
/* * Special support for eabi and SVR4 * * Copyright (C) 1995-2024 Free Software Foundation, Inc. * Written By Michael Meissner * 64-bit support written by David Edelsohn * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file 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 * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ /* Do any initializations needed for the eabi environment */ .section ".text" #include "ppc-asm.h" /* On PowerPC64 Linux, these functions are provided by the linker. */ #ifndef __powerpc64__ /* Routines for saving integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer save area. */ CFI_STARTPROC HIDDEN_FUNC(_savegpr_14) stw 14,-72(11) /* save gp registers */ HIDDEN_FUNC(_savegpr_15) stw 15,-68(11) HIDDEN_FUNC(_savegpr_16) stw 16,-64(11) HIDDEN_FUNC(_savegpr_17) stw 17,-60(11) HIDDEN_FUNC(_savegpr_18) stw 18,-56(11) HIDDEN_FUNC(_savegpr_19) stw 19,-52(11) HIDDEN_FUNC(_savegpr_20) stw 20,-48(11) HIDDEN_FUNC(_savegpr_21) stw 21,-44(11) HIDDEN_FUNC(_savegpr_22) stw 22,-40(11) HIDDEN_FUNC(_savegpr_23) stw 23,-36(11) HIDDEN_FUNC(_savegpr_24) stw 24,-32(11) HIDDEN_FUNC(_savegpr_25) stw 25,-28(11) HIDDEN_FUNC(_savegpr_26) stw 26,-24(11) HIDDEN_FUNC(_savegpr_27) stw 27,-20(11) HIDDEN_FUNC(_savegpr_28) stw 28,-16(11) HIDDEN_FUNC(_savegpr_29) stw 29,-12(11) HIDDEN_FUNC(_savegpr_30) stw 30,-8(11) HIDDEN_FUNC(_savegpr_31) stw 31,-4(11) blr FUNC_END(_savegpr_31) FUNC_END(_savegpr_30) FUNC_END(_savegpr_29) FUNC_END(_savegpr_28) FUNC_END(_savegpr_27) FUNC_END(_savegpr_26) FUNC_END(_savegpr_25) FUNC_END(_savegpr_24) FUNC_END(_savegpr_23) FUNC_END(_savegpr_22) FUNC_END(_savegpr_21) FUNC_END(_savegpr_20) FUNC_END(_savegpr_19) FUNC_END(_savegpr_18) FUNC_END(_savegpr_17) FUNC_END(_savegpr_16) FUNC_END(_savegpr_15) FUNC_END(_savegpr_14) CFI_ENDPROC #endif
wagiminator/ATmega-Transistor-Tester
6,649
software/sources/ReadADC.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include "config.h" #include <stdlib.h> //#include "autoinout.h" .GLOBAL ReadADC .GLOBAL W20msReadADC .GLOBAL W10msReadADC .GLOBAL W5msReadADC .func ReadADC .extern wait100us .extern wait5ms .extern wait10ms #define Samples 0 #define RefFlag 1 #define U_Bandgap 2 #define U_AVCC 4 ;// assembler version of ReadADC.c ;// ACALL is defined in config.h as rcall for ATmega8 and as call for ATmega168 #define RCALL rcall #ifdef INHIBIT_SLEEP_MODE .macro StartADCwait #if ADCSRA < 32 sbi ADCSRA, ADSC; #else ldi r24, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable and start ADC */ sts ADCSRA, r24; #endif lds r24, ADCSRA; /* while (ADCSRA & (1 <<ADSC)) */ sbrc r24, ADSC; rjmp .-8 ; /* wait until conversion is done */ .endm #else .macro StartADCwait ldi r24, (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | AUTO_CLOCK_DIV; /* enable ADC and Interrupt */ sts ADCSRA, r24; ldi r24, (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ sleep; /* wait for ADC */ ldi r24, (1 << SM0) | (0 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (0 << SE); */ .endm #endif .section .text ;unsigned int W20msReadADC(uint8_t Probe) ;unsigned int W5msReadADC(uint8_t Probe) #ifdef INHIBIT_SLEEP_MODE W20msReadADC: ACALL wait10ms; ;// runs to W10msReadADC W10msReadADC: ACALL wait5ms; ;// runs to W5msReadADC W5msReadADC: ACALL wait5ms; ;// runs directly to ReadADC, this will replace "ACALL ReadADC + ret" #else W20msReadADC: push r24; ldi r24, 4; /* 4 * 5ms */ RCALL sleep_5ms; rjmp to_read; W10msReadADC: push r24; ldi r24, 2; /* 2 * 5ms */ RCALL sleep_5ms; rjmp to_read; W5msReadADC: push r24; ldi r24, 1; /* 1 * 5ms */ RCALL sleep_5ms; to_read: pop r24; ; run directly to ReadADC #endif ;unsigned int ReadADC(uint8_t Probe) ReadADC: ; //returns result of ADC port Probe scaled to mV resolution (unsigned int) ; unsigned long Value; push r17; ; unsigned int U; /* return value (mV) */ ; uint8_t Samples; /* loop counter */ ; unsigned long Value; /* ADC value */ mov r17, r24; Probe ori r17, (1 << REFS0) ; Probe |= (1 << REFS0); /* use internal reference anyway */ get_sample: AOUT ADMUX, r17 ; ADMUX = Probe; /* set input channel and U reference */ #ifdef AUTOSCALE_ADC /* if voltage reference changed run a dummy conversion */ mov r30, r17; andi r30, (1 << REFS1) ; Samples = Probe & (1 << REFS1); /* get REFS1 bit flag */ lds r24, ADCconfig+RefFlag ; cp r30, r24; breq no_ref_change ; if (Samples != ADCconfig.RefFlag) sts ADCconfig+RefFlag, r30 ; ADCconfig.RefFlag = Samples; /* update flag */ #ifdef NO_AREF_CAP RCALL wait100us ; wait100us(); /* time for voltage stabilization */ #else #ifdef INHIBIT_SLEEP_MODE RCALL wait10ms ; wait10ms(); /* long time for voltage stabilization */ #else ldi r24, 2 ; /* 2 * 5ms */ RCALL sleep_5ms ; wait_about10ms() #endif #endif /* end NO_AREF_CAP */ StartADCwait ; // allways do one dummy read of ADC, 112us #endif /* end AUTOSCALE_ADC */ ;unsigned int ReadADC (uint8_t Probe) { no_ref_change: /* * sample ADC readings */ ldi r18, 0x00; Value = 0UL; /* reset sampling variable */ ldi r19, 0x00; movw r20, r18; ldi r30, 0x00; Samples = 0; /* number of samples to take */ rjmp r2ae8 ; ; while (Samples < ADCconfig.Samples) /* take samples */ Loop: StartADCwait /* start ADC and wait */ lds r22, ADCL; Value += ADCW; /* add ADC reading */ lds r23, ADCH; add r18, r22; adc r19, r23; adc r20, r1; adc r21, r1; #ifdef AUTOSCALE_ADC ; /* auto-switch voltage reference for low readings */ ; if ((Samples == 4) && (ADCconfig.U_Bandgap > 255) && ((uint16_t)Value < 1024) && !(Probe & (1 << REFS1))) { cpi r30, 0x04; Samples == 4 brne cnt_next ; if ((Samples == 4) && lds r24, ADCconfig+3; cpi r24,0; breq cnt_next ; if ( && (ADCconfig.U_Bandgap > 255) ) ldi r24, hi8(1024) ; Value < 1024 cpi r18, lo8(1024) cpc r19, r24; brcc cnt_next ; if ( && && ((uint16_t)Value < 1024) ) sbrc r17, REFS1; rjmp cnt_next ; if ( && && && !(Probe & (1 << REFS1))) ori r17, (1 << REFS1); Probe |= (1 << REFS1); /* select internal bandgap reference */ #if (PROCESSOR_TYP == 644) || (PROCESSOR_TYP == 1280) cbr r17, (1<<REFS0); Probe &= ~(1 << REFS0); /* ATmega640/1280/2560 1.1V Reference with REFS0=0 */ #endif rjmp get_sample ; goto get_sample; /* re-run sampling */ #endif /* end AUTOSCALE_ADC */ cnt_next: subi r30, 0xFF; Samples++; /* one more done */ r2ae8: lds r24, ADCconfig+Samples; cp r30, r24 ; while (Samples < ADCconfig.Samples) /* take samples */ brcs Loop ; lds r22, ADCconfig+U_AVCC ; U = ADCconfig.U_AVCC; /* Vcc reference */ lds r23, ADCconfig+U_AVCC+1; #ifdef AUTOSCALE_ADC ; /* * convert ADC reading to voltage * - single sample: U = ADC reading * U_ref / 1024 */ ; /* get voltage of reference used */ sbrs r17, REFS1 ; if (Probe & (1 << REFS1)) rjmp r2b02 ; lds r22, ADCconfig+U_Bandgap ; U = ADCconfig.U_Bandgap; /* bandgap reference */ lds r23, ADCconfig+U_Bandgap+1; #endif /* end AUTOSCALE_ADC */ ; /* convert to voltage; */ r2b02: ldi r24, 0x00 ; Value *= U; /* ADC readings * U_ref */ ldi r25, 0x00; 0 ACALL __mulsi3; ; sum(ADCreads) * ADC_reference ldi r18, lo8(1023) ; Value /= 1023; /* / 1024 for 10bit ADC */ ldi r19, hi8(1023); ldi r20, 0x00; 0 ldi r21, 0x00; 0 ACALL __udivmodsi4; R22-25 / R18-21 movw r22, r18; movw r24, r20; ; /* de-sample to get average voltage */ lds r18,ADCconfig+Samples ; Value /= ADCconfig.Samples; ldi r19, 0x00; 0 ldi r20, 0x00; 0 ldi r21, 0x00; 0 ACALL __udivmodsi4; R22-25 / R18-21 movw r24, r18 ;;// return ((unsigned int)(Value / (1023 * (unsigned long)ADCconfig.Samples))); pop r17; ret; .endfunc .func abs_diff .GLOBAL abs_diff abs_diff: movw r18, r22 sub r18, r24 sbc r19, r25 brcs is_pl ; return v1-v2 movw r24, r18 ret ; return v2-v1 .endfunc .func vcc_diff .GLOBAL vcc_diff ; uint16_t vcc_diff(uint16_t v2) // computes unsigned_diff(ADCconfig.U_AVCC, v2) vcc_diff: movw r22, r24 lds r24, ADCconfig+U_AVCC lds r25, ADCconfig+U_AVCC+1 ; runs to function unsigned diff .endfunc .func unsigned_diff .GLOBAL unsigned_diff ; uint16_t unsigned_diff(uint16_t v1, uint16_t v2) // computes v1-v2 if positive, otherwise returns 0 unsigned_diff: cp r22, r24 cpc r23, r25 brcc no_pl is_pl: sub r24, r22 sbc r25, r23 ret ; return v1-v2 no_pl: ldi r24, 0 ldi r25, 0 ret ; .endfunc
wagiminator/ATmega-Transistor-Tester
3,919
software/sources/RefVoltage.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/eeprom.h> #include "config.h" #include "part_defs.h" #define zero_reg r1 #define Ref_Tab_Abstand 50 ; displacement of table is 50mV #define Ref_Tab_Beginn 1000 ; // begin of table is 1000mV .GLOBAL RefVoltage .func RefVoltage .extern eeprom_read_byte .extern RHtab .section .text RefVoltage: #ifdef AUTO_CAL ldi r24, lo8(ref_offset) ; 1 ldi r25, hi8(ref_offset) ; 0 ;; ACALL eeprom_read_word ; eeprom_read_word((uint16_t *)(&ref_offset)); ;; lds r18, ref_mv ;; lds r19, ref_mv+1 ;; add r18, r24 ; referenz = ref_mv + ;; adc r19, r25 ACALL eeprom_read_byte ; eeprom_read_word((uint16_t *)(&ref_offset)); done as two read_byte mov r19, r24 ldi r24, lo8(ref_offset+1) ldi r25, hi8(ref_offset+1) ACALL eeprom_read_byte lds r18, ref_mv add r18, r19 lds r19, ref_mv+1 adc r19, r24 #else lds r18, ref_mv lds r19, ref_mv+1 subi r18, -REF_C_KORR ; referenz = ref_mv + REF_C_KORR; adc r19, zero_reg #endif sts ref_mv_offs, r18 sts ref_mv_offs+1, r19 #ifdef AUTO_RH ldi r24, hi8(Ref_Tab_Beginn) ; 3 cpi r18, lo8(Ref_Tab_Beginn) ; 232 cpc r19, r24 brcs ad210e ; if (referenz >= Ref_Tab_Beginn) movw r24, r18 subi r24, lo8(Ref_Tab_Beginn) ; 232 referenz -= Ref_Tab_Beginn; sbci r25, hi8(Ref_Tab_Beginn) ; 3 rjmp ad2112 ad210e: ldi r24, 0x00 ; referenz = 0; // limit to begin of table ldi r25, 0x00 ; 0 ad2112: ldi r22, lo8(Ref_Tab_Abstand) ; 50 tabind = referenz / Ref_Tab_Abstand; ldi r23, hi8(Ref_Tab_Abstand) ; 0 ACALL __udivmodhi4 ; r22 = tabind = referenz / Ref_Tab_Abstand; ; r24 = tabres = referenz % Ref_Tab_Abstand; cpi r22, 0x08 ; if (tabind > 7) brcs ad2120 ldi r22, 0x07 ; tabind = 7; // limit to end of table ad2120: ; // interpolate the table of factors LDIZ RHtab add r30, r22 adc r31, zero_reg add r30, r22 adc r31, zero_reg lpm r20, Z+ ; y1 = pgm_read_word(&RHtab[tabind]); lpm r21, Z+ lpm r18, Z+ ; y2 = pgm_read_word(&RHtab[tabind+1]); lpm r19, Z+ ldi r22, Ref_Tab_Abstand ; 50 sub r22, r24 ; tabres = Ref_Tab_Abstand-tabres; ; // interpolate the table of factors ; // RHmultip is the interpolated factor to compute capacity from load time with 470k ;; ldi r23, 0x00 ; 0 sub r20, r18 ; y1 - y2 #if FLASHEND > 0x1fff sbc r21, r19 ; hi8(y1 - y2) is usually allway zero #endif mul r22, r20 ; lo8(tabres) * lo8(y1-y2) movw r24, r0 ; r24:25 = * #if FLASHEND > 0x1fff mul r22, r21 ; lo8(tabres) * hi8(y1-y2) add r25, r0 ; r25 + lo8(*) #endif ;; mul r23, r20 ; hi8(tabres) * lo8(y1*y2) , allways zero ;; add r25, r0 ; r25 + lo8(*) eor r1, r1 adiw r24, (Ref_Tab_Abstand/2) ; 25 ldi r22, lo8(Ref_Tab_Abstand) ; 50 ldi r23, hi8(Ref_Tab_Abstand) ; 0 ACALL __udivmodhi4 ; ((y1 - y2) * tabres + (Ref_Tab_Abstand/2)) / Ref_Tab_Abstand add r22, r18 ; + y2 adc r23, r19 sts RHmultip+1, r23 sts RHmultip, r22 #else ldi r22, lo8(DEFAULT_RH_FAKT) ldi r23, hi8(DEFAULT_RH_FAKT) sts RHmultip, r22 sts RHmultip+1, r23 #endif #ifdef AUTO_CAL ldi r24, lo8(RefDiff) ldi r25, hi8(RefDiff) ACALL eeprom_read_byte ; (int8_t)eeprom_read_byte((uint8_t *)&RefDiff)); eor r25, r25 ; set zero for sign extend sbrc r24, 7 ; minus? com r25 ; yes, set to 0xff lds r22, ref_mv ; ADCconfig.U_Bandgap = (ref_mv + (int8_t)eeprom_read_byte((uint8_t *)&RefDiff)); lds r23, ref_mv+1 add r24, r22 adc r25, r23 #else ldi r22, lo8(REF_R_KORR) ldi r23, hi8(REF_R_KORR) lds r24, ref_mv ; ADCconfig.U_Bandgap = (ref_mv + REF_R_KORR); lds r25, ref_mv+1 add r24, r22 adc r25, r23 #endif #define U_Bandgap 2 sts ADCconfig+U_Bandgap+1, r25 sts ADCconfig+U_Bandgap, r24 sts adc_internal_reference+1, r25 ; adc_internal_reference = ADCconfig.U_Bandgap; sts adc_internal_reference, r24 ret .endfunc
wagiminator/ATmega-Transistor-Tester
8,084
software/sources/wait1000ms.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> .func wait1000ms .global wait5s ; wait 5 seconds .global wait4s ; wait 4 seconds .global wait3s ; wait 3 seconds .global wait2s ; wait 2 seconds .global wait1s ; wait 1 seconds .global wait1000ms ; wait 1 second and wait 1000ms are identical .global wait500ms ; wait 500ms .global wait400ms ; wait 400ms .global wait300ms ; wait 300ms .global wait200ms ; wait 200ms .global wait100ms ; wait 100ms .global wait50ms ; wait 50ms .global wait40ms ; wait 40ms .global wait30ms ; wait 30ms .global wait20ms ; wait 20ms .global wait10ms ; wait 10ms .global wait5ms ; wait 5ms .global wait4ms ; wait 4ms .global wait3ms ; wait 3ms .global wait2ms ; wait 2ms .global wait1ms ; wait 1ms .global wait500us ; wait 500µs .global wait400us ; wait 400µs .global wait300us ; wait 300µs .global wait200us ; wait 200µs .global wait100us ; wait 100µs .global wait50us ; wait 50µs .global wait40us ; wait 40µs .global wait30us ; wait 30µs .global wait20us ; wait 20µs .global wait10us ; wait 10µs /* A delay of 5us require a clock frequency of at least 1.4 MHz */ .global wait5us ; wait 5µs .global wait4us ; wait 4µs .global wait3us ; wait 3µs .global wait2us ; wait 2µs /* A delay of 1us require a clock frequency of at least 7 MHz */ .global wait1us ; wait 1µs ;wait loops for ATmega at a clock above 1MHz ; use of flash memory is: 76 bytes (16MHz operation, including 2 Byte Watch Dog reset at wait100ms) ; Every wait call needs only one instruction (rcall) for every of the 36 different delays (500ns - 5s). ; No registers are used. (only stack pointer) ; A maximum of 28 bytes of space for return addresses is used in RAM ; I see no way to implement this function with C-language (too tricky) wait5s: rcall wait1s ; 12+x return-adresses wait4s: rcall wait1s ; 12+x return-adresses wait3s: rcall wait1s ; 12+x return-adresses wait2s: rcall wait1s ;1s 12+x Return-Adresses wait1s: wait1000ms: rcall wait500ms ;500ms 11+x Return-Adresses wait500ms: rcall wait100ms ;100ms 10+x Return-Adresses wait400ms: rcall wait100ms ;100ms 10+x Return-Adresses wait300ms: rcall wait100ms ;100ms 10+x Return-Adresses wait200ms: rcall wait100ms ;100ms 10+x Return-Adresses wait100ms: rcall wait50ms ; 50ms 9+x Return-Adresses wait50ms: rcall wait10ms ;10ms 8+x Return-Adresses wait40ms: rcall wait10ms ;10ms 8+x Return-Adresses wait30ms: rcall wait10ms ;10ms 8+x Return-Adresses wait20ms: rcall wait10ms ;10ms 8+x Return-Adresses wait10ms: rcall wait5ms ;5ms 7+x Return-Adresses wait5ms: wdr ; every 5ms one Watchdog reset! rcall wait1ms ;1ms 6+x Return-Adresses wait4ms: rcall wait1ms ;1ms 6+x Return-Adresses wait3ms: rcall wait1ms ;1ms 6+x Return-Adresses wait2ms: rcall wait1ms ;1ms 6+x Return-Adresses wait1ms: rcall wait500us ;500us 5+x Return-Adresses wait500us: rcall wait100us ;100us 4+x Return-Adresses wait400us: rcall wait100us ;100us 4+x Return-Adresses wait300us: rcall wait100us ;100us 4+x Return-Adresses wait200us: rcall wait100us ;100us 4+x Return-Adresses # RCALL_TICS specify the number of tics used for rcall and ret instruction #if FLASH_END > 0x1ffff /* special 3 byte return address takes two tics more */ #define RCALL_TICS 9 #else #define RCALL_TICS 7 #endif /* PS25_PER_TIC specify the number of 25ps units for one clock tic */ /* 40000000000 need more than 32 bit, so F_CPU is divided by 10 to match the 32-bit */ /* Note, that there is a little error of time delay, if 1/F_CPU does not match a multiple */ /* of a 25ps unit */ /* Normally the higher delay values are build with multiple of the base delay, */ /* so wait100us is done with 100 times of a wait1us call for example. */ /* But for F_CPU values, that does not match the 1us delay, corrections are done */ /* for the wait calls up to the wait100us call. The higher wait calls are not corrected. */ #define PS25_PER_TIC (4000000000 / ((F_CPU + 5) / 10)) #define US100_TICS (4000000 / PS25_PER_TIC) #define US50_TICS (2000000 / PS25_PER_TIC) #define US40_TICS (1600000 / PS25_PER_TIC) #define US30_TICS (1200000 / PS25_PER_TIC) #define US20_TICS (800000 / PS25_PER_TIC) #define US10_TICS (400000 / PS25_PER_TIC) #define US5_TICS (200000 / PS25_PER_TIC) #define US4_TICS (160000 / PS25_PER_TIC) #define US3_TICS (120000 / PS25_PER_TIC) #define US2_TICS (80000 / PS25_PER_TIC) #define US1_TICS (40000 / PS25_PER_TIC) #define NS500_TICS (20000 / PS25_PER_TIC) wait100us: #if US100_TICS > (2 * US50_TICS) nop #endif rcall wait50us ; 50us delay wait50us: #if US50_TICS > (US40_TICS + US10_TICS) nop #endif rcall wait10us ;10us delay wait40us: #if US40_TICS > (US30_TICS + US10_TICS) nop #endif rcall wait10us ;10us delay wait30us: #if US30_TICS > (US20_TICS + US10_TICS) nop #endif rcall wait10us ;10us delay wait20us: #if US20_TICS > (2 * US10_TICS) nop #endif rcall wait10us ;10us delay wait10us: ; #if US5_TICS >= RCALL_TICS #if US10_TICS > (2 * US5_TICS) nop #endif rcall wait5us ; at least 5us delay is possible #if US1_TICS >= RCALL_TICS ; a 1us delay is also possible #if NS500_TICS >= RCALL_TICS wait5us: #if US5_TICS > (US4_TICS + US1_TICS) nop #endif rcall wait1us wait4us: #if US4_TICS > (US3_TICS + US1_TICS) nop #endif rcall wait1us wait3us: #if US3_TICS > (US2_TICS + US1_TICS) nop #endif rcall wait1us wait2us: #if US2_TICS > (2 * US1_TICS) nop #endif rcall wait1us wait1us: ; a 500ns delay is also possible with call #if US1_TICS > (2 * NS500_TICS) nop #endif rcall wait500ns .global wait500ns wait500ns: #define INNER_TICS NS500_TICS #else #define INNER_TICS US1_TICS wait5us: #if US5_TICS > (US4_TICS + US1_TICS) nop #endif rcall wait1us wait4us: #if US4_TICS > (US3_TICS + US1_TICS) nop #endif rcall wait1us wait3us: #if US3_TICS > (US2_TICS + US1_TICS) nop #endif rcall wait1us wait2us: #if US2_TICS > (2 * US1_TICS) nop #endif rcall wait1us wait1us: #endif #else ; wait5us is the inner body, 1us not possible #define INNER_TICS US5_TICS wait5us: wait4us: wait3us: #if INNER_TICS < (RCALL_TICS * 2) wait2us: wait1us: #else #define LATE_2US #endif #endif #else ; wait10us is the inner body #define INNER_TICS US10_TICS wait5us: wait4us: wait3us: wait2us: wait1us: #endif ; Now we have to build the inner loop with INNER_TICS clock tics. ; The rcall and ret take RCALL_TICS clock tics (7 or 9). #if INNER_TICS < RCALL_TICS #error wait100ms can not build a function with 10us, F_CPU frequency too low! #endif ;----------------------------------------------------------------------------- #if INNER_TICS >= (RCALL_TICS * 4) #define WAST_TICS3 ((INNER_TICS / 4) - RCALL_TICS) ; Build two nested loops waitinner1 and waitinner2 wait5us: #if INNER_TICS > ((INNER_TICS/2) * 2) nop #endif rcall waitinner2 waitinner2: #ifdef LATE_2US wait2us: #endif #if ((INNER_TICS / 2) - (2*(RCALL_TICS+WAST_TICS3))) > 0 nop #endif rcall waitinner1 waitinner1: #ifdef LATE_2US wait1us: #endif #if WAST_TICS3 > 1 nop #endif #if WAST_TICS3 > 0 nop #endif #else ; ################################## INNER_TICS < (RCALL_TICS * 4) #if INNER_TICS >= (RCALL_TICS * 2) #define WAST_TICS2 ((INNER_TICS - (2*RCALL_TICS)) / 2) wait5us: #if (INNER_TICS - (2*WAST_TICS2)) > (2*RCALL_TICS) nop #endif rcall waitinner1 #ifdef LATE_2US wait2us: wait1us: #endif waitinner1: #else ; ################################# INNER_TICS < (RCALL_TICS * 2) #define WAST_TICS2 (INNER_TICS - RCALL_TICS) #endif #endif #if WAST_TICS2 > 7 #warning wait1000ms: WAST_TICS2 > 7, delay times may be wrong! #endif #if WAST_TICS2 >= 6 rjmp . /* two additional tics */ #endif #if WAST_TICS2 >= 4 rjmp . /* two additional tics */ #endif #if WAST_TICS2 >= 2 rjmp . /* two additional tics */ #endif #if ((WAST_TICS2 / 2) * 2) < WAST_TICS2 nop /* one additional tic */ #endif ret
wagiminator/ATmega-Transistor-Tester
30,205
software/sources/GetESR_107.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include <avr/eeprom.h> #include "config.h" #include <stdlib.h> .GLOBAL GetESR .func GetESR /* MAX_CNT is the maximum loop counter for repetition of mesurement */ #define MAX_CNT 128 /* ADC_Sleep_Mode enables the sleep state for reading ADC */ //#define ADC_Sleep_Mode /* ESR_DEBUG enables additional Output on row 3 and row 4 */ //#define ESR_DEBUG #ifdef INHIBIT_SLEEP_MODE /* Makefile option set to disable the sleep mode */ #undef ADC_Sleep_Mode #endif #define zero_reg r1 // uint8_t big_cap; #define big_cap 1 // unsigned long sumvolt0,sumvolt1,sumvolt2; // 3 sums of ADC readings #define sumvolt0 2 /* r14-r17 */ #define sumvolt1 6 /* SP + 6:9 */ #define sumvolt2 10 /* SP + 10:13 */ // uint8_t LoADC; // used to switch Lowpin directly to GND or VCC #define LoADC 14 /* SP + 14 */ // uint8_t HiADC; // used to switch Highpin directly to GND or VCC #define HiADC 15 /* SP + 15 */ // unsigned int adcv[3]; // array for 3 ADC readings // first part adcv0 r2/r3 // first part adcv1 Y+16/17 #define adcvv1 16 // first part adcv2 Y+18/19 #define adcvv2 18 // unsigned long cap_val_nF; // capacity in nF #define cap_val_nF 20 /* SP + 20:23 */ #define adcv0L r2 #define adcv0H r3 #define adcv2L r24 #define adcv2H r25 // uint8_t HiPinR_L; // used to switch 680 Ohm to HighPin #define HiPinR_L r12 // uint8_t LoPinR_L; // used to switch 680 Ohm to LowPin #define LoPinR_L r7 // uint8_t ii,jj; // tempory values // uint8_t StartADCmsk; // Bit mask to start the ADC #define StartADCmsk r10 // uint8_t SelectLowPin; #define SelectLowPin r6 // uint8_t SelectHighPin; #define SelectHighPin r11 // int8_t esr0; // used for ESR zero correction // #define esr0 r2 // Structure cap: .extern cap #define cval_max 4 #define esr 12 #define ca 16 #define cb 17 #define cpre_max 19 .extern EE_ESR_ZERO #ifdef ADC_Sleep_Mode // #define StartADCwait() ADCSRA = (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | AUTO_CLOCK_DIV; /* enable ADC and Interrupt */ // set_sleep_mode(SLEEP_MODE_ADC); // sleep_mode() /* Start ADC, return if ADC has finished */ .macro StartADCwait ldi r24, (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ sleep; /* wait for ADC */ ldi r24, (1 << SM0) | (0 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ .endm #else // #define StartADCwait() ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable ADC and start */ .macro StartADCwait sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk = r10 */ lds r24, ADCSRA; /* while (ADCSRA & (1 <<ADSC)) */ sbrc r24, ADSC; rjmp .-8 ; /* wait until conversion is done */ .endm #endif /* ************************************************************************************ */ /* Adjust the timing for switch off the load current for big capacitors */ /* ************************************************************************************ */ // with wdt_reset the timing can be adjusted, // when time is too short, voltage is down before SH of ADC // when time is too long, capacitor will be overloaded. // That will cause too high voltage without current. .macro DelayBigCap call wait10us; // SH at 2.5 ADC clocks behind start = 20 us call wait5us #ifdef ADC_Sleep_Mode /* Wake up from sleep with Interrupt: 1+4+4T, jmp, rti, ldi, out takes 18 clock tics, */ /* 3+1 clock tics (sts,out) are needed for instructions before the current is switched off. */ #if F_CPU == 8000000UL call wait2us; /* wait2us(); // with only 17 us delay the voltage goes down before SH */ /* delay 17us + 3 clock tics (CALL instead of RCALL) = 17.375 us @ 8 MHz */ /* + 22 clock tics delay from interrupt return, +2.75us = 20.125 + */ /* 19.875 us - */ /* 20.0 us ? */ #endif #if F_CPU == 16000000UL call wait3us; /* wait3us(); // with only 18 us delay the voltage goes down before SH */ /* delay 18us + 3 clock tics (CALL instead of RCALL) = 18.1875 us */ /* + 22 clock tics delay from interrupt return, +1.375us = 19.5625 us */ call wait500ns; /* wait500ns(); // 20.125 us + */ /* 19.9375 us - */ /* 20.0625 us ? */ /* 20.1875 us + */ #endif #else /* Polling mode: lds,sbrc,sts and out Instructions are 7 clock tics */ #if F_CPU == 8000000UL call wait4us; // with only 18 us delay the voltage goes down before SH /* delay 19us + 3 clock tics (CALL instead of RCALL) = 19.375 us @ 8 MHz */ /* + 7 clock tics delay from while loop, +0.875us = 20.25 us + */ /* 19.875us - */ /* 20.0 us ? */ /* 20.125us + */ #endif #if F_CPU == 16000000UL call wait4us; // with only 18 us delay the voltage goes down before SH /* delay 19us + 3 clock tics (CALL instead of RCALL) = 19.1875 us */ /* + 7 clock tics delay from while loop, +0.4375us = 19.625 us */ push r24; /* 19.75 us */ pop r24; /* 19.875 us */ wdr ; /* wdt_reset(); // 19.9375us */ wdr ; /* wdt_reset(); // 20.0 us - */ wdr ; /* wdt_reset(); // 20.0625us ? */ wdr ; /* wdt_reset(); // 20.125 us + */ #endif #endif .endm /* ************************************************************************************ */ /* Adjust the timing for switch off the load current for small capacitors */ /* ************************************************************************************ */ .macro DelaySmallCap #ifdef ADC_Sleep_Mode /* Wake up from sleep with Interrupt: 1+4+4T, jmp, rti, ldi, out takes 18 clock tics, */ /* 5+1 clock tics (sts,rjmp,out) are needed for instructions before the current is switched off. */ #if F_CPU == 8000000UL /* Restart from sleep needs more than 2us, that is more than one ADC-clock tic in fast mode. */ /* More than one clock delay for the restart of ADC is required, 3.5 instead of 2.5 ADC clock delay */ call wait4us; /* wait4us(); // with only 3 us delay the voltage goes down before SH */ /* delay 4us + 1 clock tics (CALL instead of RCALL) = 4.125 us @ 8 MHz */ /* + 24 clock tics delay from interrupt return, +3.0us = 7.125 us + */ /* 6.75us - */ /* 6.875us ? */ /* 7.0us + */ #endif #if F_CPU == 16000000UL call wait3us; /* wait3us(); // with only 3 us delay the voltage goes down before SH */ /* delay 3us + 1 clock tics (CALL instead of RCALL) = 3.0625 us */ /* + 24 clock tics delay from interrupt return, +1.5us = 4.5625 us */ call wait500ns; /* wait500ns(); // 5.125 us + */ /* 4.9375us - */ /* 5.0625us ? */ /* 5.1875 us + */ #endif #else /* Polling mode, lds,sbrc,sts,rjmp and out Instructions are 9 clock tics */ #if F_CPU == 8000000UL call wait4us; // with only 3 us delay the voltage goes down before SH /* delay 4us + 1 clock tic (CALL instead of RCALL) = 4.125 us @ 8 MHz */ /* + 9 clock tics delay from while loop, +1.125us = 5.25 us + */ /* 4.875us - */ /* 5.0 us ? */ /* 5.125us + */ #endif #if F_CPU == 16000000UL call wait4us; // with only 18 us delay the voltage goes down before SH /* delay 4us + 1 clock tics (CALL instead of RCALL) = 4.0625 us */ /* + 9 clock tics delay from while loop, +0.5625us = 4.625 us */ push r24; /* 4.8125 us */ pop r24; /* 4.9375 us */ wdr ; /* wdt_reset(); // 5.0 us - */ wdr ; /* wdt_reset(); // 5.0625us ? */ wdr ; /* wdt_reset(); // 5.125 us + */ #endif #endif .endm //================================================================= //================================================================= //void GetESR() { .section .text GetESR: push r2 push r3 push r4 push r5 push r6 push r7 push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 push r16 push r17 push r29 push r28 in r28, _SFR_IO_ADDR(SPL); in r29, _SFR_IO_ADDR(SPH); sbiw r28, 0x1a; in r0, _SFR_IO_ADDR(SREG); cli out _SFR_IO_ADDR(SPH), r29; out _SFR_IO_ADDR(SREG), r0; out _SFR_IO_ADDR(SPL), r28; lds r18, cap+cval_max; /* cap_val_nF = cap.cval_max; */ lds r19, cap+cval_max+1; lds r20, cap+cval_max+2; lds r21, cap+cval_max+3; lds r17, cap+cpre_max; /* prefix = cap.cpre_max; */ rjmp ad_35ba; ad_35ac: movw r24, r20; /* cval /= 10; // reduce value by factor ten */ movw r22, r18 ldi r18, 0x0A; 10 mov r19, zero_reg mov r20, zero_reg mov r21, zero_reg call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ subi r17, 0xFF; /* prefix++; // take next decimal prefix */ ad_35ba: cpi r17, -9; /* while (prefix < -9) { // set cval to nF unit */ brlt ad_35ac; /* } */ std Y+cap_val_nF, r18 std Y+cap_val_nF+1, r19 std Y+cap_val_nF+2, r20 std Y+cap_val_nF+3, r21 cpi r18, lo8(1800/4); /* if (cap_val_nF < (1800/4)) return; //capacity lower than 1.8 uF */ ldi r22, hi8(1800/4) cpc r19, r22 cpc r20, zero_reg cpc r21, zero_reg brcc ad_35e4 rjmp ad_exit; ad_35e4: #ifdef ADC_Sleep_Mode ldi r24, (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ #endif cpi r18, lo8((1800*2)+1); /* if (cap_val_nF > (1800*2)) { */ ldi r23, hi8((1800*2)+1); cpc r19, r23 cpc r20, zero_reg cpc r21, zero_reg brcs ad_35fe ldi r24, 0x01; 1 std Y+big_cap, r24; /* big_cap = 1; */ cpi r18, lo8(50000); /* if (cap_val_nF > (50000)) { */ ldi r23, hi8(50000); cpc r19, r23 cpc r20, zero_reg cpc r21, zero_reg brcs not_very_big ldi r24, 0x02; 2 std Y+big_cap, r24; /* big_cap = 2; // very big capacitor */ not_very_big: /* normal ADC-speed, ADC-Clock 8us */ #ifdef ADC_Sleep_Mode ldi r25, (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | AUTO_CLOCK_DIV; /* enable ADC and Interrupt */ mov StartADCmsk, r25 sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #else ldi r18, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable and start ADC */ mov StartADCmsk, r18 #endif rjmp ad_3604; /* } else { */ ad_35fe: /* fast ADC-speed, ADC-Clock 2us */ #ifdef ADC_Sleep_Mode ldi r25, (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | FAST_CLOCK_DIV; /* enable ADC and Interrupt */ mov StartADCmsk, r25 sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #else ldi r25, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | FAST_CLOCK_DIV; /* enable and start ADC */ mov StartADCmsk, r25 #endif std Y+big_cap, zero_reg; /* big_cap = 0 */ /* } */ ad_3604: ldi r24, lo8(ESR_str); ldi r25, hi8(ESR_str); #ifdef USE_EEPROM call lcd_fix_string; /* lcd_MEM_string(ESR_str); // " ESR=" */ #else call lcd_mem_string; /* lcd_MEM_string(ESR_str); // " ESR=" */ #endif lds r14, cap+ca; /* LoADC = pgm_read_byte(&PinADCtab[cap.ca]) | TXD_MSK; */ mov SelectLowPin,r14 LDIZ PinADCtab; add r30, r14 adc r31, zero_reg lpm r24, Z+; ori r24, TXD_MSK; std Y+LoADC, r24; lds r15, cap+cb; /* HiADC = pgm_read_byte(&PinADCtab[cap.cb]) | TXD_MSK; */ mov SelectHighPin,r15 LDIZ PinADCtab; add r30, r15 adc r31, zero_reg lpm r24, Z+; ori r24, TXD_MSK; std Y+HiADC, r24; LDIZ PinRLtab; /* LoPinR_L = pgm_read_byte(&PinRLtab[cap.ca]); //R_L mask for LowPin R_L load */ add r30, r14 adc r31, zero_reg lpm LoPinR_L, Z+; LDIZ PinRLtab; /* HiPinR_L = pgm_read_byte(&PinRLtab[cap.cb]); //R_L mask for HighPin R_L load */ add r30, r15 adc r31, zero_reg lpm HiPinR_L, Z+; #if (PROCESSOR_TYP == 644) || (PROCESSOR_TYP == 1280) /* ATmega640/1280/2560 1.1V Reference with REFS0=0 */ // SelectLowPin = (cap.ca | (1<<REFS1) | (0<<REFS0)); // switch ADC to LowPin, Internal Ref. ldi r25, (1<<REFS1)|(0<<REFS0); 0xC0 or SelectLowPin, r25 // SelectHighPin = (cap.cb | (1<<REFS1) | (0<<REFS0)); // switch ADC to HighPin, Internal Ref. or SelectHighPin, r25 #else // SelectLowPin = (cap.ca | (1<<REFS1) | (1<<REFS0)); // switch ADC to LowPin, Internal Ref. ldi r25, (1<<REFS1)|(1<<REFS0); 0xC0 or SelectLowPin, r25 // SelectHighPin = (cap.cb | (1<<REFS1) | (1<<REFS0)); // switch ADC to HighPin, Internal Ref. or SelectHighPin, r25 #endif // Measurement of ESR of capacitors AC Mode ldi r24, 0x01; /* sumvolt0 = 1; // set sum of LowPin voltage to 1 to prevent divide by zero */ mov r14, r24 mov r15, zero_reg mov r16, zero_reg mov r17, zero_reg std Y+sumvolt1, r24; /* sumvolt1 = 1; // clear sum of HighPin voltage with current */ // // offset is about (x*10*200)/34000 in 0.01 Ohm units std Y+sumvolt1+1, zero_reg; std Y+sumvolt1+2, zero_reg; std Y+sumvolt1+3, zero_reg; std Y+sumvolt2, zero_reg; /* sumvolt2 = 0; // clear sum of HighPin voltage without current */ std Y+sumvolt2+1, zero_reg; std Y+sumvolt2+2, zero_reg; std Y+sumvolt2+3, zero_reg; call EntladePins; /* EntladePins(); // discharge capacitor */ ldi r24, TXD_VAL; out _SFR_IO_ADDR(ADC_PORT), r24; /* ADC_PORT = TXD_VAL; // switch ADC-Port to GND */ sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; // set Mux input and Voltage Reference to internal 1.1V */ #ifdef NO_AREF_CAP call wait100us; /* time for voltage stabilization */ #else call wait10ms; /* time for voltage stabilization with 100nF */ #endif // Measurement frequency is given by sum of ADC-Reads < 680 Hz for normal ADC speed. // For fast ADC mode the frequency is below 2720 Hz (used for capacity value below 3.6 uF). // ADC Sample and Hold (SH) is done 1.5 ADC clock number after real start of conversion. // Real ADC-conversion is started with the next ADC-Clock (125kHz) after setting the ADSC bit. eor r13, r13; /* for(ii=0;ii<MAX_CNT;ii++) { */ // when time is too short, voltage is down before SH of ADC // when time is too long, capacitor will be overloaded. // That will cause too high voltage without current. ldi r27, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | FAST_CLOCK_DIV; /* enable ADC and start with ADSC */ mov r9, r27 // adcv[0] = ADCW; // Voltage LowPin with current // ADMUX = SelectHighPin; ldi r26, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable ADC and start with ADSC */ mov r8, r26 /* ********* Forward direction, connect Low side with GND *********** */ ad_3692: ldd r19, Y+LoADC; out _SFR_IO_ADDR(ADC_DDR), r19; /* ADC_DDR = LoADC; // switch Low-Pin to output (GND) */ sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; */ StartADCwait /* start ADC and wait */ ;======= /* while (1) { */ while_lop1: wdr ; /* wdt_reset(); */ sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; */ out _SFR_IO_ADDR(R_PORT), HiPinR_L; /* R_PORT = HiPinR_L; // switch R-Port to VCC */ out _SFR_IO_ADDR(R_DDR), HiPinR_L; /* R_DDR = HiPinR_L; // switch R_L port for HighPin to output (VCC) */ StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds adcv0L, ADCW; /* adcv[0] = ADCW; // Voltage LowPin with current */ lds adcv0H, ADCW+1 sts ADMUX, SelectHighPin; /* ADMUX = SelectHighPin; */ ldd r20, Y+big_cap; /* if (!big_cap) { */ and r20, r20 brne ad_big1 /* **** Polling mode, small cap **** */ StartADCwait /* start ADC and wait */ sts ADCSRA, r9; /* ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | FAST_CLOCK_DIV; // enable ADC and start */ DelaySmallCap; /* wait the time defined by macro */ rjmp ad_swoff1; /* } else { */ ad_big1: /* **** Polling mode, big cap **** */ StartADCwait /* start ADC and wait */ // Start Conversion, real start is next rising edge of ADC clock sts ADCSRA, r8; /* ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; // enable ADC and start */ DelayBigCap; /* wait the time defined by macro */ /* } */ ad_swoff1: out _SFR_IO_ADDR(R_DDR), zero_reg; /* R_DDR = 0; // switch current off, SH is 1.5 ADC clock behind real start */ out _SFR_IO_ADDR(R_PORT), zero_reg; /* R_PORT = 0; */ ad_370c: lds r24, ADCSRA; /* while (ADCSRA&(1<<ADSC)); // wait for conversion finished */ sbrc r24, ADSC rjmp ad_370c lds r18, ADCW; /* adcv[1] = ADCW; // Voltage HighPin with current */ lds r19, ADCW+1; #ifdef ADC_Sleep_Mode sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #endif StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds r24, ADCW; /* adcv[2] = ADCW; // Voltage HighPin without current */ lds r25, ADCW+1; cpi r24, 0x03; /* if (adcv[2] > 2) break; // at least more than two digits required */ cpc r25, zero_reg brcc end_while1; rjmp while_lop1; /* } // end while (1) */ ;======= end_while1: // sumvolt0 += adcv[0]; // add sum of both LowPin voltages with current // adcv0 = r2/r3 // sumvolt1 += adcv[1]; // add HighPin voltages with current // adcv1 = r18/r19 std Y+adcvv1, r18; std Y+adcvv1+1, r19; // sumvolt2 += adcv[2]; // capacitor voltage without current // adcv2 = R24/r25 std Y+adcvv2, r24; std Y+adcvv2+1, r25; /* ********* Reverse direction, connect High side with GND *********** */ ldd r19, Y+HiADC; /* ADC_DDR = HiADC; // switch High Pin to GND */ out _SFR_IO_ADDR(ADC_DDR), r19; StartADCwait /* start ADC and wait */ ;======= /* while (1) { */ while_lop2: wdr ; /* wdt_reset(); */ sts ADMUX, SelectHighPin; /* ADMUX = SelectHighPin; */ out _SFR_IO_ADDR(R_PORT), LoPinR_L; /* R_PORT = LoPinR_L; */ out _SFR_IO_ADDR(R_DDR), LoPinR_L; /* R_DDR = LoPinR_L; // switch LowPin with 680 Ohm to VCC */ StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds r22, ADCW; /* adcv[0] = ADCW; // Voltage HighPin with current */ lds r23, ADCW+1; sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; */ ldd r20, Y+big_cap ; /* if (!big_cap) { */ and r20, r20 brne ad_big2 // ****** Polling mode small cap StartADCwait /* start ADC and wait */ sts ADCSRA, r9; /* ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | FAST_CLOCK_DIV; // enable ADC and start */ DelaySmallCap; /* wait the time defined by macro */ rjmp ad_swoff2; /* } else { */ ad_big2: // ****** Polling mode big cap StartADCwait /* start ADC and wait */ sts ADCSRA, r8; /* ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; // enable ADC and start with ADSC */ DelayBigCap; /* wait the time defined by macro */ /* } */ ad_swoff2: out _SFR_IO_ADDR(R_DDR), zero_reg; // switch current off, SH is 1.5 ADC clock ticks behind real start out _SFR_IO_ADDR(R_PORT), zero_reg; ad_37f4: lds r24, ADCSRA; /* while (ADCSRA&(1<<ADSC)); // wait for conversion finished */ sbrc r24, ADSC rjmp ad_37f4 lds r20, ADCW; /* adcv[1] = ADCW; // Voltage LowPin with current */ lds r21, ADCW+1; #ifdef ADC_Sleep_Mode sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #endif StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds r18, ADCW; /* adcv[2] = ADCW; // Voltage LowPin without current */ lds r19, ADCW+1; cpi r18, 0x03; /* if (adcv[2] > 2) break; // at least more than two digits required */ cpc r19, zero_reg brcc end_while2; rjmp while_lop2; /* } // end while (1) */ ;======= end_while2: out _SFR_IO_ADDR(R_DDR), zero_reg; /* R_DDR = 0; // switch current off */ movw r24, r22; /* sumvolt0 += adcv[0]; // add LowPin voltages with current */ add r24, adcv0L; /* // add sum of both LowPin voltages with current */ adc r25, adcv0H add r14, r24 adc r15, r25 adc r16, zero_reg adc r17, zero_reg std Y+sumvolt0, r14 std Y+sumvolt0+1, r15 std Y+sumvolt0+2, r16 std Y+sumvolt0+3, r17 ldd r24, Y+adcvv1; /* sumvolt1 += adcv[1]; // add HighPin voltages with current */ ldd r25, Y+adcvv1+1; add r24, r20 adc r25, r21 ldd r20, Y+sumvolt1; /* sumvolt1 += adcv[1]; // add HighPin voltages with current */ ldd r21, Y+sumvolt1+1; ldd r22, Y+sumvolt1+2; ldd r23, Y+sumvolt1+3; add r20, r24 adc r21, r25 adc r22, zero_reg adc r23, zero_reg std Y+sumvolt1, r20; std Y+sumvolt1+1, r21; std Y+sumvolt1+2, r22; std Y+sumvolt1+3, r23; ldd r24, Y+adcvv2; /* // add HighPin voltages without current */ ldd r25, Y+adcvv2+1; 0x11 add r24, r18 adc r25, r19 ldd r20, Y+sumvolt2; /* sumvolt2 += adcv[2]; // add HighPin voltages without current */ ldd r21, Y+sumvolt2+1; ldd r22, Y+sumvolt2+2; ldd r23, Y+sumvolt2+3; add r20, r24 adc r21, r25 adc r22, zero_reg adc r23, zero_reg std Y+sumvolt2, r20 ; std Y+sumvolt2+1, r21; std Y+sumvolt2+2, r22; std Y+sumvolt2+3, r23; // Measurement frequency is given by sum of ADC-Reads < 680 Hz for normal ADC speed. // For fast ADC mode the frequency is below 2720 Hz (used for capacity value below 3.6 uF). // ADC Sample and Hold (SH) is done 1.5 ADC clock number after real start of conversion. // Real ADC-conversion is started with the next ADC-Clock (125kHz) after setting the ADSC bit. inc r13; /* for( ;ii<MAX_CNT;ii++) */ mov r21, r13 cpi r21, MAX_CNT; breq ad_38ac rjmp ad_3692; /* } // end for */ ad_38ac: #ifdef ESR_DEBUG movw r22, r14; /* DisplayValue(sumvolt0,0,'L',4); */ movw r24, r16; ldi r20, 0; ldi r18, 'L'; ldi r16, 4 ; call DisplayValue #endif ldd r10, Y+cap_val_nF; ldd r11, Y+cap_val_nF+1; ldd r12, Y+cap_val_nF+2; ldd r13, Y+cap_val_nF+3; ldd r22, Y+big_cap; /* if (big_cap) { */ and r22, r22 breq is_small // HighPin Voltage, which is usually 2 * 14 * 8 us = 224 us. // With the loading of the capacitor the current will sink, so we get a too high voltage at // the LowPin. The velocity of degration is inversely proportional to time constant (represented by capacity value). // Time constant for 1uF & 720 Ohm is 720us // // sumvolt0 -= (sumvolt0 * 150UL) / cap_val_nF; // Version 1.04k ldi r18, lo8(310); /* sumvolt0 -= (sumvolt0 * 345UL) / cap_val_nF; */ ldi r19, hi8(310); rjmp ad_38dc /* } else { */ is_small: ldi r18, lo8(105); /* sumvolt0 -= (sumvolt0 * 105UL) / cap_val_nF; */ ldi r19, hi8(105); ad_38dc: ldi r20, 0x00; ldi r21, 0x00; ldd r22, Y+sumvolt0 ldd r23, Y+sumvolt0+1 ldd r24, Y+sumvolt0+2 ldd r25, Y+sumvolt0+3 call __mulsi3; /* r22:25 = r22:25 * r18:21 */ movw r18, r10; /* cap_val_nF */ movw r20, r12 call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ ldd r10, Y+sumvolt0; ldd r11, Y+sumvolt0+1; ldd r12, Y+sumvolt0+2; ldd r13, Y+sumvolt0+3; sub r10, r18; /* r10:13 == sumvolt0 -= */ sbc r11, r19 sbc r12, r20 sbc r13, r21 /* } */ #ifdef ESR_DEBUG call lcd_line3; ldd r22, Y+sumvolt1; /* DisplayValue(sumvolt1,0,'H',4); */ ldd r23, Y+sumvolt1+1; ldd r24, Y+sumvolt1+2; 0 ldi r25, 0x00; 0 ldi r20, 0; ldi r18, 'H'; ldi r16, 4 ; call DisplayValue ldi r24, ' ' call lcd_data #endif ldi r24, lo8(EE_ESR_ZERO); /* esr0 = (int8_t)eeprom_read_byte(&EE_ESR_ZERO); */ ldi r25, hi8(EE_ESR_ZERO); call eeprom_read_byte; mov r2, r24 // // sumvolt0 += (((long)sumvolt0 * esr0) / (RRpinMI * 10)); // subtract 0.23 Ohm from ESR, Vers. 1.04k // sumvolt2 += (((long)sumvolt0 * esr0) / (RRpinMI * 10)); // subtract 0.23 Ohm from ESR mov r22, r24 eor r23, r23 sbrc r22, 7 com r23 mov r24, r23 mov r25, r23 movw r18, r10; /* sumvolt0 */ movw r20, r12; call __mulsi3; /* r22:25 = r22:25 * r18:21 */ #if RRpinMI == PIN_RM ldi r18, lo8(RRpinMI*10) ldi r19, hi8(RRpinMI*10) #else lds r4, RRpinMI lds r5, RRpinMI+1 add r4,r4; RRpinMI*2 adc r5,r5 movw r18,r4 ldi r30,4 ad_3924: add r18,r4; + (2*RRpinMI) adc r19,r5 dec r30 brne ad_3924 #endif movw r4,r18; /* r4:5 = 10 * RRpinMI */ ldi r20, 0x00; ldi r21, 0x00; call __divmodsi4; /* r18:21 = r22:25 / r18:21 */ ldd r24, Y+sumvolt2 ; ldd r25, Y+sumvolt2+1; ldd r26, Y+sumvolt2+2; ldd r27, Y+sumvolt2+3; add r18, r24 /* r18 == sumvolt2 += */ adc r19, r25 adc r20, r26 adc r21, r27 std Y+sumvolt2, r18; std Y+sumvolt2+1, r19; std Y+sumvolt2+2, r20; std Y+sumvolt2+3, r21; #ifdef ESR_DEBUG movw r22, r10; /* DisplayValue(sumvolt0,0,'C',4); */ movw r24, r12; ldi r20, 0; ldi r18, 'C'; ldi r16, 4 ; call DisplayValue #endif ldd r6, Y+sumvolt1; /* if (sumvolt1 > sumvolt0) { */ ldd r7, Y+sumvolt1+1; ldd r8, Y+sumvolt1+2; ldd r9, Y+sumvolt1+3; cp r10, r6 cpc r11, r7 cpc r12, r8 cpc r13, r9 brcc ad_396c sub r6, r10; /* sumvolt1 -= sumvolt0; // difference HighPin - LowPin Voltage with current */ sbc r7, r11 sbc r8, r12 sbc r9, r13 rjmp ad_3972; /* } else { */ ad_396c: eor r6, r6; /* sumvolt1 = 0; */ eor r7, r7 movw r8, r6 ad_3972: #ifdef ESR_DEBUG call lcd_line4; movw r22, r6; /* DisplayValue(sumvolt1,0,'d',4); */ movw r24, r8 ldi r20, 0; ldi r18, 'd'; ldi r16, 4 ; call DisplayValue ldi r24, ' ' call lcd_data ldd r22, Y+sumvolt2; /* DisplayValue(sumvolt2,0,' ',4); */ ldd r23, Y+sumvolt2+1; ldd r24, Y+sumvolt2+2; ldd r25, Y+sumvolt2+3; ldi r20, 0; ldi r18, ' '; ldi r16, 4 ; call DisplayValue #endif movw r22, r4 ldi r24, 0x00; ldi r25, 0x00; /* r22:25 = 10 * (unsigned long)RRpinMI) */ /* jj = 0; */ ldd r14, Y+sumvolt2; /* if (sumvolt1 >= sumvolt2) { */ ldd r15, Y+sumvolt2+1; ldd r16, Y+sumvolt2+2; ldd r17, Y+sumvolt2+3; cp r6, r14; /* r6:9 = sumvolt1 */ cpc r7, r15 cpc r8, r16 cpc r9, r17 brcs ad_39c0 // mean voltage at the capacitor is higher with current // sumvolt0 is the sum of voltages at LowPin, caused by output resistance of Port // RRpinMI is the port output resistance in 0.1 Ohm units. // we scale up the difference voltage with 10 to get 0.01 Ohm units of ESR /* cap.esr = ((sumvolt1 - sumvolt2) * 10 * (unsigned long)RRpinMI) / sumvolt0; */ movw r18, r6 movw r20, r8 sub r18, r14; /* sumvolt1 - sumvolt2 */ sbc r19, r15 sbc r20, r16 sbc r21, r17 call __mulsi3; /* r22:25 = r22:25 * r18:21 */ movw r18, r10; /* r10:13 = sumvolt0 */ movw r20, r12 call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ sts cap+esr, r18; sts cap+esr+1, r19; movw r22, r18; /* DisplayValue(cap.esr,-2,LCD_CHAR_OMEGA,2); */ ldi r24, 0x00; 0 ldi r25, 0x00; 0 ldi r20, -2 ; 254 ldi r18, LCD_CHAR_OMEGA; ldi r16, 2 ; call DisplayValue rjmp ad_exit; /* } else { */ ad_39c0: /* jj = ((sumvolt2 - sumvolt1) * 10 * (unsigned long)RRpinMI) / sumvolt0; */ movw r18, r14 movw r20, r16 sub r18, r6 sbc r19, r7 sbc r20, r8 sbc r21, r9 call __mulsi3; /* r22:25 = r22:25 * r18:21 */ movw r18, r10 movw r20, r12 call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ mov r17, r18 ldi r24,'0'; /* lcd_data('0'); */ call lcd_data mov r24, r17; /* if ((jj < 100) && (jj > 0)) { */ subi r24, 0x01; 1 cpi r24, 0x63; 99 brcc ad_exit; ldd r19, Y+big_cap; /* if (big_cap != 2) { */ cpi r19, 0x02; /* (cap_val_nF > (50000)) */ brne ad_3a0e ldi r24,'?'; /* lcd_data('?'); // mark ESR zero correction */ call lcd_data mov r22, r2; /* esr0 -= jj; // correct ESR_ZERO by negative resistance */ sub r22, r17 ldi r24, lo8(EE_ESR_ZERO); /* eeprom_write_byte((uint8_t *)(&EE_ESR_ZERO), (int8_t)esr0); */ ldi r25, hi8(EE_ESR_ZERO); /* // fix new zero offset */ call eeprom_write_byte rjmp ad_exit; /* } else { */ ad_3a0e: ldi r24,'!'; /* lcd_data('!'); // mark ESR zero without correction */ call lcd_data // return; /* } } } */ ad_exit: #ifdef ADC_Sleep_Mode out _SFR_IO_ADDR(SMCR), zero_reg; /* SMCR = 0 */ #endif adiw r28, 0x1a; 26 in r0, _SFR_IO_ADDR(SREG); 63 cli out _SFR_IO_ADDR(SPH), r29; 62 out _SFR_IO_ADDR(SREG), r0; 63 out _SFR_IO_ADDR(SPL), r28; 61 pop r28 pop r29 pop r17 pop r16 pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop r7 pop r6 pop r5 pop r4 pop r3 pop r2 ret .endfunc
wagiminator/ATmega-Transistor-Tester
1,235
software/sources/i2lcd.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include "config.h" .GLOBAL u2lcd .GLOBAL u2lcd_space .extern lcd_data .extern lcd_string .extern lcd_space .func i2lcd ; use allways rcall for nearby functions #define RCALL rcall .section .text .GLOBAL i2lcd i2lcd: ; void i2lcd(int iw) #if FLASHEND > 0x1fff ;; movw r20, r24 sbrs r25, 7 rjmp to_lcd ; if (iw >= 0) { ; // negativ value, output - and invert iw push r24 ; save r24:r25 push r25 ldi r24,'-' ; 45 RCALL lcd_data ; lcd_data('-'); uses r22 pop r25 ; recall r25:r24 pop r24 ; old r24 com r25 neg r24 sbci r25,-1 ; iw = - iw #endif u2lcd: ; void i2lcd(uint16_t iw) to_lcd: ; void i2lcd(uint16_t iw) ldi r22, lo8(outval) ;0x0F ldi r23, hi8(outval) ;0x01 ldi r20, 10 ldi r21, 0x00 ; 0 ACALL utoa ; utoa(iw, outval, 10); //output voltage to string RCALL lcd_string ;lcd_string(utoa(iw, outval, 10)); //output correction voltage ret #if FLASHEND > 0x1fff .GLOBAL i2lcd_space i2lcd_space: RCALL i2lcd rjmp space_ret ; use return from u2lcd_space u2lcd_space: RCALL i2lcd space_ret: RCALL lcd_space ret #endif .endfunc
wagiminator/ATmega-Transistor-Tester
14,195
software/sources/samplingADC.S
// June 2015 - Jan 2016, pa3fwm@amsat.org #ifdef SamplingADC_CNT #include "samplingADC_cnt.S" /* take replacement with counter1 use */ #else #ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include "config.h" #include <stdlib.h> .GLOBAL samplingADC_freqgen .func samplingADC_freqgen .endfunc .GLOBAL samplingADC_freqgen_sck .func samplingADC_freqgen_sck .endfunc .GLOBAL samplingADC .func samplingADC #if (TICS_PER_ADC_CLOCK != 128) && (TICS_PER_ADC_CLOCK != 64) #error Unsupported clock frequency #endif #define TICS_PER_ADC_CYCLE 13*TICS_PER_ADC_CLOCK #define Lessdelay (256-2*TICS_PER_ADC_CLOCK) .section .progmem.gcc ; We put this code not simply generically in .text, but in .progmem.gcc. ; Gcc's linker script forces this section to be immediately after the interrupt vectors, ; and it seems in case of the transistortester code nothing else ends up in this section. ; We also put the genfreq code at the start of this file, so it will be the first thing ; after the vectors. This guarantees that the condition on genfreq_jmpbase (see below) is satisfied. #ifdef WITH_XTAL genfreq: ; generate signal with frequency CPUclock / ( 8 + R11 + R10/256 ) ; generate r19 periods ; to do this, we have a loop where we jump back to r27:31 in "normal" case, or (r27:31)-1 in case of "carry" of the fractional bits mov r19, r0 ldi r27, lo8(gs(genfreq_jmpbase)) sub r27, r11 ldi r26, 0 ; accumulated backlog push r30 push r31 ldi r31, hi8(gs(genfreq_jmpbase)) ; ; NOTE: we assume that lo8(gs(genfreq_jmpbase)) > 8 so r31 never needs to be updated ; this is guaranteed due to the placement in .progmem.gcc, see the above comment. ; nop nop nop nop nop nop nop mov r30, r27 genfreq_jmpbase: AOUT R_PORT, R18 ; = Rport_1 AOUT R_PORT, R14 ; = Rport_0 dec r19 breq genfreq_end1 add r26, r10 sbc r30, r1 ijmp genfreq_end1: AOUT R_DDR, R16 ; R_DDR = Rddr_1 ; switch to "active" state (relatively high impedance in case of crystal measurement) immediately after the last impulse, to preserve a positive DC component pop r31 pop r30 sbrs r24, smplADC_sck ; should we short-circuit the DUT (crystal)? rjmp genfreq_end AIN r26, ADC_DDR ori r26, (1<<TP1)|(1<<TP2)|(1<<TP3) AOUT ADC_DDR,r26 rjmp genfreq_end #endif samplingADC: samplingADC_freqgen: samplingADC_freqgen_sck: ; prototypes for C declared in tt_function.h ; documentation is also there ;uint16_t samplingADC(R24:25 what, R22:23 array[], R20 nn, R18 Rport_1, R16 Rddr_1, R14 Rport_0, R12 Rddr_0, R10:11 freq, R8 shortcircuitduration ) {} ; the last two arguments are only used WITH_XTAL, and are optional (can be omitted if not needed; registers will not be clobbered) #ifdef WITH_XTAL push r4 ; r4:5 will be used for the high-pass filter push r5 push r17 mov r5, r1 dec r5 ; set bit 7 in r5 to mark it for initialization sbrs r24, smplADC_sck ; if we'll need to short-circuit the DUT later on, store the correct value of ADC_DDR in r9 rjmp L30a push r9 AIN r9, ADC_DDR ; L30a: push r7 lds r7, ADMUX #endif ; r25 is span mov r30, r22 ; r31:r30 := ptr mov r31, r23 cpi r25, 0 ; set nonsensical span of 0 to 1 brne L16 inc r25 L16: AOUT R_PORT, R14 ; Rport_0 AOUT R_DDR, R12 ; Rddr_0 ldi r27, (1<<ADEN) | (1<<ADSC) | (1<<ADATE) | (1<<ADIF) | (0<<ADIE) | AUTO_CLOCK_DIV; sts ADCSRA, r27 ; start first ADC with ext trigger, but start immediately also, to get done that first conversion which takes extra long ldi r26, (1<<ADTS2) | (0<<ADTS1) | (1<<ADTS0); sts ADCSRB, r26 ; trigger source is COUNTER1 compare match B ldi r26, (1<<WGM12) sts TCCR1B, r26 ; TCCR1B = 0; stop counter1 sts TCCR1A, r1 ; TCCR1A = 0; set counter1 to Clear Timer on Compare Match mode ldi r26, 0xff sts TCNT1H, r26 ; set initial counter to -1 sts TCNT1L, r26 ldi r26, (1<<OCF1B)|(1<<OCF1A) sts TIFR1, r26 ; reset both counter compare interrupts, otherwise ADC might be started prematurely sts OCR1BH, r1 ; schedule start of ADC cycle at counter=0, i.e., essentially immediately sts OCR1BL, r1 ; #ifdef WITH_XTAL sbrs r24, smplADC_many ; if we have the long excitation rjmp L20a ldi r26, 3 ; schedule start of ADC cycle at counter=3*256 sts OCR1BH, r26 dec r26 sts TCNT1H, r26 ; and make sure TCNT1 is initialized sucht that this is still essentially immediately ldi r26, 0xff sts TCNT1L, r26 L20a: #endif #ifdef WITH_XTAL ; compute number of cycles for genfreq: push r24 ; we need registers r24 and r25 for calling __udivmodhi4 push r25 ldi r25, 184/4 ; total duration should be at most 255 cycles, but there's some 66 cycles of overhead (determined experimentally) sbrc r24, smplADC_many ; except in case of long set of pulses for crystal excitation, then ldi r25, (184+3*256)/4 ; total duration should be at most 4*256 cycles L20: ; note that we've divided r25:24 by 4 in the above, so it fits in 16 bits ldi r24, 0 movw r22,r10 subi r23, -8 ; period is 8+r11+r10/256 lsr r23 ; divide period by 4 since we've divided duration by 4 too ror r22 lsr r23 ror r22 call __udivmodhi4 mov r0,r22 ; store number of pulses in r0 inc r0 ; 1 more pulse than periods pop r25 pop r24 #endif ; prepare timing and registers for main loop ; r27:26 will contain the TOP value for the counter, i.e., 1 less than the pulse-generation period ldi r27, hi8(TICS_PER_ADC_CYCLE-1) ldi r26, lo8(TICS_PER_ADC_CYCLE-1) sub r26, r25 ; this defaults to 1663-span, but may need to be incremented if measurement will take longer due to large span ldi r21, 1 ; r21 will contain number of ADC readings per pulse mov r19, r25 ; load span into r19; total measurement will cover r19*nn tics, which is upperbounded by 256*r19 ; one ADC cycle is 13*128 (or 13*64) tics, but we need some time for generating the pulse, so can fit say at most 10*128 = 5*256 tics (or 8*64 = 2*256; 10*64 isn't a multiple of 256, so would require more code) ; NEW: leave a bit more space so we can also do the long train of pulses for crystals L14: cpi r19, (1+10*TICS_PER_ADC_CLOCK/256) ; if "remaining" span <=5 (or <=2), we're fine, don't need to increase pulse generation period #ifdef WITH_XTAL sbrc r24, smplADC_many cpi r19, (2+2*TICS_PER_ADC_CLOCK/256) ; in case of long pulse train: if "remaining" span <=3 (or <=2), we're fine, don't need to increase pulse generation period #endif brmi L13 subi r26, lo8(-TICS_PER_ADC_CYCLE) ; otherwise, extend pulse generation period by 1664 sbci r27, hi8(-TICS_PER_ADC_CYCLE) inc r21 ; increment number of ADC readings per pulse subi r19, 3*(TICS_PER_ADC_CLOCK/64) ; each extra ADC cycle included in pulse generation period makes space for 13*128 (or 13*64) tics; for simplicity we (safely) calculate as if it were 12*128 = 6*256 (or 12*64 = 3*256) rjmp L14 ; check whether this was enough L13: sts OCR1AH, r27 ; store calculated TOP value for counter 1 sts OCR1AL, r26 ; wait_adc: lds r26, ADCSRA sbrs r26, ADIF rjmp wait_adc ; wait until the initial conversion finishes ldi r27, (1<<ADEN) | (1<<ADATE) | (1<<ADIF) | (0<<ADIE) | AUTO_CLOCK_DIV; sts ADCSRA, r27 ; reset ADC interrupt flag ldi r26,(1<<OCIE1A) sts TIMSK1, r26 ; disable counter1 compare B Interrupt (used to trigger ADC), enable counter1 compare A Interrupt (used to exit sleep to generate next pulse) ldi r26, (1<<CS10)|(1<<WGM12) sts TCCR1B, r26 ; start counter1 at full speed ldi r22, 2 ; skip first ADC result since it is nonsense (it predates the start of the pulse or step) ldi r26, 0 ; switch ADC to free-running mode (we can do that here because can be sure that by now it has been triggered) sts ADCSRB, r26 ; ; we'll have counter1 counting up from 0 to about 1663 (or multiples of that) ; each time it overflows, we'll start our signal for "exciting" the DUT ; first sample will be taken 2*128 clockcycles after triggering ; so this whole signal generation procedure should take 256 clockcycles ; note: there's some uncertainty due to the unknown time the interrupt handler takes, which may be compiler-dependent ; at 8 MHz, the first sample is taken after only 128 clockcycles; this is taken into account via the Lessdelay macro ; we have the following excitation options, governed by the "what" parameter: ; - 0 (default): step (Rddr_0 -> Rddr_1) and optionally single pulse (Rport_1) ; - smplADC_freq: bunch of pulses via Rport_1 ; - ... |smplADC_many: 4 times longer bunch of pulses via Rport_1 ; - ... |smplADC_sck: short-circuit the DUT for a while after applying pulses ; - smplADC_direct: single pulse via the ADC pins, i.e. with no series resistance ("direct" pulse) backtosleep: ldi r26, (1<<SE) sts SMCR, r26 sleep ; toggle output (back) to the idle state AOUT R_PORT, R14 ; Rport_0 AOUT R_DDR, R12 ; Rddr_0 sbrs r24, smplADC_direct rjmp stepresponse ; wait a bit less than 256 ticks; precise value determined experimentally, by looking at the sampled data and aligning start of response with first sample #define Delay_pulse (201-Lessdelay) ldi r26, (Delay_pulse/3) #if Delay_pulse%3>0 nop #endif #if Delay_pulse%3>1 nop #endif L11: dec r26 brne L11 ; do the "direct" pulse, i.e., apply the pulse via de ADC pins, with no series resistance push r30 push r31 AIN r30, ADC_DDR ; AIN r31, ADC_PORT ; ldi r26, (1<<TP3) ; sbrc R12, PIN_RL2 ; is the bit for TP2 resistor set? ldi r26, (1<<TP2) ; sbrc R12, PIN_RL1 ; ist the bit for TP3 resistor set? ldi r26, (1<<TP1) ; ; r26 now hold the bit for the direct ADC port mov r27, r31 ; ADC_PORT state or r27, r26 ; r27 is the for ADC port with HiPin set to 1 or r26, r30 ; r26 enables the HiPin and LoPin output, ADC_DDR AOUT ADC_PORT, r27 ; set Hipin to high AOUT R_DDR, R16 ; R_DDR = Rddr1 open all resistor ports AOUT ADC_DDR, r26 ; one clock tic high without resistor at HiPin, current about 5V/(42 Ohm)=119mA !!! AOUT ADC_DDR, r30 ; disable the HiPin output AOUT ADC_PORT, r31 ; reset Hipin to low pop r31 pop r30 rjmp waitevent backtosleep2: jmp backtosleep stepresponse: #ifdef WITH_XTAL sbrc r24,smplADC_freq rjmp genfreq #endif stepresponse2: ; wait a bit less than 256 ticks; precise value determined experimentally #ifdef WITH_XTAL #define Delay_step (211-Lessdelay) #else #define Delay_step (214-Lessdelay) #endif ldi r26, (Delay_step/3) #if Delay_step%3>0 nop #endif #if Delay_step%3>1 nop #endif L10: dec r26 brne L10 AOUT R_PORT, R18 ; = Rport_1 AOUT R_PORT, R14 ; = Rport_0 nop ; generate start of step signal ; this is (should be) aligned with the first sample AOUT R_DDR, R16 ; R_DDR = Rddr_1 genfreq_end: waitevent: ; waiting loop: we wait until either counter1 is almost going to be reset, or the AD converter has a result lds r26, TCNT1L ; need to read TCNT1L to latch TCNT1H lds r26, TCNT1H lds r27, OCR1AH inc r26 cp r26, r27 ; check if TCNT1H is getting near OCR1AH; if so, go to sleep to be sure not to miss the interrupt brcc backtosleep2 #ifdef WITH_XTAL sbrs r24, smplADC_sck ; are we doing a measurement involving short-circuiting the DUT (crystal)? rjmp L26 cp r26, r8 ; then check whether it's getting time to end the short-circuit brne L26 ; r8 determines how many times 256 clockcycles the short-circuit should last L27: ; we enter this point up to 256 clockcycles early lds r26, TCNT1L ; (need to read TCNT1L to latch TCNT1H) lds r26, TCNT1H cp r26, r8 ; busyloop until r26 exceeds r8; due to this busyloop there's a few cycles of uncertainty, but that doesn't matter for this application breq L27 AOUT ADC_DDR,r9 ; set ADC_DDR back to its original non-shortcircuiting value L26: #endif lds r26, ADCSRA ; otherwise: sbrs r26, ADIF ; check if conversion done (interrupt flag is raised) rjmp waitevent ; if not, go back to checking counter ; the ADC gives a result ldi r27, (1<<ADEN) | (1<<ADATE) | (1<<ADIF) | (0<<ADIE) | AUTO_CLOCK_DIV; sts ADCSRA, r27 ; reset ADC interrupt flag #ifdef WITH_XTAL sbrs r24,smplADC_mux ; do we need to toggle MUX? rjmp L23 ldi r23, 3 cpi r21, 2 ; if span so large that we have to discard one or more ADC readings per cycle: brcs L23 brne L24 ; if precisely one ADC reading per cycle to be discarded, r23=1, otherwise =3 ldi r23, 1 ; now r23 is the value of r21 (counter for ADC discarding) at which we have to set the ADMUX to its proper setting L24: mov r19, r7 cp r22, r23 breq L22 andi r19, 0xf8 ; set ADMUX to input 0 if we're going to discard the value L22: sts ADMUX, r19 L23: #endif ; now need to check whether we should read or discard it dec r22 ; r22 counts AD conversions within one pulse cycle brnewaitevent: brne waitevent ; if r22 not yet zero, it's not yet our turn lds r22, ADCL ; read ADC lds r23, ADCH #ifdef WITH_XTAL sbrs r5, 7 ; bit 7 of r5 is used as marker that we still need to initialize the DC level rjmp L25 movw r4, r22 lsl r4 ; r4:5 = r22:23 << 2 rol r5 ; rotate left through Carry lsl r4 rol r5 ; rotate left through Carry ;lsl r4 ;rol r5 L25: mov r17, r4 ; r4:5 contains "DC-level"<<2 mov r19, r5 lsr r19 ; shift >>2 ror r17 lsr r19 ror r17 ;lsr r19 ;ror r17 sbrc r24, smplADC_hpf sub r22, r17 ; subtract DC from sample sbrc r24, smplADC_hpf sbc r23, r19 add r4, r22 ; update DC<<2, namely dc := (sample-dc)/8 ; adc r5, r23 #endif ld r19, z ; and store, accumulating if that bit in r24 is set sbrc r24, smplADC_cumul add r22, r19 st z+, r22 ld r19, z sbrc r24, smplADC_cumul adc r23, r19 sbrs r24, smplADC_8bit st z+, r23 mov r22, r21 ; reinitialize r22 dec r20 ; decrement counter of remaining samples ; brne waitevent brne brnewaitevent end: AOUT TIMSK1, r1 ; disable counter1 interrupts AOUT TCCR1B, r1 ; stop counter1 ldi r27, AUTO_CLOCK_DIV; AOUT ADCSRA, r27 ; disable ADC #ifdef WITH_XTAL AOUT ADMUX, r7 pop r7 sbrs r24, smplADC_sck ; if possibly short-circuiting the DUT, restore ADC_DDR rjmp L30c AOUT ADC_DDR, r9 pop r9 L30c: pop r17 pop r5 pop r4 #endif ret #endif /* SamplingADC_CNT */
wagiminator/ATmega-Transistor-Tester
1,658
software/sources/get_log.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include "config.h" #include <stdlib.h> #include "config.h" #define Log_Tab_Distance 20 .GLOBAL get_log .func get_log .extern LogTab .section .text ; // get_log interpolate a table with the function -1000*log(1 - (permil/1000)) ; uint16_t get_log(uint16_t permil) { get_log: push r28 push r29 ldi r18, lo8(Log_Tab_Distance) ;0x14 ldi r19, hi8(Log_Tab_Distance) ;0x00 movw r22, r18 call __udivmodhi4 ; tabind = permil / Log_Tab_Distance; // index to table movw r26, r24 ; r26:27 = tabres = permil % Log_Tab_Distance; // fraction of table distance ; // interpolate the table of factors ; y1 = pgm_read_word(&LogTab[tabind]); // get the lower table value LDIZ LogTab; add r30, r22 adc r31, r23 add r30, r22 adc r31, r23 ; &LogTab[tabind] lpm r28, Z+ ; y1 = pgm_read_word(&LogTab[tabind]); // get the lower table value lpm r29, Z+ lpm r20, Z+ ; y2 = pgm_read_word(&LogTab[tabind+1]); // get the higher table value lpm r21, Z+ ; result = ((y2 - y1) * tabres ) / Log_Tab_Distance + y1; // interpolate sub r20, r28 ; (y2 - y1) sbc r21, r29 ; hi8(y2 - y1) mul r20, r26 ; * tabres (maximum 19) movw r24, r0 ; r24:25 = ((y2 - y1) * tabres ) mul r20, r27 ; hi8(tabres) add r25, r0 mul r21, r26 ; hi8(y2 - Y1) add r25, r0 eor r1, r1 movw r22, r18 ; Log_Tab_Distance call __udivmodhi4 ; ((y2 - y1) * tabres ) / Log_Tab_Distance add r22, r28 ; result = ((y2 - y1) * tabres ) / Log_Tab_Distance + y1; // interpolate adc r23, r29 movw r24, r22 ; return(result); pop r29 pop r28 ret .endfunc
wagiminator/ATmega-Transistor-Tester
2,082
software/sources/swuart.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include "config.h" #define bitcnt r18 #define temp r21 #define Txbyte r24 #define SER_PORT _SFR_IO_ADDR(SERIAL_PORT) #define SER_DDR _SFR_IO_ADDR(SERIAL_DDR) ;* Software-UART nach Atmel AVR-Application-Note AVR305 ;*************************************************************************** ;* ;* "putchar" ;* ;* This subroutine transmits the byte stored in the "Txbyte" register ;* Low registers used :None ;* High registers used :2 (bitcnt,Txbyte) ;* Pointers used :None ;* ;*************************************************************************** .func uart_putc .global uart_putc .extern wait100us .extern wait3us .section .text uart_putc: #if defined(WITH_UART) && (!defined(WITH_HARDWARE_SERIAL)) ; push bitcnt ; in temp,_SFR_IO_ADDR(SREG) push Txbyte ; save character push bitcnt ; save register used for bit count ldi bitcnt,10 ;1+8+sb (sb is # of stop bits) com Txbyte ;Inverte everything sbi SER_DDR,SERIAL_BIT ; enable output of serial bit sec ;Start bit putchar0: brcc putchar1 ;If carry set #ifdef SWUART_INVERT sbi SER_PORT,SERIAL_BIT ; send a '0' #else cbi SER_PORT,SERIAL_BIT ; send a '0' #endif rjmp putchar2 ;else putchar1: #ifdef SWUART_INVERT cbi SER_PORT,SERIAL_BIT ; send a '1' #else sbi SER_PORT,SERIAL_BIT ; send a '1' #endif nop putchar2: rcall wait100us ; about 9600 Baud #if F_CPU >= 8000000UL rcall wait3us #endif lsr Txbyte ;Get next bit dec bitcnt ;If not all bit sent brne putchar0 ; send next ;else pop bitcnt ; restore register used for bit count pop Txbyte ; restore character send ; out _SFR_IO_ADDR(SREG),temp ; pop bitcnt #endif /* defined(WITH_UART) && (!defined(WITH_HARDWARE_SERIAL)) */ #ifdef WITH_HARDWARE_SERIAL ; wait for empty transmit buffer w3: lds r25, UCSR0A sbrs r25, UDRE0 rjmp w3 ; wait AOUT UDR0, r24 ; put data to transmit buffer #endif /* def WITH_HARDWARE_SERIAL */ ret ; return .endfunc
wagiminator/ATmega-Transistor-Tester
5,524
software/sources/wait_for_key_ms.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <stdlib.h> #include "config.h" #include "lcd_defines.h" #ifdef WITH_ROTARY_SWITCH #warning Please use the C-version of this program, if you use the Rotary Switch! #error Modify your Makefile! #endif #define RCALL rcall #define MAX_CS 150 #define incre 6 .GLOBAL wait_for_key_ms #if INHIBIT_SLEEP_MODE .extern wait200ms .extern wait10ms #else .extern sleep_5ms #endif .func wait_for_key_ms .section .text ;/* wait max_time or previous key press */ ;/* max_time zero wait without time limit */ ;/* return value: !=0 == key is pressed for xx*10ms, 0 == key is not pressed, time expired */ ;uint8_t wait_for_key_ms(int max_time) wait_for_key_ms: push r14 push r15 push r16 push r17 push r28 ; save registers r28:29 push r29 movw r14, r24 ; r14:15 = max_time ; // if key is pressed, return 1 ; // if max_time == 0 , do not count, wait endless ldi r28, 101 ; kk = 100 wrelease: sbic _SFR_IO_ADDR(RST_PIN_REG), RST_PIN ; if((RST_PIN_REG & (1<<RST_PIN))) rjmp no_w200 #if INHIBIT_SLEEP_MODE RCALL wait5ms ; wait5ms(); #else ldi r24, 1 RCALL sleep_5ms ; wait_about5ms(); #endif subi r28, 1 ; kk--; brne wrelease ; while (kk >= 0) no_w200: movw r28,r14 ; count_time = max_time ldi r16, 0x55 ; key_pressed = 0x55; ldi r17, 0 ; key_cs = 0 ; wait max_time milliseconds or endless, if zero no_cnt: sbrc r29, 7 ; while (count_time >= 0) rjmp to_ret wloop: #if INHIBIT_SLEEP_MODE RCALL wait10ms ; wait10ms(); #else ldi r24, 0x02 ; 2 RCALL sleep_5ms ; wait_about10ms(); #endif add r16, r16 ; key_pressed += key_pressed; // multiply with 2 is shift to left sbis _SFR_IO_ADDR(RST_PIN_REG), RST_PIN ; if((RST_PIN_REG & (1<<RST_PIN))) { subi r16, 0xff ; key_pressed++; //append a 1 andi r16, 0x3f ; key_pressed &= 0x3f; cpi r16, 0x3f ; if (key_pressed == 0x3f) //63 all bits set brne not_pressed cpse r17, r1 ; if (key_cs == 0) rjmp no_first movw r28,r14 ; count_time = max_time; ldi r17, 4 ; key_cs = 4; no_first: subi r17, 0xff ; key_cs++; cpi r17, MAX_CS ; if (key_cs >= MAX_CS) brcs cnt_loop ; rjmp to_ret ; break; not_pressed: cpse r16, r1 ; if (( key_pressed == 0) && rjmp cnt_loop cpse r17, r1 ; ( key_cs != 0)) rjmp to_ret ; break; cnt_loop: wdr ; wdt_reset(); sbiw r28, 0x00 ; if (count_time > 0) // count only, if counter > 0 breq no_cnt ; special case zero, don't count sbiw r28, 0x0a ; count_time -= 10; // 10 ms are done, count down brne no_cnt ; if (count_time == 0) count_time = -1; // never count to zero, zero is endless! ldi r28, 0xFF ; count_time = -1 ldi r29, 0xFF ; rjmp no_cnt to_ret: mov r24, r17 ; return(key_cs) pop r29 ; restore registers r29:28 pop r28 pop r17 pop r16 pop r15 pop r14 ret .endfunc #ifdef WAIT_LINE2_CLEAR .GLOBAL wait_for_key_5s_line2 .extern wait_for_key_ms .extern lcd_line2 .extern lcd_clear_line .func wait_for_key_5s_line2 ; /* wait 5 seconds or previous key press, then clear line 2 of LCD and */ ; /* set the cursor to the beginning of line 2 */ ; void wait_for_key_5s_line2(void) wait_for_key_5s_line2: #if 0 ldi r24, '+' RCALL lcd_data ; lcd_data('+'); ldi r24, lo8(SHORT_WAIT_TIME) ; 0x88 ldi r25, hi8(SHORT_WAIT_TIME) ; 0x13 RCALL wait_for_key_ms ;wait_for_key_ms(SHORT_WAIT_TIME); #if (LCD_LINES < 4) RCALL lcd_line2 ; //2. row RCALL lcd_clear_line ; lcd_clear_line(); // clear the whole line RCALL lcd_line2 ; //2. row #else RCALL lcd_line4 ; //4. row RCALL lcd_clear_line ; lcd_clear_line(); // clear the whole line RCALL lcd_line4 ; //4. row #endif #else push r28 RCALL lcd_save_position mov r28, r24 ; current_line = lcd_save_position() lds r24, last_line_used and r24, r24 breq x83c ; if (last_line_used != 0) cpi r24, 1 brne x822 cpi r28, (LCD_LINES-1) brne x822 ; if ((last_line_used == 1) &&(current_line == (LCD_LINES-1))) ldi r22, (LCD_LINE_LENGTH -1) ldi r24, ((LCD_LINES - 1) * PAGES_PER_LINE) rcall lcd_set_cursor ; lcd_set_cursor(((LCD_LINES - 1) * PAGES_PER_LINE), (LCD_LINE_LENGTH - 1)) ldi r24, '+' ; // add a + sign at the last location of screen rcall lcd_data ; lcd_data('+') ldi r22, (LCD_LINE_LENGTH -1) ldi r24, ((LCD_LINES - 1) * PAGES_PER_LINE) rcall lcd_set_cursor ; lcd_set_cursor(((LCD_LINES - 1) * PAGES_PER_LINE), (LCD_LINE_LENGTH - 1)) x822: #ifdef WITH_ROTARY_SWITCH ldi r24, lo8(SHORT_WAIT_TIME) ; 0x88 ldi r25, hi8(SHORT_WAIT_TIME) ; 0x13 rcall wait_for_key_ms ;wait_for_key_ms(SHORT_WAIT_TIME); // wait until time is elapsed or key is pressed cpse r24, r1 rjmp x855 lds r24, rotary+incre cpse r24, r1 rjmp x822 #else ldi r24, lo8(SHORT_WAIT_TIME) ; 0x88 ldi r25, hi8(SHORT_WAIT_TIME) ; 0x13 rcall wait_for_key_ms ;wait_for_key_ms(SHORT_WAIT_TIME); // wait until time is elapsed or key is pressed #endif x855: cpi r28, (LCD_LINES - 1) ; (current_line == (LCD_LINES - 1)) brne x83a lds r24, last_line_used cpi r24, 1 brne x83a ; if ((current_line == (LCD_LINES - 1)) && (last_line_used == 1)) ldi r24, (LCD_LINES - 1) ldi r22, 0x00 ; 0 rcall lcd_set_cursor ; lcd_set_cursor((LCD_LINES-1) * PAGES_PER_LINE,0) rcall lcd_clear_line x83a: rcall lcd_restore_position x83c: pop r28 #endif ret .endfunc #endif
wagiminator/ATmega-Transistor-Tester
3,686
software/sources/lcd_hw_1_bit.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif ;--------------------------------------------------------------------- #include <avr/io.h> #include "config.h" .section .text ;---------------------------------------------------------------------- ; Global Definitions ;---------------------------------------------------------------------- #define preg_1 r24 #define preg_2 r22 ; Serial Clock Input (SCL) #define set_en_low cbi _SFR_IO_ADDR(HW_LCD_EN_PORT), HW_LCD_EN_PIN #define set_en_high sbi _SFR_IO_ADDR(HW_LCD_EN_PORT), HW_LCD_EN_PIN ; Register select (0 = Command, 1 = Data) #define set_rs_low cbi _SFR_IO_ADDR(HW_LCD_RS_PORT), HW_LCD_RS_PIN #define set_rs_high sbi _SFR_IO_ADDR(HW_LCD_RS_PORT), HW_LCD_RS_PIN ; Serial data input (SI) #define set_b0_low cbi _SFR_IO_ADDR(HW_LCD_B0_PORT), HW_LCD_B0_PIN #define set_b0_high sbi _SFR_IO_ADDR(HW_LCD_B0_PORT), HW_LCD_B0_PIN ;---------------------------------------------------------------------- ; ; "_lcd_hw_write" ; ; preg_1 (r24) = flags ; preg_2 (r22) = data ; ; Write one byte (Cmd or Data) to ST7565 controller. In assembler for ; Performance reasons. ;---------------------------------------------------------------------- .global _lcd_hw_write .func _lcd_hw_write .extern wait1us _lcd_hw_write: ; Set RS (0=Cmd, 1=Data) sbrc preg_1, 0 set_rs_high sbrs preg_1, 0 set_rs_low _bit_loop: ; Send bit-7 set_en_low sbrc preg_2, 7 set_b0_high sbrs preg_2, 7 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-6 set_en_low sbrc preg_2, 6 set_b0_high sbrs preg_2, 6 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-5 set_en_low sbrc preg_2, 5 set_b0_high sbrs preg_2, 5 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-4 set_en_low sbrc preg_2, 4 set_b0_high sbrs preg_2, 4 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-3 set_en_low sbrc preg_2, 3 set_b0_high sbrs preg_2, 3 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-2 set_en_low sbrc preg_2, 2 set_b0_high sbrs preg_2, 2 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-1 set_en_low sbrc preg_2, 1 set_b0_high sbrs preg_2, 1 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-0 set_en_low sbrc preg_2, 0 set_b0_high sbrs preg_2, 0 set_b0_low set_en_high ; force data read from LCD controller _lcd_hw_write_exit: ret .endfunc
wagiminator/ATmega-Transistor-Tester
14,329
software/sources/samplingADC_cnt.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include <avr/eeprom.h> #include <stdlib.h> #include "config.h" #include "part_defs.h" .GLOBAL samplingADC .func samplingADC #if AUTO_CLOCK_DIV == ((1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0)) #define TICS_PER_ADC_CLOCK 128 #else #define TICS_PER_ADC_CLOCK 64 #endif #define ADC_StartDelay 32 /* we cannot trigger the ADC before the Counter1 is started */ #define ADC_SHtime (TICS_PER_ADC_CLOCK*2) /* time to ADC S&H for triggered start */ ;=============================================================================================== ; This version uses counter1 for start of first ADC-cycle in a Signal sequence ;=============================================================================================== .section .text samplingADC: ;uint16_t samplingADC(R24:25 what, R22:23 array[], R20 nn, R18 Rport_1, R16 Rddr_1, R14 Rport_0, R12 Rddr_0) {} ; R24 = The length of the generated pulse in clock tics. ; Supported values are 0-15 for pulse-length 1-16 . ; Bit 0x10 is used for a direct pulse with length 1. ; For direct pulse the ADC port is used as output without 680 Ohm resistors. ; R25 = Pulse-distance (span) ; Possible values for pulse distance are 1,2,4,8,13,16,26,32,52,64,104,128 and 208 . ; All other values match not with the ADC convertion time without remainder, ; so that the sample time is not correct for the second and all following conversion periods. ; R22:23 The address of a array, which hold the data ldi r26, 0 ; no RAM space ldi r27, 0 ldi r30, lo8(gs(Retur1)) ;0x6B ; 107 ldi r31, hi8(gs(Retur1)) ;0x32 ; 50 jmp __prologue_saves__ Retur1: ; clr r1 mov R13, R18 ; R13 = Rport_1 movw R18,R24 ; R18 = pulse-length+options, R19 = distance of samples and R19, R19 brne no_zero ldi R19, 1 ; span must be 1 no_zero: andi R18, 0x1f ; 0 - 15 for pulse length and direct-pulse option movw R4, R22 ; R4:5 = &array[0]; ldi R21, 1 ; nn=256 cpse R20, r1 ldi R21, 0 ; nn <256 mov r22, R20 ; NN dec r22 mul R19, r22 ; (NN-1) * span movw r22, r0 ; r22:23 = last_sample = (NN-1) * span clr r1 ; restore zero register ; R19 = span, r27=clock_div ldi r26, lo8(TICS_PER_ADC_CLOCK*13) ldi r27, hi8(TICS_PER_ADC_CLOCK*13) movw r2, r26 ; save tics per ADC cycle in r2:3 AOUT R_PORT, R14 ; Rport_0 set to start condition AOUT R_DDR, R12 ; Rddr_0 ldi r26, (1<<ADTS2) | (0<<ADTS1) | (1<<ADTS0); sts ADCSRB, r26 ; // trigger source COUNTER1 compare match B ldi r27, (1<<ADEN) | (1<<ADSC) | (1<<ADATE) | (1<<ADIF) | (0<<ADIE) | AUTO_CLOCK_DIV; sts ADCSRA, r27 ; start first ADC with ext trigger, but start immediately wait_adc: lds r26, ADCSRA ; while (ADCSRA & (1 << ADSC)) sbrc r26, ADSC rjmp wait_adc ; /* wait until first initial conversion is done */ sts ADCSRA, r26 ; clear flags (1<<ADIF) mov r10, r1 ; start_pos = 0; mov r11, r1 movw r6, r10 ; r6:7 Samples = 0; // no ADC sample get yet ; // The pulse generation is time critical ; // we are just behind the previous cycle of the ADC ; // time to next S&H is below 1.5 ADC clocks. ; // If required, the next Signal period begins in about 13 ADC-clocks. ; // We switch back to the initial trigger source to stop the counter after completing this cycle. //============================================================================================== GeneratePulse: ; r2:3 = CPUtics of a full ADC period (13 ADC-clocks) ; r4:5 = Address of buffer ; r6:7 = Samples, the count of collected data ; r8:9 = sample_pos the tic position of actual sample ; r10:11 = start_pos, the tic position of the first sample in this signal period ; R12 = Rddr_0 ; R13 = Rport_1 ; R14 = Rport_0 ; r15 = scratch ; R16 = Rddr_1 ; r17 = scratch ; R19 = span each time shift step has span CPU-tics ; R20:21 = nn the number of requested data elements ; r22:23 = last_sample the position of last sample ; R24 = option, R18 = pulse_width, R19 = span sts TCCR1B, r1 ; TCCR1B = 0; // stop counter1 sts TCCR1A, r1 ; TCCR1A = 0; // set counter1 to normal mode sts TCNT1H, r1 ; TCNT1 = 0; // set initial counter to zero sts TCNT1L, r1 ; // set the ADC Start time, documentation mentions a 3 CPU clock delay, which is compensated here movw r26, r10 ; start_pos movw r8, r10 ; sample_pos = start_pos add r26, R18 ; + pulse_width adc r27, r1 adiw r26, (ADC_StartDelay - 3) sts OCR1BH, r27 ; OCR1B = (ADC_StartDelay - 3 + start_pos); sts OCR1BL, r26 ; set compare B to start condition for this Pulse generation subi r26, lo8(-(ADC_SHtime + 16 + 3)) ; + time to S&H sbci r27, hi8(-(ADC_SHtime + 16 + 3)) ; sts OCR1AH, r27 ; OCR1A = (ADC_StartDelay + ADC_SHtime + 16 + start_pos ); sts OCR1AL, r26 ; update compare A interrupt to behind S&H sts TIMSK1, r1 ; // disable counter1 compare A Interrupt ldi r26, (1<<ICF1) | (1<<OCF1B) | (1<<OCF1A) | (1<<TOV1); out _SFR_IO_ADDR(TIFR1), r26 ; clear interrupt flags cp r6, R20 ; if (Samples >= nn) cpc r7, R21 brcs get_next_data // all samples collected, finish finish: clr r1 sts TCCR1B, r1 ; TCCR1B = 0; // stop counter1 ldi r26, (1<<ADIF) | (1<<ADIE) ; // stop ADC sts ADCSRA, r26 ;## in r28, _SFR_IO_ADDR(SPL) ;## in r29, _SFR_IO_ADDR(SPH) ldi r30, 18 ; restore full register list jmp __epilogue_restores__ ;============== return ====================== get_next_data: ldi r26, (0<<ICNC1)|(1<<CS10) ; TCCR1B = (0<<ICNC1)|(1<<CS10); sts TCCR1B, r26 ; // start counter at full speed ;============ Counter 1 is started ================================================= ; // We must count the CPU cycles used by the program to generate the signal just before S&H! ; The counter starts ADC in ADC_StartDelay tics. ; The signal generation takes 13 tics + (dp_width-1). ; So we must only delay the two ADC clock cycles (ADC_SHtime) plus the ADC_StartDelay, ; but minus the count of tics for the signal generation. ; The time difference for the different signal types is compensated with counter delay. #define SignalStartDelay (ADC_SHtime+ADC_StartDelay-11+1) ; 256 + 32 -11 = 277 ldi r26, (SignalStartDelay / 3) lop1: dec r26 brne lop1 #if (SignalStartDelay % 3) > 1 nop #endif #if (SignalStartDelay % 3) > 0 nop #endif ldi r30, lo8(gs(Return2)) ;11 ldi r31, hi8(gs(Return2)) ;10 sub r30, R18 ;9 -pulse_width sbc r31, r1 ;8 mov r27, R14 ;7 Rport_0 or r27, R13 ;6 Rport_1 wdr ;5 wdt_reset(); ijmp ;4 computed goto Return+(16-dp_width) rjmp direct_pulse ; special pulse without resistors, two additional tics AOUT R_PORT, R13 ;17 R_PORT = Rport_1, dp_width = (16-1) AOUT R_PORT, R13 ;16 R_PORT = Rport_1, dp_width = (15-1) AOUT R_PORT, R13 ;15 R_PORT = Rport_1, dp_width = (14-1) AOUT R_PORT, R13 ;14 R_PORT = Rport_1, dp_width = (13-1) AOUT R_PORT, R13 ;13 R_PORT = Rport_1, dp_width = (12-1) AOUT R_PORT, R13 ;12 R_PORT = Rport_1, dp_width = (11-1) AOUT R_PORT, R13 ;11 R_PORT = Rport_1, dp_width = (10-1) AOUT R_PORT, R13 ;10 R_PORT = Rport_1, dp_width = (9-1) AOUT R_PORT, R13 ; 9 R_PORT = Rport_1, dp_width = (8-1) AOUT R_PORT, R13 ; 8 R_PORT = Rport_1, dp_width = (7-1) AOUT R_PORT, R13 ; 7 R_PORT = Rport_1, dp_width = (6-1) AOUT R_PORT, R13 ; 6 R_PORT = Rport_1, dp_width = (5-1) AOUT R_PORT, R13 ; 5 R_PORT = Rport_1, dp_width = (4-1) AOUT R_PORT, R13 ; 4 R_PORT = Rport_1, dp_width = (3-1) AOUT R_PORT, R13 ; 3 R_PORT = Rport_1, dp_width = (2-1) Return2: AOUT R_PORT, r27 ; 2 R_PORT = Rport_1|Rport_0; // beginning of step, or end of (last) impulse AOUT R_DDR, R16 ; 1 R_DDR = Rddr_1; // start of first measurement is aligned with this ;============ End of time critical part ================================================= AOUT R_PORT, R14 ; R_PORT = Rport_0; only switch of unused Rport_0 rjmp wait_cnt ;; cap: ; byte d=( (hivolt) ? HiPinR_L : HiPinR_H ); ; samplingADC(samp_opt, uu, N2+1, d, HiPinR_H, d, HiPinR_L); ; ; Rport_1 = Rport_0 = HiPinR_H or HiPinR_L ; Rddr_1 = HiPinR_H ; Rddr_0 = HiPinR_L ; ;uint16_t samplingADC(R24:25 what, R22:23 array[], R20 nn, R18 Rport_1, R16 Rddr_1, R14 Rport_0, R12 Rddr_0) {} ; ; samplingADC(par, uu, 0, HiPinR_L, 0, 0, HiPinR_L); ;; LC: ; Rport_1 = HiPinR_L ; Rport_0 = 0 ; Rddr_1 = 0 ; Rddr_0 = HiPinR_L ; ;; UJT: ; port0 = pinmaskRL(B2pin); ; port1 = pinmaskRL(B2pin) | pinmaskRH(Epin) ; ddr1 = pinmaskRL(B2pin) | pinmaskRH(Epin) ; ddr0 = pinmaskRL(B2pin) | pinmaskRL(Epin); direct_pulse: nop ;16 + 2 tics for rjmp #if MHZ_CPU != 16 ; nop ;15 #endif in r30, _SFR_IO_ADDR(ADC_DDR) ;14 in r31, _SFR_IO_ADDR(ADC_PORT) ;13 ldi r26, (1<<TP3) ;12 sbrc R12, PIN_RL2 ;11 is the bit for TP2 resistor set? ldi r26, (1<<TP2) ;10 sbrc R12, PIN_RL1 ;9 ist the bit for TP3 resistor set? ldi r26, (1<<TP1) ;8 ; r26 now hold the bit for the direct ADC port mov r27, r31 ;7 ADC_PORT state or r27, r26 ;6 r27 is the for ADC port with HiPin set to 1 or r26, r30 ;5 r26 enables the HiPin and LoPin output, ADC_DDR AOUT ADC_PORT, r27 ;4 set Hipin to high AOUT R_DDR, R16 ;3 R_DDR = Rddr1 open all resistor ports AOUT ADC_DDR, r26 ;2 one clock tic high without resistor at HiPin, current about 5V/(42 Ohm)=119mA !!! #if MHZ_CPU == 16 ; AOUT ADC_DDR, r26 ;2 one clock tic high without resistor at HiPin, current about 5V/(42 Ohm)=119mA !!! #endif AOUT ADC_DDR, r30 ;1 disable the HiPin output ;============ End of time critical part ================================================= AOUT ADC_PORT, r31 ; reset Hipin to low rjmp wait_cnt wait_cnt: sbis _SFR_IO_ADDR(TIFR1), OCF1A ; while (TIFR1 & (1 << OCF1A) == 0) rjmp wait_cnt ; /* wait until counter1 compare match is done */ ;---------------XXXXXXXX------------------------- ; // The first triggered ADC conversion takes 13.5 ADC clock cycles from Counter Reg B compare sts TCCR1B, r1 ; TCCR1B = 0; // stop counter, no longer required_ ldi r26, (1<<ICF1) | (1<<OCF1B) | (1<<OCF1A) | (1<<TOV1); out _SFR_IO_ADDR(TIFR1), r26 ; clear interrupt flags //============================================================================================== CheckNextSample: ; // The pulse generation is time critical. ; // We are just behind the previous cycle of the ADC for repeated conversion. ; // The time to next S&H is below 1.5 ADC clocks in this case. ; // If required, the next Signal period begins in about 13 ADC-clocks. ; // Let us look, if the next ADC S&H is within the sampling period movw r26, r8 ; sample_pos add r26, r2 ; sample_pos + adc_period adc r27, r3 cp r22, r26 ;R22:23 = position of last sample, r26:27 = sample_pos + adc_period+1 cpc r23, r27 brcc more_data ; if (((start1 + m_shift) + samples_per_adc_period + 1) > nn) ; -------------------------------------------------------------- ; // The running ADC-cycle is the last one in this Signal period ; // We switch back to the initial trigger source to stop the counter after completing this cycle. ldi r26, (1<<ADTS2) | (0<<ADTS1) | (1<<ADTS0); sts ADCSRB, r26 ; trigger source = COUNTER1 compare match B, STOP after ADC-cycle ends ; // We must differ between the first and repeated ADC cycle condition. ; // If it is the first cycle, we are already behind the S&H time (Counter1 Compare match A). ; // The other situation is the repeated ADC. In this case we are just behind ; // the end of ADC cycle, so we must wait for the next S&H time. ; // The next S&H is at 1.5*ADCclock. cp r10, r8 ; start_delay <= sample_pos cpc r11, r9 brcc behind_SH ; if (m_shift > 0) // This is not the first ADC-cycle in this Signal-generation cycle. // Let us wait for next SH time. ldi r26, ((TICS_PER_ADC_CLOCK*3)/6) ; 1.5 * ADC_CLOCK lop3: dec r26 brne lop3 behind_SH: ; ------------------------------------- ; toggle output back to the idle state AOUT R_PORT, R14 ; 5 Rport_0 AOUT R_DDR, R12 ; 4 Rddr_0 rcall store_data ; store new ADC data to array and count Samples ; // This was the last ADC data of this Signal period, update the time shift registers add r10, R19 ; start_pos += span: adc r11, r1 ; call wait200us ; ############# for Test only ################################################# rjmp GeneratePulse ; last data of this signal period is fetched ; -------------------------------------------------------------- ; // there are more data to collect in this Signal period ; // Now we try to switch the ADC to free running mode more_data: sts ADCSRB, r1 ;ADCSRB = 0; // source ADC finish == 13 ADC clock cyclus free run rcall store_data ; store new ADC data in array and count Samples add r8, r2 ; sample_pos += adc_period; adc r9, r3 ; rjmp CheckNextSample ; check, if the next data is the last one in this signal period ; Store ADC data in caller's array ; Wait for ADC data ready with polling ; The position of array cell is array[start1 + m_shift] ; r8:9 = position of sample, R4:5 = beginn of array ; Function use register r17:15 to get new ADC data and ; register r26:27 to read (and accumulate) the old data at the array place. ; every call increments the Samples counter r6:7 . store_data: movw r26, r8 ; sample_pos movw r30, R4 ; &array sub_loop: sub r26, R19 ; - span sbc r27, r1 brcs is_found adiw r30, 2 ; increment array address rjmp sub_loop is_found: ld r26, Z ; lo8(array[start1 + m_shift]) ldd r27, Z+1 ; hi8(array[start1 + m_shift]) ; r30:31 = Z = number of a 16-Bit element. wait_adc3: lds r17, ADCSRA ; while (ADCSRA & (1 << ADIF) == 0) sbrs r17, ADIF rjmp wait_adc3 ; /* wait until conversion is done */ sts ADCSRA, r17 ; clear the interrupt ADIF ; // next ADC data are ready lds r17, ADCL ; neẃ ADC value lds r15, ADCH ;## lds r17, TCNT1L ; TCNT ;## lds r15, TCNT1H sbrc r24, smplADC_cumul ; skip next instruction, if no acummulate add r17, r26 ; + lo8(array[start1 + m_shift]) st Z+, r17 ; store lower part sbrc r24, smplADC_cumul ; skip next instruction, if no acummulate adc r15, r27 ; + hi8(array[start1 + m_shift]) st Z, r15 ; store upper part ldi r17, 1 add r6, r17 ; Samples++ adc r7, r1 ; add carry to r7 ret ; return store_data .endfunc
wagiminator/ATmega-Transistor-Tester
7,905
software/sources/PinLayout.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include "config.h" #include "part_defs.h" ;// show the Pin Layout of the device ; void PinLayout(char pin1, char pin2, char pin3) ;// pin1-3 is EBC or SGD or CGA ; typedef struct { ; unsigned long hfe; //0 current amplification factor ; unsigned int uBE; //4 B-E-voltage of the Transistor ; unsigned int current; //6 current of Drain in 0.01mA ; // for bipolar current is ICE0 ; unsigned int gthvoltage; //8 Gate-threshold voltage ; // for bipolar gthvoltage is ICEs in 0.01mA ; uint8_t b,c,e; //10,11,12 pins of the Transistor ; uint8_t count; //13 ; }trans_t; #define RCALL rcall .GLOBAL PinLayout .func PinLayout .extern lcd_data .extern lcd_space .extern lcd_testpin .extern _trans #define OFFS_b 12 /* offset to trans.b */ #define OFFS_c 13 /* offset to trans.c */ #define OFFS_e 14 /* offset to trans.e */ .extern N123_str .extern N321_str PinLayout: #ifndef EBC_STYLE ; // Layout with 123= style push r14 push r15 push r16 push r17 mov r17, r24 ; Pin1 mov r16, r22 ; Pin2 mov r15, r20 ; Pin3 ldi r24, lo8(N123_str) ; 0x0B ldi r25, hi8(N123_str) ; 0x01 #ifdef USE_EEPROM RCALL lcd_fix_string ; lcd_MEM_string(N123_str); //" 123=" #else RCALL lcd_pgm_string ; lcd_MEM_string(N123_str); //" 123=" #endif eor r14, r14 ; for (ipp=0; loop1: lds r30, _trans lds r31, _trans+1 ldd r24, Z+OFFS_e ; _trans->e cp r14, r24 brne checkb ; if (ipp == _trans->e) mov r24, r17 ; pin1 rjmp data_ipp ; lcd_data(pin1); // Output Character in right order checkb: ldd r24, Z+OFFS_b ; _trans->b cp r14, r24 ; if (ipp == _trans->b) brne checkc mov r24, r16 rjmp data_ipp ; lcd_data(pin2); checkc: ldd r24, Z+OFFS_c ; _trans->c cp r14, r24 brne next_ipp ; if (ipp == _trans->c) mov r24, r15 data_ipp: RCALL lcd_data ; lcd_data(pin3); next_ipp: inc r14 mov r24, r14 cpi r24, 0x03 ; for ( ;ipp<3;ipp++) { brne loop1 pop r17 pop r16 pop r15 pop r14 ret #else #if EBC_STYLE == 321 ; // Layout with 321= style push r14 push r15 push r16 push r17 mov r17, r24 ; Pin1 mov r16, r22 ; Pin2 mov r15, r20 ; Pin3 ldi r24, lo8(N321_str) ; 0x0B ldi r25, hi8(N321_str) ; 0x01 #ifdef USE_EEPROM RCALL lcd_fix_string ; lcd_MEM_string(N321_str); //" 321=" #else RCALL lcd_pgm_string ; lcd_MEM_string(N321_str); //" 321=" #endif ldi r24, 0x03 ; 3 mov r14, r24 ; ipp = 3; loop2: dec r14 ; ipp--; lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_e ; _trans->e cp r14, r24 brne checkb ; if (ipp == _trans->e) mov r24, r17 ; lcd_data(pin1); // Output Character in right order rjmp data_ipp2 checkb: lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_b ; _trans->b cp r14, r24 brne checkc ; if (ipp == _trans->b) mov r24, r16 ; lcd_data(pin2); rjmp data_ipp2 checkc: ldd r24, Z+OFFS_c ; _trans->c cp r14, r24 brne next_ipp2 ; if (ipp == _trans->c) mov r24, r15 ; lcd_data(pin3); data_ipp2: RCALL lcd_data ; lcd_data(pinx); next_ipp2: and r14, r14 ; while (ipp != 0) brne loop2 pop r17 pop r16 pop r15 pop r14 ret #else ; // Layout with EBC= style push r15 push r16 push r17 mov r17, r24 ; Pin1 mov r16, r22 ; Pin2 mov r15, r20 ; Pin3 RCALL lcd_space ; lcd_space(); mov r24, r17 ; Pin1 RCALL lcd_data ; lcd_data(pin1); mov r24, r16 ; Pin2 RCALL lcd_data ; lcd_data(pin2); mov r24, r15 ; Pin3 RCALL lcd_data ; lcd_data(pin3); RCALL lcd_equal ; lcd_data('='); lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_e ; _trans->e RCALL lcd_testpin ; lcd_testpin(_trans->e); lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_b ; _trans->b RCALL lcd_testpin ; lcd_testpin(_trans->b); lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_c ; _trans->c RCALL lcd_testpin ; lcd_testpin(_trans->c); pop r17 pop r16 pop r15 ret #endif #endif .endfunc #ifdef WITH_GRAPHICS .GLOBAL PinLayoutLine .func PinLayoutLine PinLayoutLine: push r14 push r15 push r16 push r17 mov r17, r24 ; Pin1 mov r16, r22 ; Pin2 mov r15, r20 ; Pin3 ldi r24, 0 call lcd_next_line_wait ; lcd_next_line_wait(0); #ifdef NO_LONG_PINLAYOUT RCALL lcd_space ; lcd_space() ldi r24, lo8(Pin_str) ; ldi r25, hi8(Pin_str) ; #ifdef USE_EEPROM RCALL lcd_fix_string ; lcd_MEM_string(Pin_str); //"Pin " #else RCALL lcd_pgm_string ; lcd_MEM_string(Pin_str); //"Pin " #endif mov r20, r15 mov r22, r16 mov r24, r17 RCALL PinLayout ; PinLayout(Pin1, Pin2, Pin3) #else ldi r24, lo8(Pin_str) ; ldi r25, hi8(Pin_str) ; #ifdef USE_EEPROM RCALL lcd_fix_string ; lcd_MEM_string(Pin_str); //"Pin " #else RCALL lcd_pgm_string ; lcd_MEM_string(Pin_str); //"Pin " #endif #ifndef EBC_STYLE ; // Layout with 1= 2= 3= style eor r14, r14 ; for (ipp=0; lloop1: mov r24, r14 RCALL lcd_testpin ; lcd_testpin(ipp) RCALL lcd_equal ; lcd_data('=') lds r30, _trans lds r31, _trans+1 ldd r24, Z+OFFS_e ; _trans->e cp r14, r24 brne lcheckb ; if (ipp == _trans->e) mov r24, r17 ; pin1 rjmp ldata_ipp ; lcd_data(pin1); // Output Character in right order lcheckb: ldd r24, Z+OFFS_b ; _trans->b cp r14, r24 ; if (ipp == _trans->b) brne lcheckc mov r24, r16 rjmp ldata_ipp ; lcd_data(pin2); lcheckc: ldd r24, Z+OFFS_c ; _trans->c cp r14, r24 brne lnext_ipp ; if (ipp == _trans->c) mov r24, r15 ldata_ipp: RCALL lcd_data ; lcd_data(pin3); lnext_ipp: RCALL lcd_space ; lcd_space() inc r14 mov r24, r14 cpi r24, 0x03 ; for ( ;ipp<3;ipp++) { brne lloop1 #else #if EBC_STYLE == 321 ; // Layout with 3= 2= 1= style ldi r24, 0x03 ; 3 mov r14, r24 ; ipp = 3; lloop2: dec r14 ; ipp--; mov r24, r14 RCALL lcd_testpin ; lcd_testpin(ipp) RCALL lcd_equal ; lcd_data('=') lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_e ; _trans->e cp r14, r24 brne lcheckb ; if (ipp == _trans->e) mov r24, r17 ; lcd_data(pin1); // Output Character in right order rjmp ldata_ipp2 lcheckb: lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_b ; _trans->b cp r14, r24 brne lcheckc ; if (ipp == _trans->b) mov r24, r16 ; lcd_data(pin2); rjmp ldata_ipp2 lcheckc: ldd r24, Z+OFFS_c ; _trans->c cp r14, r24 brne lnext_ipp2 ; if (ipp == _trans->c) mov r24, r15 ; lcd_data(pin3); ldata_ipp2: RCALL lcd_data ; lcd_data(pinx); lnext_ipp2: RCALL lcd_space ; lcd_space() and r14, r14 ; while (ipp != 0) brne lloop2 #else ; // Layout with E= B= C= style mov r24, r17 ; Pin1 RCALL lcd_data ; lcd_data(pin1); RCALL lcd_equal ; lcd_data('=') lds r30, _trans ; lds r31, _trans+1 ; ldd r24, Z+OFFS_e ; _trans->e RCALL lcd_testpin ; lcd_testpin(_trans->e); RCALL lcd_space ; lcd_space() mov r24, r16 ; Pin2 RCALL lcd_data ; lcd_data(pin2); RCALL lcd_equal ; lcd_data('=') lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_b ; _trans->b RCALL lcd_testpin ; lcd_testpin(_trans->b); RCALL lcd_space ; lcd_space() mov r24, r15 ; Pin3 RCALL lcd_data ; lcd_data(pin3); RCALL lcd_equal ; lcd_data('='); lds r30, _trans ;0x0142 lds r31, _trans+1 ;0x0143 ldd r24, Z+OFFS_c ; _trans->c RCALL lcd_testpin ; lcd_testpin(_trans->c); #endif /* =321 */ #endif /* EBC_STYLE */ #endif /* NO_LONG_PINLAYOUT */ pop r17 ; restore registers and return pop r16 pop r15 pop r14 ret .endfunc #endif /* WITH_GRAPHICS */ .GLOBAL Rnum2pins .func Rnum2pins Rnum2pins: mov r22,r24 ldi r24, TP1 ldi r25, TP3 and r22,r22 brne nozero ldi r25, TP2 nozero: cpi r22, 2 brne no_two ldi r24, TP2 no_two: ret .endfunc
wagiminator/ATmega-Transistor-Tester
3,938
software/sources/GetRLmultip.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/eeprom.h> #include <stdlib.h> #include "config.h" #define zero_reg r1 /* unsigned int GetRLmultip(unsigned int cvolt) { */ // interpolate table RLtab corresponding to voltage cvolt /* unsigned int uvolt; */ /* unsigned int y1, y2; */ /* uint8_t tabind; */ /* uint8_t tabres; */ /* if (cvolt >= RL_Tab_Beginn) { */ /* uvolt = cvolt - RL_Tab_Beginn; */ /* } else { */ /* uvolt = 0; // limit to begin of table */ /* } */ /* tabind = uvolt / RL_Tab_Abstand; */ /* tabres = uvolt % RL_Tab_Abstand; */ /* tabres = RL_Tab_Abstand - tabres; */ /* if (tabind > ((RL_Tab_Length/RL_Tab_Abstand)-1)) { */ /* tabind = (RL_Tab_Length/RL_Tab_Abstand)-1; // limit to end of table */ /* tabres = 0; */ /* } */ /* y1 = MEM_read_word(&RLtab[tabind]); */ /* y2 = MEM_read_word(&RLtab[tabind+1]); */ /* return ( ((y1 - y2) * tabres + (RL_Tab_Abstand/2)) / RL_Tab_Abstand + y2); // interpolate table */ /*} */ .GLOBAL GetRLmultip .func GetRLmultip #define RL_Tab_Abstand 25 // displacement of table 25mV #define RL_Tab_Beginn 300 // begin of table ist 300mV #define RL_Tab_Length 1100 // length of table is 1400-300 .section .text ; unsigned int GetRLmultip(unsigned int cvolt) GetRLmultip: push r0 ldi r18, hi8(RL_Tab_Beginn) ; 1 cpi r24, lo8(RL_Tab_Beginn) ; 44 cpc r25, r18 brcc is_bigger ;if (cvolt >= RL_Tab_Beginn) ldi r24, lo8(RL_Tab_Beginn) ; uvolt = 0 = RL_Tab_Begin - RL_Tab_Begin ldi r25, hi8(RL_Tab_Beginn) ; limit to begin of table is_bigger: subi r24, lo8(RL_Tab_Beginn) ; uvolt = cvolt - RL_Tab_Beginn; sbci r25, hi8(RL_Tab_Beginn) ; 1 ldi r22, lo8(RL_Tab_Abstand) ; 25 ldi r23, hi8(RL_Tab_Abstand) ; 0 ACALL __udivmodhi4 ;tabind = uvolt / RL_Tab_Abstand; ; r24:25 tabres = uvolt % RL_Tab_Abstand; // r25 allways zero ; tabres = RL_Tab_Abstand - tabres; ldi r25, RL_Tab_Abstand ; 25 cpi r22, ((RL_Tab_Length/RL_Tab_Abstand)-1) ; if (tabind > ((RL_Tab_Length/RL_Tab_Abstand)-1)) brcs is_lower mov r25, r24 ; tabres = 0 = (RL_Tab_Abstand==tabres) - tabres ldi r22, (RL_Tab_Length/RL_Tab_Abstand)-1; tabind = (RL_Tab_Length/RL_Tab_Abstand)-1;// limit to end of table is_lower: sub r25, r24 ; tabres = RL_Tab_Abstand - tabres; ; r22 = tabind , r25 = tabres LDIZ RLtab add r30, r22 ; + tabind adc r31, zero_reg add r30, r22 ; + tabind (word access) adc r31, zero_reg #ifdef MEM_EEPROM push r25 ; save tabres movw r24,r30 ACALL eeprom_read_byte ; y1 = MEM_read_word(&RLtab[tabind]); mov r20, r24 adiw r30, 1 ; address of high order byte movw r24,r30 ACALL eeprom_read_byte ; y1 = MEM_read_word(&RLtab[tabind]); mov r21, r24 adiw r30, 1 ; tabind+1 movw r24,r30 ACALL eeprom_read_byte ; y2 = MEM_read_word(&RLtab[tabind+1]); mov r18, r24 adiw r30, 1 ; address of high order byte movw r24,r30 ACALL eeprom_read_byte ; y2 = MEM_read_word(&RLtab[tabind+1]); mov r19, r24 pop r22 ; restore tabres in r22 #else lpm r20, Z+ ; y1 = MEM_read_word(&RLtab[tabind]); lpm r21, Z+ lpm r18, Z+ ; y2 = MEM_read_word(&RLtab[tabind+1]); lpm r19, Z+ mov r22, r25 #endif ; return ( ((y1 - y2) * tabres + (RL_Tab_Abstand/2)) / RL_Tab_Abstand + y2); // interpolate table ;; ldi r23, 0x00 ; hi8(tabres) allways zero sub r20, r18 ; y1 - y2 sbc r21, r19 ; maximum of 3466 need two registers mul r22, r20 ;lo8(tabres) * lo8(y1-y2) movw r24, r0 ; r24:25 = * mul r22, r21 ;lo8(tabres) * hi8(y1-y2) add r25, r0 ; r25 + lo8(*) ;; mul r23, r20 ;hi8(tabres) * lo8(y1-y2) , allways zero ;; add r25, r0 ; r25 + lo8(*) eor r1, r1 adiw r24, (RL_Tab_Abstand/2) ; 12 ldi r22, lo8(RL_Tab_Abstand) ; 25 ldi r23, hi8(RL_Tab_Abstand) ; 0 ACALL __udivmodhi4 ; ((y1 - y2) * tabres + (RL_Tab_Abstand/2)) / RL_Tab_Abstand add r22, r18 ; + y2 adc r23, r19 movw r24, r22 pop r0 ret .endfunc
wagiminator/ATmega-Transistor-Tester
5,853
software/sources/UfAusgabe.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include <avr/eeprom.h> #include "config.h" #include "part_defs.h" .section .text #define zero_reg r1 #define RCALL rcall /* #include <avr/io.h> */ /* #include "Transistortester.h" */ /* void mVAusgabe(uint8_t nn) { */ /* if (nn < 3) { */ /* // Output in mV units */ /* DisplayValue(diodes.Voltage[nn],-3,'V',3); */ /* lcd_space(); */ /* } */ /* } */ .GLOBAL mVAusgabe .extern DisplayValue .extern lcd_space .func mVAusgabe mVAusgabe: ; if (nn < 6) { cpi r24, 0x06 ; 6 brcc ad1ca4; // Output in mV units LDIZ diodes+12; add r30,r24 adc r31,zero_reg add r30,r24 adc r31,zero_reg ld r24, Z ; diodes.Voltage[nn] ldd r25, Z+1 ; 0x01 ldi r22, 0x03 ; 3 RCALL Display_mV ; Display_mV(diodes.Voltage[nn],3); RCALL lcd_space; ; lcd_space(); ad1ca4: ret .endfunc /* // ****************************************************************** */ /* // output of flux voltage for 1-2 diodes in row 2 */ /* // bcdnum = Numbers of both Diodes: */ /* // higher 4 Bit number of first Diode */ /* // lower 4 Bit number of second Diode (Structure diodes[nn]) */ /* // if number >= 3 no output is done */ /* void UfAusgabe(uint8_t bcdnum) { */ /* if (ResistorsFound > 0) { //also Resistor(s) found */ /* lcd_space(); */ /* lcd_data(LCD_CHAR_RESIS3); // special symbol or R */ /* } */ /* lcd_line2(); //2. row */ /* lcd_PGM_string(Uf_str); //"Uf=" */ /* mVAusgabe(bcdnum >> 4); */ /* mVAusgabe(bcdnum & 0x0f); */ /* } */ .GLOBAL UfAusgabe .extern lcd_space .extern lcd_data .extern lcd_line2 .extern mVAusgabe .func UfAusgabe UfAusgabe: push r17 mov r17, r24 lds r24, ResistorsFound; 0x0168 and r24, r24 breq ad1cbe; if (ResistorsFound > 0) { RCALL lcd_space; lcd_space(); ldi r24, LCD_CHAR_RESIS3; 0 RCALL lcd_data; lcd_data(LCD_CHAR_RESIS3); // special symbol or R ad1cbe: RCALL lcd_line2; //2. row ldi r24, lo8(Uf_str); 0xE9 ldi r25, hi8(Uf_str); 0x01 #ifdef USE_EEPROM RCALL lcd_fix_string ; lcd_PGM_string(Uf_str); //"Uf=" #else RCALL lcd_pgm_string ; lcd_PGM_string(Uf_str); //"Uf=" #endif mov r24, r17 swap r24 andi r24, 0x0F rcall mVAusgabe ; mVAusgabe(bcdnum >> 4); mov r24, r17 andi r24, 0x0F ; 15 rcall mVAusgabe ; mVAusgabe(bcdnum & 0x0f); pop r17 ret .endfunc /* void SerienDiodenAusgabe() { */ /* uint8_t first; */ /* uint8_t second; */ /* first = diode_sequence >> 4; */ /* second = diode_sequence & 3; */ /* lcd_testpin(diodes.Anode[first]); */ /* lcd_PGM_string(AnKat_str); //"->|-" */ /* lcd_testpin(diodes.Cathode[first]); */ /* lcd_PGM_string(AnKat_str); //"->|-" */ /* lcd_testpin(diodes.Cathode[second]); */ /* UfAusgabe(diode_sequence); */ /* } */ .GLOBAL SerienDiodenAusgabe .extern lcd_testpin .extern UfAusgabe .extern AnKat_str .func SerienDiodenAusgabe SerienDiodenAusgabe: lds r24, diode_sequence; 0x0102 swap r24 andi r24, 0x0F ; first = diode_sequence >> 4; rcall DiodeSymbol_ApinCpin ; 1->|-2 lds r24, diode_sequence; 0x0102 andi r24, 0x03 ; second = diode_sequence & 3; RCALL DiodeSymbol_ACpin ; ->|-3 lds r24, diode_sequence; x0102 rcall UfAusgabe ; UfAusgabe(diode_sequence); ret .endfunc .func load_diodes_adr load_diodes_adr: ldi r30, lo8(diodes) ;0x80 ldi r31, hi8(diodes) ;0x01 add r30, r24 ; [nn] adc r31, zero_reg ret .endfunc .GLOBAL DiodeSymbol_withPins .func DiodeSymbol_withPins DiodeSymbol_withPins: #if FLASHEND > 0x1fff // enough memory (>8k) to sort the pins push r28 rcall load_diodes_adr #if EBC_STYLE == 321 // the higher test pin number is left side ld r28, Z ; diodes.Anode[nn] ldd r25, Z+6 ; diodes.Cathode[nn] cp r28, r25 brcc cat_first1 ; if (anode_nr > cathode_nr) { rcall DiodeSymbol_ApinCpin rjmp diode_fin // } else { cat_first1: rcall DiodeSymbol_CpinApin #else // the higher test pin number is right side ld r25, Z ldd r28, Z+6 ; if (anode_nr < cathode_nr) { cp r28, r25 brcc cat_first2 rcall DiodeSymbol_ApinCpin rjmp diode_fin // } else { cat_first2: rcall DiodeSymbol_CpinApin #endif #else rcall DiodeSymbol_ApinCpin #endif diode_fin: rcall lcd_space pop r28 ret .endfunc .GLOBAL DiodeSymbol_ApinCpin .func DiodeSymbol_ApinCpin DiodeSymbol_ApinCpin: rcall load_diodes_adr push r24 ld r24, Z ;Anode RCALL lcd_testpin ; lcd_testpin(diodes.Anode[nn]); pop r24 rcall DiodeSymbol_ACpin ; ->|-3 ret .endfunc .GLOBAL DiodeSymbol_ACpin .func DiodeSymbol_ACpin DiodeSymbol_ACpin: push r24 ldi r24, lo8(AnKat_str) ;0xA3 ldi r25, hi8(AnKat_str) ;0x03 #ifdef USE_EEPROM .extern lcd_fix_string RCALL lcd_fix_string ; lcd_PGM_string(AnKat_str); //"->|-" #else .extern lcd_pgm_string RCALL lcd_pgm_string ; lcd_PGM_string(AnKat_str); //"->|-" #endif pop r24 rcall load_diodes_adr ldd r24, Z+6 ; Cathode RCALL lcd_testpin ; lcd_testpin(diodes.Cathode[nn]); ret .endfunc .GLOBAL DiodeSymbol_CpinApin .func DiodeSymbol_CpinApin DiodeSymbol_CpinApin: rcall load_diodes_adr push r24 ldd r24, Z+6 ;Cathode RCALL lcd_testpin ; lcd_testpin(diodes.Cathode[nn]); pop r24 rcall DiodeSymbol_CApin ; -|<-3 ret .endfunc .GLOBAL DiodeSymbol_CApin .func DiodeSymbol_CApin DiodeSymbol_CApin: push r24 ldi r24, lo8(KatAn_str) ;0xA3 ldi r25, hi8(KatAn_str) ;0x03 #ifdef USE_EEPROM .extern lcd_fix_string RCALL lcd_fix_string ; lcd_PGM_string(KatAn_str); //"->|-" #else .extern lcd_pgm_string RCALL lcd_pgm_string ; lcd_PGM_string(KatAn_str); //"->|-" #endif pop r24 rcall load_diodes_adr ld r24, Z ; Anode RCALL lcd_testpin ; lcd_testpin(diodes.Anode[nn]); ret .endfunc
wagiminator/ATmega-Transistor-Tester
24,755
software/sources/lcd_hw_4_bit.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif ;--------------------------------------------------------------------- #include <avr/io.h> #include "config.h" ;#define FAST_SERIAL_OUT /* use no sub-function for bit setting */ #define FAST_SPI_OUTPUT .section .text ;---------------------------------------------------------------------- ; Global Definitions ;---------------------------------------------------------------------- #define preg_1 r24 #define preg_2 r22 ; for ST7565 controller: Serial Clock Input (SCL) #define set_en_low cbi _SFR_IO_ADDR(HW_LCD_EN_PORT), HW_LCD_EN_PIN #define set_en_high sbi _SFR_IO_ADDR(HW_LCD_EN_PORT), HW_LCD_EN_PIN #define set_en_output sbi (_SFR_IO_ADDR(HW_LCD_EN_PORT) - 1), HW_LCD_EN_PIN #define set_en_input cbi (_SFR_IO_ADDR(HW_LCD_EN_PORT) - 1), HW_LCD_EN_PIN ; Register select (0 = Command, 1 = Data) #define set_rs_low cbi _SFR_IO_ADDR(HW_LCD_RS_PORT), HW_LCD_RS_PIN #define set_rs_high sbi _SFR_IO_ADDR(HW_LCD_RS_PORT), HW_LCD_RS_PIN #define set_rs_output sbi (_SFR_IO_ADDR(HW_LCD_RS_PORT) - 1), HW_LCD_RS_PIN #define set_rs_input cbi (_SFR_IO_ADDR(HW_LCD_RS_PORT) - 1), HW_LCD_RS_PIN ; for ST7565 controller: Serial data input (SI) #define set_b0_low cbi _SFR_IO_ADDR(HW_LCD_B0_PORT), HW_LCD_B0_PIN #define set_b0_high sbi _SFR_IO_ADDR(HW_LCD_B0_PORT), HW_LCD_B0_PIN #define set_b0_output sbi (_SFR_IO_ADDR(HW_LCD_B0_PORT) - 1), HW_LCD_B0_PIN #define set_b0_input cbi (_SFR_IO_ADDR(HW_LCD_B0_PORT) - 1), HW_LCD_B0_PIN ; for ST7565 controller: Chip Enable #define set_ce_low cbi _SFR_IO_ADDR(HW_LCD_CE_PORT), HW_LCD_CE_PIN #define set_ce_high sbi _SFR_IO_ADDR(HW_LCD_CE_PORT), HW_LCD_CE_PIN #define set_ce_output sbi (_SFR_IO_ADDR(HW_LCD_CE_PORT) - 1), HW_LCD_CE_PIN #define set_ce_input cbi (_SFR_IO_ADDR(HW_LCD_CE_PORT) - 1), HW_LCD_CE_PIN #define set_b4_low cbi _SFR_IO_ADDR(HW_LCD_B4_PORT), HW_LCD_B4_PIN #define set_b4_high sbi _SFR_IO_ADDR(HW_LCD_B4_PORT), HW_LCD_B4_PIN #define set_b4_output sbi (_SFR_IO_ADDR(HW_LCD_B4_PORT) - 1), HW_LCD_B4_PIN #define set_b5_low cbi _SFR_IO_ADDR(HW_LCD_B5_PORT), HW_LCD_B5_PIN #define set_b5_high sbi _SFR_IO_ADDR(HW_LCD_B5_PORT), HW_LCD_B5_PIN #define set_b5_output sbi (_SFR_IO_ADDR(HW_LCD_B5_PORT) - 1), HW_LCD_B5_PIN #define set_b6_low cbi _SFR_IO_ADDR(HW_LCD_B6_PORT), HW_LCD_B6_PIN #define set_b6_high sbi _SFR_IO_ADDR(HW_LCD_B6_PORT), HW_LCD_B6_PIN #define set_b6_output sbi (_SFR_IO_ADDR(HW_LCD_B6_PORT) - 1), HW_LCD_B6_PIN #define set_b7_low cbi _SFR_IO_ADDR(HW_LCD_B7_PORT), HW_LCD_B7_PIN #define set_b7_high sbi _SFR_IO_ADDR(HW_LCD_B7_PORT), HW_LCD_B7_PIN #define set_b7_output sbi (_SFR_IO_ADDR(HW_LCD_B7_PORT) - 1), HW_LCD_B7_PIN ; for ST7108 Controller: select CS1 and CS2 #define set_cs1_low cbi _SFR_IO_ADDR(HW_LCD_CS1_PORT), HW_LCD_CS1_PIN #define set_cs1_high sbi _SFR_IO_ADDR(HW_LCD_CS1_PORT), HW_LCD_CS1_PIN #define set_cs1_output sbi (_SFR_IO_ADDR(HW_LCD_CS1_PORT) - 1), HW_LCD_CS1_PIN #define set_cs2_low cbi _SFR_IO_ADDR(HW_LCD_CS2_PORT), HW_LCD_CS2_PIN #define set_cs2_high sbi _SFR_IO_ADDR(HW_LCD_CS2_PORT), HW_LCD_CS2_PIN #define set_cs2_output sbi (_SFR_IO_ADDR(HW_LCD_CS2_PORT) - 1), HW_LCD_CS2_PIN #define set_clk_low cbi _SFR_IO_ADDR(HW_LCD_CLK_PORT), HW_LCD_CLK_PIN #define set_clk_high sbi _SFR_IO_ADDR(HW_LCD_CLK_PORT), HW_LCD_CLK_PIN #define set_clk_output sbi (_SFR_IO_ADDR(HW_LCD_CLK_PORT) - 1), HW_LCD_CLK_PIN #define set_pclk_low cbi _SFR_IO_ADDR(HW_LCD_PCLK_PORT), HW_LCD_PCLK_PIN #define set_pclk_high sbi _SFR_IO_ADDR(HW_LCD_PCLK_PORT), HW_LCD_PCLK_PIN #define set_pclk_output sbi (_SFR_IO_ADDR(HW_LCD_PCLK_PORT) - 1), HW_LCD_PCLK_PIN #define RCALL rcall /* For normal I2C mode use 5us wait time, but SSD1306 is faster, the cycle time is specified as 2.5us. */ /* So we use 2us, which results to a cycle time of >4us */ #define WAIT_I2C wait2us #define release_sda cbi (_SFR_IO_ADDR(HW_LCD_SDA_PORT) - 1), HW_LCD_SDA_PIN #define set_low_sda sbi (_SFR_IO_ADDR(HW_LCD_SDA_PORT) - 1), HW_LCD_SDA_PIN #define release_scl cbi (_SFR_IO_ADDR(HW_LCD_SCL_PORT) - 1), HW_LCD_SCL_PIN #define set_low_scl sbi (_SFR_IO_ADDR(HW_LCD_SCL_PORT) - 1), HW_LCD_SCL_PIN #define HW_LCD_SDA_OUT _SFR_IO_ADDR(HW_LCD_SDA_PORT) #define HW_LCD_SCL_OUT _SFR_IO_ADDR(HW_LCD_SCL_PORT) #define HW_LCD_SDA_IN (_SFR_IO_ADDR(HW_LCD_SDA_PORT) - 2) #define HW_LCD_SCL_IN (_SFR_IO_ADDR(HW_LCD_SCL_PORT) - 2) /* SSD1306 controller defines 0x3C or 0x3D (SA0=1) as address LCD_I2C_ADDR */ ;---------------------------------------------------------------------- ; ; "_lcd_hw_write" ; ; preg_1 (r24) = flags ; preg_2 (r22) = data ; ;---------------------------------------------------------------------- .global _lcd_hw_write .func _lcd_hw_write .extern wait1us .extern wait30us ; used only for slow 4-bit interface (SLOW_LCD) .extern wait50us ; used for ST7920 controller #if (LCD_INTERFACE_MODE == MODE_SPI) || (LCD_INTERFACE_MODE == MODE_3LINE) ;--------------------------------------------------------------------------------- ; serial output for ST7565 controller, 4-Bit SPI _lcd_hw_write: #ifdef LCD_SPI_OPEN_COL set_en_low set_en_output // en/CLK to GND #ifdef PULLUP_DISABLE AOUT MCUCR, r1 ; MCUCR = 0; //enable pull up resistors #endif set_ce_low set_ce_output // enable chip ; Set RS (0=Cmd, 1=Char) #if (LCD_INTERFACE_MODE == MODE_3LINE) sbrs preg_1, 0 rjmp clr_rs set_b0_input set_b0_high // enable B0 pullup rjmp set_sce clr_rs: set_b0_low set_b0_output set_sce: set_rs_low set_rs_output // SCE to GND; rcall wait1us set_en_input set_en_high // enable en pullup rcall wait1us #else sbrs preg_1, 0 rjmp clr_rs set_rs_input // set B0 to input set_rs_high // enable B0 pullup rjmp fini_rs clr_rs: set_rs_low set_rs_output // set B0 for RS to GND fini_rs: rcall wait1us #endif ; Send bit-7 ROL preg_2 // shift B7 to carry rcall shift_out ; Send bit-6 ROL preg_2 // shift B6 to carry rcall shift_out ; Send bit-5 ROL preg_2 // shift B5 to carry rcall shift_out ; Send bit-4 ROL preg_2 // shift B4 to carry rcall shift_out ; Send bit-3 ROL preg_2 // shift B3 to carry rcall shift_out ; Send bit-2 ROL preg_2 // shift B2 to carry rcall shift_out ; Send bit-1 ROL preg_2 // shift B1 to carry rcall shift_out ; Send bit-0 ROL preg_2 // shift B0 to carry rcall shift_out rcall wait1us set_en_low set_en_output // set en/clk to GND #if (LCD_INTERFACE_MODE == MODE_3LINE) // rcall wait1us set_rs_input // SCE to high set_rs_high // enable pullup #endif set_ce_input set_ce_high // disable chip #ifdef PULLUP_DISABLE ldi r25, (1<<PUD) ; AOUT MCUCR, r25 ; MCUCR = (1<<PUD); //disable pull up resistors #endif set_en_low set_en_output // en/CLK to GND set_b0_low // ## reset b0 to GND to prevent incorrect detection of rotary encoder movement set_b0_output // ## ret // return _lcd_hw_write // sub-function shift_out: send 1, if carry is set, send 0, if carry is reset shift_out: set_en_low set_en_output // set en/clk to GND brcc clr_bit set_b0_input // set B0 to input set_b0_high // enable B0 pullup = high rjmp fini_bit clr_bit: set_b0_low set_b0_output // set B0 for Bx to GND fini_bit: set_en_input set_en_high // enable en/clk pullup rcall wait1us ret #else /* no LCD_SPI_OPEN_COL */ #ifdef FAST_SPI_OUTPUT ; Set RS (0=Cmd, 1=Char) set_ce_low set_ce_output // enable chip #if (LCD_INTERFACE_MODE == MODE_3LINE) set_en_low sbrc preg_1, 0 set_b0_high sbrs preg_1, 0 set_b0_low set_b0_output ; set B0 to output set_rs_low ; SCE to GND set_rs_output //init hardware set_en_high ; force data read from LCD controller #else sbrc preg_1, 0 set_rs_high sbrs preg_1, 0 set_rs_low set_rs_output; //init hardware set_b0_output ; wait for address setup, set B0 to output #endif ; Send bit-7 set_en_low sbrc preg_2, 7 set_b0_high sbrs preg_2, 7 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-6 set_en_low sbrc preg_2, 6 set_b0_high sbrs preg_2, 6 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-5 set_en_low sbrc preg_2, 5 set_b0_high sbrs preg_2, 5 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-4 set_en_low sbrc preg_2, 4 set_b0_high sbrs preg_2, 4 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-3 set_en_low sbrc preg_2, 3 set_b0_high sbrs preg_2, 3 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-2 set_en_low sbrc preg_2, 2 set_b0_high sbrs preg_2, 2 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-1 set_en_low sbrc preg_2, 1 set_b0_high sbrs preg_2, 1 set_b0_low set_en_high ; force data read from LCD controller ; Send bit-0 set_en_low sbrc preg_2, 0 set_b0_high sbrs preg_2, 0 set_b0_low set_en_high ; force data read from LCD controller #if (LCD_INTERFACE_MODE == MODE_3LINE) set_rs_high ; SCE to VCC #endif set_ce_high // disable chip set_en_low set_b0_low // ## reset b0 to GND to prevent incorrect detection of rotary encoder movement ret // return _lcd_hw_write #else /* no FAST_SPI_OUTPUT */ ; Set RS (0=Cmd, 1=Char) set_ce_low // enable chip set_ce_output #if (LCD_INTERFACE_MODE == MODE_3LINE) set_en_low set_rs_low set_rs_output //init hardware sbrc preg_1, 0 set_b0_high // set to data sbrs preg_1, 0 set_b0_low // set to command set_b0_output ; set B0 to output set_rs_low ; SCE to GND set_en_high ; force data read from LCD controller #else sbrc preg_1, 0 set_rs_high sbrs preg_1, 0 set_rs_low set_rs_output; //init hardware set_b0_output ; wait for address setup, set B0 to output #endif ; Send bit-7 ROL preg_2 // shift B7 to carry rcall shift_out2 ; Send bit-6 ROL preg_2 // shift B6 to carry rcall shift_out2 ; Send bit-5 ROL preg_2 // shift B5 to carry rcall shift_out2 ; Send bit-4 ROL preg_2 // shift B4 to carry rcall shift_out2 ; Send bit-3 ROL preg_2 // shift B3 to carry rcall shift_out2 ; Send bit-2 ROL preg_2 // shift B2 to carry rcall shift_out2 ; Send bit-1 ROL preg_2 // shift B1 to carry rcall shift_out2 ; Send bit-0 ROL preg_2 // shift B0 to carry rcall shift_out2 #if (LCD_INTERFACE_MODE == MODE_3LINE) set_rs_high ; SCE to VCC #endif set_ce_high // disable chip set_en_low set_b0_low // ## reset b0 to GND to prevent incorrect detection of rotary encoder movement ret // return _lcd_hw_write shift_out2: set_en_low; brcs set_bit set_b0_low rjmp fini_bit set_bit: set_b0_high // enable B0 pullup fini_bit: set_b0_output // set B0 to output mode set_en_high // set en up ret #endif /* FAST_SPI_OUTPUT */ #endif /* LCD_SPI_OPEN_COL */ .endfunc #elif (LCD_INTERFACE_MODE == MODE_7920_SERIAL) || (LCD_INTERFACE_MODE == MODE_1803_SERIAL) ;--------------------------------------------------------------------------------- _lcd_hw_write: ; 1-bit interface for ST7920 controller set_b0_high set_b0_output ; enable output mode set_en_low set_en_output ; enable output mode RCALL toggle_en ; set en high and low RCALL four_bits ; output four times 1 set_b0_low ; RW to write RCALL toggle_en ; set en high and low sbrc preg_1, 0 set_b0_high ; data mode sbrs preg_1, 0 set_b0_low ; instruction mode RCALL toggle_en ; set en high and low set_b0_low RCALL toggle_en ; set en high and low ; first 8 bit transfer finished #if (LCD_INTERFACE_MODE == MODE_7920_SERIAL) ; output highest bit first sbrc preg_2, 7 set_b0_high ; bit 7 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 6 set_b0_high ; bit 6 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 5 set_b0_high ; bit 5 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 4 set_b0_high ; bit 4 == 1 RCALL toggle_en ; set en high and low set_b0_low RCALL four_bits ; output 4 times 0 ; the upper 4-bit are followed by 4 x 0 set_b0_low sbrc preg_2, 3 set_b0_high ; bit 3 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 2 set_b0_high ; bit 2 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 1 set_b0_high ; bit 1 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 0 set_b0_high ; bit 0 == 1 RCALL toggle_en ; set en high and low set_b0_low RCALL four_bits ; output 4 times 0 ; the lower 4-bit are followed by 4 x 0 #else /* (LCD_INTERFACE_MODE == MODE_1803_SERIAL) */ ; output lowest bit first sbrc preg_2, 0 set_b0_high ; bit 0 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 1 set_b0_high ; bit 1 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 2 set_b0_high ; bit 2 == 1 RCALL toggle_en ; set en high and low ; the upper 4-bit are followed by 4 x 0 set_b0_low sbrc preg_2, 3 set_b0_high ; bit 3 == 1 RCALL toggle_en ; set en high and low set_b0_low RCALL four_bits ; output 4 times 0 ; the lower 4-bit are followed by 4 x 0 set_b0_low sbrc preg_2, 4 set_b0_high ; bit 4 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 5 set_b0_high ; bit 5 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 6 set_b0_high ; bit 6 == 1 RCALL toggle_en ; set en high and low set_b0_low sbrc preg_2, 7 set_b0_high ; bit 7 == 1 RCALL toggle_en ; set en high and low set_b0_low RCALL four_bits ; output 4 times 0 ; the upper 4-bit are followed by 4 x 0 #endif RCALL wait50us RCALL wait30us ; at least 72 us delay ret // return _lcd_hw_write .endfunc /* output 4 times the same bit */ four_bits: RCALL toggle_en RCALL toggle_en RCALL toggle_en RCALL toggle_en ret toggle_en: set_en_high ;force data read from LCD controller set_en_high ; hold en high to meet the specification (300ns) set_en_low ; set SCLK back to low ret #elif (LCD_INTERFACE_MODE == MODE_I2C) ;--------------------------------------------------------------------------------- ;=================================================== _lcd_hw_write: ; use I2C as master push preg_2 push preg_1 ; save data/command release_scl rcall WAIT_I2C set_low_sda ; set START bit rcall WAIT_I2C ldi preg_1, (LCD_I2C_ADDR*2) rcall i2c_send ; write I2C address pop preg_2 ldi preg_1,0x80 ; send command type sbrc preg_2,0 ; skip if bit 0 is unset ldi preg_1,0x40 ; send data type rcall i2c_send ; send command/data pop preg_1 ;restore data from parameter rcall i2c_send ; write the data set_low_sda ; set the sda signal to low STOP rcall WAIT_I2C release_scl ; pullup move the scl signal to high rcall WAIT_I2C release_sda ; pullup move the sda signal to high, STOP rcall WAIT_I2C ret // return _lcd_hw_write ; ;=================================================== i2c_send: sec ;set carry rol preg_1 ; shift carry to r24 bit 0 and bit 7 of r24 to carry i2c_wf: set_low_scl ; scl signal to low, data change brcc wr0 ; carry was set release_sda ; pullup move the sda signal to high rjmp wr1 wr0: set_low_sda ; set the sda signal to low wr1: rcall WAIT_I2C ; wait defined time release_scl ; pullup move the scl signal to high rcall WAIT_I2C ; wait defined time lsl preg_1 brne i2c_wf ; 8 bit are transfered set_low_scl ; scl signal to low, data change release_sda ; give sda free rcall WAIT_I2C ; wait defined time release_scl ; pullup move the scl signal to high, ack cycle loop: sbis HW_LCD_SCL_IN, HW_LCD_SCL_PIN rjmp loop ; wait for releasing SCL ; r24 is zero, return 0 sbic HW_LCD_SDA_IN, HW_LCD_SDA_PIN ldi preg_1,1 ; if SDA is returned high, answer 1 rcall WAIT_I2C ; wait defined time set_low_scl rcall WAIT_I2C ; wait defined time ret .endfunc .global i2c_init .func i2c_init .extern wait5us i2c_init: release_sda release_scl cbi HW_LCD_SDA_OUT, HW_LCD_SDA_PIN ; set output to 0, no pull up cbi HW_LCD_SCL_OUT, HW_LCD_SCL_PIN ; set output to 0, no pull up ret .endfunc #elif (LCD_INTERFACE_MODE == MODE_7108_SERIAL) ;--------------------------------------------------------------------------------- _lcd_hw_write: ; serial interface for ST7108 controller set_clk_low set_clk_output set_pclk_low set_pclk_output set_en_low set_en_output set_b0_low set_b0_output sbrc preg_2, 7 set_b0_high ; bit 7 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 6 set_b0_high ; bit 6 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 5 set_b0_high ; bit 5 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 4 set_b0_high ; bit 4 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 3 set_b0_high ; bit 3 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 2 set_b0_high ; bit 2 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 1 set_b0_high ; bit 1 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif sbrc preg_2, 0 set_b0_high ; bit 0 == 1 #ifdef FAST_SERIAL_OUT set_clk_high ; set clk high and low set_clk_low set_b0_low #else RCALL toggle_clk ; set clk high and low #endif ; all 8 bit are loaded to the 74HC164 output set_pclk_high ; set parallel clk high and low set_pclk_low set_rs_low ; instruction mode set_rs_output ; if RS is set to same as B0, RS is allready output sbrc preg_1, 0 set_rs_high ; data mode RCALL wait1us ; hold the setup time of RS set_en_high RCALL wait1us set_en_low ; RCALL wait30us ; at least 30 us delay RCALL wait10us ; at least 10 us delay ret .endfunc #ifndef FAST_SERIAL_OUT toggle_clk: set_clk_high set_clk_high set_clk_low set_b0_low ret #endif #else /* !(LCD_INTERFACE_MODE == (MODE_SPI | MODE_7920_SERIAL | MODE_I2C | MODE_7108_SERIAL)) */ ;--------------------------------------------------------------------------------- _lcd_hw_write: ; must be a 4-bit parallel interface for HD44780 compatible controller or simular ; Set RS (0=Cmd, 1=Char) sbrc preg_1, 0 set_rs_high sbrs preg_1, 0 set_rs_low set_rs_output; //init hardware nop ; //wait for address setup set_en_high set_en_output; //init hardware ; Send high nibble set_b4_low set_b5_low set_b6_low set_b7_low sbrc preg_2, 4 set_b4_high set_b4_output; //init hardware sbrc preg_2, 5 set_b5_high set_b5_output; //init hardware sbrc preg_2, 6 set_b6_high set_b6_output; //init hardware sbrc preg_2, 7 set_b7_high set_b7_output; //init hardware nop ; wait for data setup time set_en_low ; force data read from LCD controller RCALL wait1us ; skip sending low nibble for init commands sbrc preg_1, 7 rjmp _lcd_hw_write_exit ; Send low nibble set_en_high set_b4_low set_b5_low set_b6_low set_b7_low sbrc preg_2, 0 set_b4_high sbrc preg_2, 1 set_b5_high sbrc preg_2, 2 set_b6_high sbrc preg_2, 3 set_b7_high nop ; wait for data setup time set_en_low ; force data read from LCD controller #if (LCD_ST_TYPE == 7920) RCALL wait50us #endif #ifdef SLOW_LCD RCALL wait50us #else RCALL wait1us #endif _lcd_hw_write_exit: ret ; end _lcd_hw_write .endfunc #endif /* LCD_INTERFACE_MODE */ ;---------------------------------------------------------------------- #if (LCD_ST_TYPE == 7108) .global _lcd_hw_select .func _lcd_hw_select ; select one of the two controllers or both ; ; preg_1 (r24) = bit 0 for CS1 and bit 1 for CS2 ; _lcd_hw_select: #ifdef ST_CS_LOW /* inverted CS level, 0 = enable */ sbrc preg_1, 0 set_cs1_low ; enable controller 1 sbrs preg_1, 0 set_cs1_high ; disable controller 1 sbrc preg_1, 1 set_cs2_low ; enable controller 2 sbrs preg_1, 1 set_cs2_high ; disable controller 2 #else /* not inverted CS level, 1 = enable */ sbrc preg_1, 0 set_cs1_high ; enable controller 1 sbrs preg_1, 0 set_cs1_low ; disable controller 1 sbrc preg_1, 1 set_cs2_high ; enable controller 2 sbrs preg_1, 1 set_cs2_low ; disable controller 2 #endif set_cs1_output ; enable output CS1 set_cs2_output ; enable output CS2 ret .endfunc #endif
wagerr/wagerr
28,453
src/secp256k1/src/asm/field_10x26_arm.s
@ vim: set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab syntax=armasm: /********************************************************************** * Copyright (c) 2014 Wladimir J. van der Laan * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* ARM implementation of field_10x26 inner loops. Note: - To avoid unnecessary loads and make use of available registers, two 'passes' have every time been interleaved, with the odd passes accumulating c' and d' which will be added to c and d respectively in the even passes */ .syntax unified .arch armv7-a @ eabi attributes - see readelf -A .eabi_attribute 8, 1 @ Tag_ARM_ISA_use = yes .eabi_attribute 9, 0 @ Tag_Thumb_ISA_use = no .eabi_attribute 10, 0 @ Tag_FP_arch = none .eabi_attribute 24, 1 @ Tag_ABI_align_needed = 8-byte .eabi_attribute 25, 1 @ Tag_ABI_align_preserved = 8-byte, except leaf SP .eabi_attribute 30, 2 @ Tag_ABI_optimization_goals = Aggressive Speed .eabi_attribute 34, 1 @ Tag_CPU_unaligned_access = v6 .text @ Field constants .set field_R0, 0x3d10 .set field_R1, 0x400 .set field_not_M, 0xfc000000 @ ~M = ~0x3ffffff .align 2 .global secp256k1_fe_mul_inner .type secp256k1_fe_mul_inner, %function @ Arguments: @ r0 r Restrict: can overlap with a, not with b @ r1 a @ r2 b @ Stack (total 4+10*4 = 44) @ sp + #0 saved 'r' pointer @ sp + #4 + 4*X t0,t1,t2,t3,t4,t5,t6,t7,u8,t9 secp256k1_fe_mul_inner: stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r14} sub sp, sp, #48 @ frame=44 + alignment str r0, [sp, #0] @ save result address, we need it only at the end /****************************************** * Main computation code. ****************************************** Allocation: r0,r14,r7,r8 scratch r1 a (pointer) r2 b (pointer) r3:r4 c r5:r6 d r11:r12 c' r9:r10 d' Note: do not write to r[] here, it may overlap with a[] */ /* A - interleaved with B */ ldr r7, [r1, #0*4] @ a[0] ldr r8, [r2, #9*4] @ b[9] ldr r0, [r1, #1*4] @ a[1] umull r5, r6, r7, r8 @ d = a[0] * b[9] ldr r14, [r2, #8*4] @ b[8] umull r9, r10, r0, r8 @ d' = a[1] * b[9] ldr r7, [r1, #2*4] @ a[2] umlal r5, r6, r0, r14 @ d += a[1] * b[8] ldr r8, [r2, #7*4] @ b[7] umlal r9, r10, r7, r14 @ d' += a[2] * b[8] ldr r0, [r1, #3*4] @ a[3] umlal r5, r6, r7, r8 @ d += a[2] * b[7] ldr r14, [r2, #6*4] @ b[6] umlal r9, r10, r0, r8 @ d' += a[3] * b[7] ldr r7, [r1, #4*4] @ a[4] umlal r5, r6, r0, r14 @ d += a[3] * b[6] ldr r8, [r2, #5*4] @ b[5] umlal r9, r10, r7, r14 @ d' += a[4] * b[6] ldr r0, [r1, #5*4] @ a[5] umlal r5, r6, r7, r8 @ d += a[4] * b[5] ldr r14, [r2, #4*4] @ b[4] umlal r9, r10, r0, r8 @ d' += a[5] * b[5] ldr r7, [r1, #6*4] @ a[6] umlal r5, r6, r0, r14 @ d += a[5] * b[4] ldr r8, [r2, #3*4] @ b[3] umlal r9, r10, r7, r14 @ d' += a[6] * b[4] ldr r0, [r1, #7*4] @ a[7] umlal r5, r6, r7, r8 @ d += a[6] * b[3] ldr r14, [r2, #2*4] @ b[2] umlal r9, r10, r0, r8 @ d' += a[7] * b[3] ldr r7, [r1, #8*4] @ a[8] umlal r5, r6, r0, r14 @ d += a[7] * b[2] ldr r8, [r2, #1*4] @ b[1] umlal r9, r10, r7, r14 @ d' += a[8] * b[2] ldr r0, [r1, #9*4] @ a[9] umlal r5, r6, r7, r8 @ d += a[8] * b[1] ldr r14, [r2, #0*4] @ b[0] umlal r9, r10, r0, r8 @ d' += a[9] * b[1] ldr r7, [r1, #0*4] @ a[0] umlal r5, r6, r0, r14 @ d += a[9] * b[0] @ r7,r14 used in B bic r0, r5, field_not_M @ t9 = d & M str r0, [sp, #4 + 4*9] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 /* B */ umull r3, r4, r7, r14 @ c = a[0] * b[0] adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u0 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u0 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t0 = c & M str r14, [sp, #4 + 0*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u0 * R1 umlal r3, r4, r0, r14 /* C - interleaved with D */ ldr r7, [r1, #0*4] @ a[0] ldr r8, [r2, #2*4] @ b[2] ldr r14, [r2, #1*4] @ b[1] umull r11, r12, r7, r8 @ c' = a[0] * b[2] ldr r0, [r1, #1*4] @ a[1] umlal r3, r4, r7, r14 @ c += a[0] * b[1] ldr r8, [r2, #0*4] @ b[0] umlal r11, r12, r0, r14 @ c' += a[1] * b[1] ldr r7, [r1, #2*4] @ a[2] umlal r3, r4, r0, r8 @ c += a[1] * b[0] ldr r14, [r2, #9*4] @ b[9] umlal r11, r12, r7, r8 @ c' += a[2] * b[0] ldr r0, [r1, #3*4] @ a[3] umlal r5, r6, r7, r14 @ d += a[2] * b[9] ldr r8, [r2, #8*4] @ b[8] umull r9, r10, r0, r14 @ d' = a[3] * b[9] ldr r7, [r1, #4*4] @ a[4] umlal r5, r6, r0, r8 @ d += a[3] * b[8] ldr r14, [r2, #7*4] @ b[7] umlal r9, r10, r7, r8 @ d' += a[4] * b[8] ldr r0, [r1, #5*4] @ a[5] umlal r5, r6, r7, r14 @ d += a[4] * b[7] ldr r8, [r2, #6*4] @ b[6] umlal r9, r10, r0, r14 @ d' += a[5] * b[7] ldr r7, [r1, #6*4] @ a[6] umlal r5, r6, r0, r8 @ d += a[5] * b[6] ldr r14, [r2, #5*4] @ b[5] umlal r9, r10, r7, r8 @ d' += a[6] * b[6] ldr r0, [r1, #7*4] @ a[7] umlal r5, r6, r7, r14 @ d += a[6] * b[5] ldr r8, [r2, #4*4] @ b[4] umlal r9, r10, r0, r14 @ d' += a[7] * b[5] ldr r7, [r1, #8*4] @ a[8] umlal r5, r6, r0, r8 @ d += a[7] * b[4] ldr r14, [r2, #3*4] @ b[3] umlal r9, r10, r7, r8 @ d' += a[8] * b[4] ldr r0, [r1, #9*4] @ a[9] umlal r5, r6, r7, r14 @ d += a[8] * b[3] ldr r8, [r2, #2*4] @ b[2] umlal r9, r10, r0, r14 @ d' += a[9] * b[3] umlal r5, r6, r0, r8 @ d += a[9] * b[2] bic r0, r5, field_not_M @ u1 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u1 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t1 = c & M str r14, [sp, #4 + 1*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u1 * R1 umlal r3, r4, r0, r14 /* D */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u2 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u2 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t2 = c & M str r14, [sp, #4 + 2*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u2 * R1 umlal r3, r4, r0, r14 /* E - interleaved with F */ ldr r7, [r1, #0*4] @ a[0] ldr r8, [r2, #4*4] @ b[4] umull r11, r12, r7, r8 @ c' = a[0] * b[4] ldr r8, [r2, #3*4] @ b[3] umlal r3, r4, r7, r8 @ c += a[0] * b[3] ldr r7, [r1, #1*4] @ a[1] umlal r11, r12, r7, r8 @ c' += a[1] * b[3] ldr r8, [r2, #2*4] @ b[2] umlal r3, r4, r7, r8 @ c += a[1] * b[2] ldr r7, [r1, #2*4] @ a[2] umlal r11, r12, r7, r8 @ c' += a[2] * b[2] ldr r8, [r2, #1*4] @ b[1] umlal r3, r4, r7, r8 @ c += a[2] * b[1] ldr r7, [r1, #3*4] @ a[3] umlal r11, r12, r7, r8 @ c' += a[3] * b[1] ldr r8, [r2, #0*4] @ b[0] umlal r3, r4, r7, r8 @ c += a[3] * b[0] ldr r7, [r1, #4*4] @ a[4] umlal r11, r12, r7, r8 @ c' += a[4] * b[0] ldr r8, [r2, #9*4] @ b[9] umlal r5, r6, r7, r8 @ d += a[4] * b[9] ldr r7, [r1, #5*4] @ a[5] umull r9, r10, r7, r8 @ d' = a[5] * b[9] ldr r8, [r2, #8*4] @ b[8] umlal r5, r6, r7, r8 @ d += a[5] * b[8] ldr r7, [r1, #6*4] @ a[6] umlal r9, r10, r7, r8 @ d' += a[6] * b[8] ldr r8, [r2, #7*4] @ b[7] umlal r5, r6, r7, r8 @ d += a[6] * b[7] ldr r7, [r1, #7*4] @ a[7] umlal r9, r10, r7, r8 @ d' += a[7] * b[7] ldr r8, [r2, #6*4] @ b[6] umlal r5, r6, r7, r8 @ d += a[7] * b[6] ldr r7, [r1, #8*4] @ a[8] umlal r9, r10, r7, r8 @ d' += a[8] * b[6] ldr r8, [r2, #5*4] @ b[5] umlal r5, r6, r7, r8 @ d += a[8] * b[5] ldr r7, [r1, #9*4] @ a[9] umlal r9, r10, r7, r8 @ d' += a[9] * b[5] ldr r8, [r2, #4*4] @ b[4] umlal r5, r6, r7, r8 @ d += a[9] * b[4] bic r0, r5, field_not_M @ u3 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u3 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t3 = c & M str r14, [sp, #4 + 3*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u3 * R1 umlal r3, r4, r0, r14 /* F */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u4 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u4 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t4 = c & M str r14, [sp, #4 + 4*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u4 * R1 umlal r3, r4, r0, r14 /* G - interleaved with H */ ldr r7, [r1, #0*4] @ a[0] ldr r8, [r2, #6*4] @ b[6] ldr r14, [r2, #5*4] @ b[5] umull r11, r12, r7, r8 @ c' = a[0] * b[6] ldr r0, [r1, #1*4] @ a[1] umlal r3, r4, r7, r14 @ c += a[0] * b[5] ldr r8, [r2, #4*4] @ b[4] umlal r11, r12, r0, r14 @ c' += a[1] * b[5] ldr r7, [r1, #2*4] @ a[2] umlal r3, r4, r0, r8 @ c += a[1] * b[4] ldr r14, [r2, #3*4] @ b[3] umlal r11, r12, r7, r8 @ c' += a[2] * b[4] ldr r0, [r1, #3*4] @ a[3] umlal r3, r4, r7, r14 @ c += a[2] * b[3] ldr r8, [r2, #2*4] @ b[2] umlal r11, r12, r0, r14 @ c' += a[3] * b[3] ldr r7, [r1, #4*4] @ a[4] umlal r3, r4, r0, r8 @ c += a[3] * b[2] ldr r14, [r2, #1*4] @ b[1] umlal r11, r12, r7, r8 @ c' += a[4] * b[2] ldr r0, [r1, #5*4] @ a[5] umlal r3, r4, r7, r14 @ c += a[4] * b[1] ldr r8, [r2, #0*4] @ b[0] umlal r11, r12, r0, r14 @ c' += a[5] * b[1] ldr r7, [r1, #6*4] @ a[6] umlal r3, r4, r0, r8 @ c += a[5] * b[0] ldr r14, [r2, #9*4] @ b[9] umlal r11, r12, r7, r8 @ c' += a[6] * b[0] ldr r0, [r1, #7*4] @ a[7] umlal r5, r6, r7, r14 @ d += a[6] * b[9] ldr r8, [r2, #8*4] @ b[8] umull r9, r10, r0, r14 @ d' = a[7] * b[9] ldr r7, [r1, #8*4] @ a[8] umlal r5, r6, r0, r8 @ d += a[7] * b[8] ldr r14, [r2, #7*4] @ b[7] umlal r9, r10, r7, r8 @ d' += a[8] * b[8] ldr r0, [r1, #9*4] @ a[9] umlal r5, r6, r7, r14 @ d += a[8] * b[7] ldr r8, [r2, #6*4] @ b[6] umlal r9, r10, r0, r14 @ d' += a[9] * b[7] umlal r5, r6, r0, r8 @ d += a[9] * b[6] bic r0, r5, field_not_M @ u5 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u5 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t5 = c & M str r14, [sp, #4 + 5*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u5 * R1 umlal r3, r4, r0, r14 /* H */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u6 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u6 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t6 = c & M str r14, [sp, #4 + 6*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u6 * R1 umlal r3, r4, r0, r14 /* I - interleaved with J */ ldr r8, [r2, #8*4] @ b[8] ldr r7, [r1, #0*4] @ a[0] ldr r14, [r2, #7*4] @ b[7] umull r11, r12, r7, r8 @ c' = a[0] * b[8] ldr r0, [r1, #1*4] @ a[1] umlal r3, r4, r7, r14 @ c += a[0] * b[7] ldr r8, [r2, #6*4] @ b[6] umlal r11, r12, r0, r14 @ c' += a[1] * b[7] ldr r7, [r1, #2*4] @ a[2] umlal r3, r4, r0, r8 @ c += a[1] * b[6] ldr r14, [r2, #5*4] @ b[5] umlal r11, r12, r7, r8 @ c' += a[2] * b[6] ldr r0, [r1, #3*4] @ a[3] umlal r3, r4, r7, r14 @ c += a[2] * b[5] ldr r8, [r2, #4*4] @ b[4] umlal r11, r12, r0, r14 @ c' += a[3] * b[5] ldr r7, [r1, #4*4] @ a[4] umlal r3, r4, r0, r8 @ c += a[3] * b[4] ldr r14, [r2, #3*4] @ b[3] umlal r11, r12, r7, r8 @ c' += a[4] * b[4] ldr r0, [r1, #5*4] @ a[5] umlal r3, r4, r7, r14 @ c += a[4] * b[3] ldr r8, [r2, #2*4] @ b[2] umlal r11, r12, r0, r14 @ c' += a[5] * b[3] ldr r7, [r1, #6*4] @ a[6] umlal r3, r4, r0, r8 @ c += a[5] * b[2] ldr r14, [r2, #1*4] @ b[1] umlal r11, r12, r7, r8 @ c' += a[6] * b[2] ldr r0, [r1, #7*4] @ a[7] umlal r3, r4, r7, r14 @ c += a[6] * b[1] ldr r8, [r2, #0*4] @ b[0] umlal r11, r12, r0, r14 @ c' += a[7] * b[1] ldr r7, [r1, #8*4] @ a[8] umlal r3, r4, r0, r8 @ c += a[7] * b[0] ldr r14, [r2, #9*4] @ b[9] umlal r11, r12, r7, r8 @ c' += a[8] * b[0] ldr r0, [r1, #9*4] @ a[9] umlal r5, r6, r7, r14 @ d += a[8] * b[9] ldr r8, [r2, #8*4] @ b[8] umull r9, r10, r0, r14 @ d' = a[9] * b[9] umlal r5, r6, r0, r8 @ d += a[9] * b[8] bic r0, r5, field_not_M @ u7 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u7 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t7 = c & M str r14, [sp, #4 + 7*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u7 * R1 umlal r3, r4, r0, r14 /* J */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u8 = d & M str r0, [sp, #4 + 8*4] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u8 * R0 umlal r3, r4, r0, r14 /****************************************** * compute and write back result ****************************************** Allocation: r0 r r3:r4 c r5:r6 d r7 t0 r8 t1 r9 t2 r11 u8 r12 t9 r1,r2,r10,r14 scratch Note: do not read from a[] after here, it may overlap with r[] */ ldr r0, [sp, #0] add r1, sp, #4 + 3*4 @ r[3..7] = t3..7, r11=u8, r12=t9 ldmia r1, {r2,r7,r8,r9,r10,r11,r12} add r1, r0, #3*4 stmia r1, {r2,r7,r8,r9,r10} bic r2, r3, field_not_M @ r[8] = c & M str r2, [r0, #8*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u8 * R1 umlal r3, r4, r11, r14 movw r14, field_R0 @ c += d * R0 umlal r3, r4, r5, r14 adds r3, r3, r12 @ c += t9 adc r4, r4, #0 add r1, sp, #4 + 0*4 @ r7,r8,r9 = t0,t1,t2 ldmia r1, {r7,r8,r9} ubfx r2, r3, #0, #22 @ r[9] = c & (M >> 4) str r2, [r0, #9*4] mov r3, r3, lsr #22 @ c >>= 22 orr r3, r3, r4, asl #10 mov r4, r4, lsr #22 movw r14, field_R1 << 4 @ c += d * (R1 << 4) umlal r3, r4, r5, r14 movw r14, field_R0 >> 4 @ d = c * (R0 >> 4) + t0 (64x64 multiply+add) umull r5, r6, r3, r14 @ d = c.lo * (R0 >> 4) adds r5, r5, r7 @ d.lo += t0 mla r6, r14, r4, r6 @ d.hi += c.hi * (R0 >> 4) adc r6, r6, 0 @ d.hi += carry bic r2, r5, field_not_M @ r[0] = d & M str r2, [r0, #0*4] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R1 >> 4 @ d += c * (R1 >> 4) + t1 (64x64 multiply+add) umull r1, r2, r3, r14 @ tmp = c.lo * (R1 >> 4) adds r5, r5, r8 @ d.lo += t1 adc r6, r6, #0 @ d.hi += carry adds r5, r5, r1 @ d.lo += tmp.lo mla r2, r14, r4, r2 @ tmp.hi += c.hi * (R1 >> 4) adc r6, r6, r2 @ d.hi += carry + tmp.hi bic r2, r5, field_not_M @ r[1] = d & M str r2, [r0, #1*4] mov r5, r5, lsr #26 @ d >>= 26 (ignore hi) orr r5, r5, r6, asl #6 add r5, r5, r9 @ d += t2 str r5, [r0, #2*4] @ r[2] = d add sp, sp, #48 ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc} .size secp256k1_fe_mul_inner, .-secp256k1_fe_mul_inner .align 2 .global secp256k1_fe_sqr_inner .type secp256k1_fe_sqr_inner, %function @ Arguments: @ r0 r Can overlap with a @ r1 a @ Stack (total 4+10*4 = 44) @ sp + #0 saved 'r' pointer @ sp + #4 + 4*X t0,t1,t2,t3,t4,t5,t6,t7,u8,t9 secp256k1_fe_sqr_inner: stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r14} sub sp, sp, #48 @ frame=44 + alignment str r0, [sp, #0] @ save result address, we need it only at the end /****************************************** * Main computation code. ****************************************** Allocation: r0,r14,r2,r7,r8 scratch r1 a (pointer) r3:r4 c r5:r6 d r11:r12 c' r9:r10 d' Note: do not write to r[] here, it may overlap with a[] */ /* A interleaved with B */ ldr r0, [r1, #1*4] @ a[1]*2 ldr r7, [r1, #0*4] @ a[0] mov r0, r0, asl #1 ldr r14, [r1, #9*4] @ a[9] umull r3, r4, r7, r7 @ c = a[0] * a[0] ldr r8, [r1, #8*4] @ a[8] mov r7, r7, asl #1 umull r5, r6, r7, r14 @ d = a[0]*2 * a[9] ldr r7, [r1, #2*4] @ a[2]*2 umull r9, r10, r0, r14 @ d' = a[1]*2 * a[9] ldr r14, [r1, #7*4] @ a[7] umlal r5, r6, r0, r8 @ d += a[1]*2 * a[8] mov r7, r7, asl #1 ldr r0, [r1, #3*4] @ a[3]*2 umlal r9, r10, r7, r8 @ d' += a[2]*2 * a[8] ldr r8, [r1, #6*4] @ a[6] umlal r5, r6, r7, r14 @ d += a[2]*2 * a[7] mov r0, r0, asl #1 ldr r7, [r1, #4*4] @ a[4]*2 umlal r9, r10, r0, r14 @ d' += a[3]*2 * a[7] ldr r14, [r1, #5*4] @ a[5] mov r7, r7, asl #1 umlal r5, r6, r0, r8 @ d += a[3]*2 * a[6] umlal r9, r10, r7, r8 @ d' += a[4]*2 * a[6] umlal r5, r6, r7, r14 @ d += a[4]*2 * a[5] umlal r9, r10, r14, r14 @ d' += a[5] * a[5] bic r0, r5, field_not_M @ t9 = d & M str r0, [sp, #4 + 9*4] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 /* B */ adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u0 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u0 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t0 = c & M str r14, [sp, #4 + 0*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u0 * R1 umlal r3, r4, r0, r14 /* C interleaved with D */ ldr r0, [r1, #0*4] @ a[0]*2 ldr r14, [r1, #1*4] @ a[1] mov r0, r0, asl #1 ldr r8, [r1, #2*4] @ a[2] umlal r3, r4, r0, r14 @ c += a[0]*2 * a[1] mov r7, r8, asl #1 @ a[2]*2 umull r11, r12, r14, r14 @ c' = a[1] * a[1] ldr r14, [r1, #9*4] @ a[9] umlal r11, r12, r0, r8 @ c' += a[0]*2 * a[2] ldr r0, [r1, #3*4] @ a[3]*2 ldr r8, [r1, #8*4] @ a[8] umlal r5, r6, r7, r14 @ d += a[2]*2 * a[9] mov r0, r0, asl #1 ldr r7, [r1, #4*4] @ a[4]*2 umull r9, r10, r0, r14 @ d' = a[3]*2 * a[9] ldr r14, [r1, #7*4] @ a[7] umlal r5, r6, r0, r8 @ d += a[3]*2 * a[8] mov r7, r7, asl #1 ldr r0, [r1, #5*4] @ a[5]*2 umlal r9, r10, r7, r8 @ d' += a[4]*2 * a[8] ldr r8, [r1, #6*4] @ a[6] mov r0, r0, asl #1 umlal r5, r6, r7, r14 @ d += a[4]*2 * a[7] umlal r9, r10, r0, r14 @ d' += a[5]*2 * a[7] umlal r5, r6, r0, r8 @ d += a[5]*2 * a[6] umlal r9, r10, r8, r8 @ d' += a[6] * a[6] bic r0, r5, field_not_M @ u1 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u1 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t1 = c & M str r14, [sp, #4 + 1*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u1 * R1 umlal r3, r4, r0, r14 /* D */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u2 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u2 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t2 = c & M str r14, [sp, #4 + 2*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u2 * R1 umlal r3, r4, r0, r14 /* E interleaved with F */ ldr r7, [r1, #0*4] @ a[0]*2 ldr r0, [r1, #1*4] @ a[1]*2 ldr r14, [r1, #2*4] @ a[2] mov r7, r7, asl #1 ldr r8, [r1, #3*4] @ a[3] ldr r2, [r1, #4*4] umlal r3, r4, r7, r8 @ c += a[0]*2 * a[3] mov r0, r0, asl #1 umull r11, r12, r7, r2 @ c' = a[0]*2 * a[4] mov r2, r2, asl #1 @ a[4]*2 umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[3] ldr r8, [r1, #9*4] @ a[9] umlal r3, r4, r0, r14 @ c += a[1]*2 * a[2] ldr r0, [r1, #5*4] @ a[5]*2 umlal r11, r12, r14, r14 @ c' += a[2] * a[2] ldr r14, [r1, #8*4] @ a[8] mov r0, r0, asl #1 umlal r5, r6, r2, r8 @ d += a[4]*2 * a[9] ldr r7, [r1, #6*4] @ a[6]*2 umull r9, r10, r0, r8 @ d' = a[5]*2 * a[9] mov r7, r7, asl #1 ldr r8, [r1, #7*4] @ a[7] umlal r5, r6, r0, r14 @ d += a[5]*2 * a[8] umlal r9, r10, r7, r14 @ d' += a[6]*2 * a[8] umlal r5, r6, r7, r8 @ d += a[6]*2 * a[7] umlal r9, r10, r8, r8 @ d' += a[7] * a[7] bic r0, r5, field_not_M @ u3 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u3 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t3 = c & M str r14, [sp, #4 + 3*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u3 * R1 umlal r3, r4, r0, r14 /* F */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u4 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u4 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t4 = c & M str r14, [sp, #4 + 4*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u4 * R1 umlal r3, r4, r0, r14 /* G interleaved with H */ ldr r7, [r1, #0*4] @ a[0]*2 ldr r0, [r1, #1*4] @ a[1]*2 mov r7, r7, asl #1 ldr r8, [r1, #5*4] @ a[5] ldr r2, [r1, #6*4] @ a[6] umlal r3, r4, r7, r8 @ c += a[0]*2 * a[5] ldr r14, [r1, #4*4] @ a[4] mov r0, r0, asl #1 umull r11, r12, r7, r2 @ c' = a[0]*2 * a[6] ldr r7, [r1, #2*4] @ a[2]*2 umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[5] mov r7, r7, asl #1 ldr r8, [r1, #3*4] @ a[3] umlal r3, r4, r0, r14 @ c += a[1]*2 * a[4] mov r0, r2, asl #1 @ a[6]*2 umlal r11, r12, r7, r14 @ c' += a[2]*2 * a[4] ldr r14, [r1, #9*4] @ a[9] umlal r3, r4, r7, r8 @ c += a[2]*2 * a[3] ldr r7, [r1, #7*4] @ a[7]*2 umlal r11, r12, r8, r8 @ c' += a[3] * a[3] mov r7, r7, asl #1 ldr r8, [r1, #8*4] @ a[8] umlal r5, r6, r0, r14 @ d += a[6]*2 * a[9] umull r9, r10, r7, r14 @ d' = a[7]*2 * a[9] umlal r5, r6, r7, r8 @ d += a[7]*2 * a[8] umlal r9, r10, r8, r8 @ d' += a[8] * a[8] bic r0, r5, field_not_M @ u5 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u5 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t5 = c & M str r14, [sp, #4 + 5*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u5 * R1 umlal r3, r4, r0, r14 /* H */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 adds r5, r5, r9 @ d += d' adc r6, r6, r10 bic r0, r5, field_not_M @ u6 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u6 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t6 = c & M str r14, [sp, #4 + 6*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u6 * R1 umlal r3, r4, r0, r14 /* I interleaved with J */ ldr r7, [r1, #0*4] @ a[0]*2 ldr r0, [r1, #1*4] @ a[1]*2 mov r7, r7, asl #1 ldr r8, [r1, #7*4] @ a[7] ldr r2, [r1, #8*4] @ a[8] umlal r3, r4, r7, r8 @ c += a[0]*2 * a[7] ldr r14, [r1, #6*4] @ a[6] mov r0, r0, asl #1 umull r11, r12, r7, r2 @ c' = a[0]*2 * a[8] ldr r7, [r1, #2*4] @ a[2]*2 umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[7] ldr r8, [r1, #5*4] @ a[5] umlal r3, r4, r0, r14 @ c += a[1]*2 * a[6] ldr r0, [r1, #3*4] @ a[3]*2 mov r7, r7, asl #1 umlal r11, r12, r7, r14 @ c' += a[2]*2 * a[6] ldr r14, [r1, #4*4] @ a[4] mov r0, r0, asl #1 umlal r3, r4, r7, r8 @ c += a[2]*2 * a[5] mov r2, r2, asl #1 @ a[8]*2 umlal r11, r12, r0, r8 @ c' += a[3]*2 * a[5] umlal r3, r4, r0, r14 @ c += a[3]*2 * a[4] umlal r11, r12, r14, r14 @ c' += a[4] * a[4] ldr r8, [r1, #9*4] @ a[9] umlal r5, r6, r2, r8 @ d += a[8]*2 * a[9] @ r8 will be used in J bic r0, r5, field_not_M @ u7 = d & M mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u7 * R0 umlal r3, r4, r0, r14 bic r14, r3, field_not_M @ t7 = c & M str r14, [sp, #4 + 7*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u7 * R1 umlal r3, r4, r0, r14 /* J */ adds r3, r3, r11 @ c += c' adc r4, r4, r12 umlal r5, r6, r8, r8 @ d += a[9] * a[9] bic r0, r5, field_not_M @ u8 = d & M str r0, [sp, #4 + 8*4] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R0 @ c += u8 * R0 umlal r3, r4, r0, r14 /****************************************** * compute and write back result ****************************************** Allocation: r0 r r3:r4 c r5:r6 d r7 t0 r8 t1 r9 t2 r11 u8 r12 t9 r1,r2,r10,r14 scratch Note: do not read from a[] after here, it may overlap with r[] */ ldr r0, [sp, #0] add r1, sp, #4 + 3*4 @ r[3..7] = t3..7, r11=u8, r12=t9 ldmia r1, {r2,r7,r8,r9,r10,r11,r12} add r1, r0, #3*4 stmia r1, {r2,r7,r8,r9,r10} bic r2, r3, field_not_M @ r[8] = c & M str r2, [r0, #8*4] mov r3, r3, lsr #26 @ c >>= 26 orr r3, r3, r4, asl #6 mov r4, r4, lsr #26 mov r14, field_R1 @ c += u8 * R1 umlal r3, r4, r11, r14 movw r14, field_R0 @ c += d * R0 umlal r3, r4, r5, r14 adds r3, r3, r12 @ c += t9 adc r4, r4, #0 add r1, sp, #4 + 0*4 @ r7,r8,r9 = t0,t1,t2 ldmia r1, {r7,r8,r9} ubfx r2, r3, #0, #22 @ r[9] = c & (M >> 4) str r2, [r0, #9*4] mov r3, r3, lsr #22 @ c >>= 22 orr r3, r3, r4, asl #10 mov r4, r4, lsr #22 movw r14, field_R1 << 4 @ c += d * (R1 << 4) umlal r3, r4, r5, r14 movw r14, field_R0 >> 4 @ d = c * (R0 >> 4) + t0 (64x64 multiply+add) umull r5, r6, r3, r14 @ d = c.lo * (R0 >> 4) adds r5, r5, r7 @ d.lo += t0 mla r6, r14, r4, r6 @ d.hi += c.hi * (R0 >> 4) adc r6, r6, 0 @ d.hi += carry bic r2, r5, field_not_M @ r[0] = d & M str r2, [r0, #0*4] mov r5, r5, lsr #26 @ d >>= 26 orr r5, r5, r6, asl #6 mov r6, r6, lsr #26 movw r14, field_R1 >> 4 @ d += c * (R1 >> 4) + t1 (64x64 multiply+add) umull r1, r2, r3, r14 @ tmp = c.lo * (R1 >> 4) adds r5, r5, r8 @ d.lo += t1 adc r6, r6, #0 @ d.hi += carry adds r5, r5, r1 @ d.lo += tmp.lo mla r2, r14, r4, r2 @ tmp.hi += c.hi * (R1 >> 4) adc r6, r6, r2 @ d.hi += carry + tmp.hi bic r2, r5, field_not_M @ r[1] = d & M str r2, [r0, #1*4] mov r5, r5, lsr #26 @ d >>= 26 (ignore hi) orr r5, r5, r6, asl #6 add r5, r5, r9 @ d += t2 str r5, [r0, #2*4] @ r[2] = d add sp, sp, #48 ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc} .size secp256k1_fe_sqr_inner, .-secp256k1_fe_sqr_inner
wagiminator/ATmega-Transistor-Tester
27,761
software/sources/GetESR.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include <avr/eeprom.h> #include <stdlib.h> #include "config.h" #include "part_defs.h" .GLOBAL GetESR .func GetESR /* MAX_CNT is the maximum loop counter for repetition of mesurement */ #define MAX_CNT 255 /* ADC_Sleep_Mode enables the sleep state for reading ADC */ //#define ADC_Sleep_Mode /* ESR_DEBUG enables additional Output on row 3 and row 4 */ //#define ESR_DEBUG #ifdef INHIBIT_SLEEP_MODE /* Makefile option set to disable the sleep mode */ #undef ADC_Sleep_Mode #endif #define zero_reg r1 // uint8_t big_cap; // #define big_cap 1 #if defined(__AVR_ATmega2560__) // ATmega2560 uses 3 bytes for return address #define RetAdr 3 #else // normalle 2 bytes are used for the return address #define RetAdr 2 #endif // unsigned long sumvolt0,sumvolt1,sumvolt2; // 3 sums of ADC readings #define sumvolt0 RetAdr /* r14-r17 */ #define sumvolt1 RetAdr+4 /* SP + 6:9 */ #define sumvolt2 RetAdr+8 /* SP + 10:13 */ // uint8_t LoADC; // used to switch Lowpin directly to GND or VCC #define LoADC RetAdr+12 /* SP + 14 */ // uint8_t HiADC; // used to switch Highpin directly to GND or VCC #define HiADC RetAdr+13 /* SP + 15 */ // unsigned int adcv[4]; // array for 4 ADC readings // first part adcv0 r2/r3 // first part adcv1 Y+16/17 #define adcvv1 RetAdr+14 // first part adcv2 Y+18/19 #define adcvv2 RetAdr+16 // unsigned long cap_val_nF; // capacity in nF #define cap_val_nF RetAdr+18 /* SP + 20:23 */ #define LowUpCount RetAdr+22 /* SP + 24 */ #define HighUpCount RetAdr+23 /* SP + 25 */ #define LowTooHigh RetAdr+24 /* SP + 26 */ #define HighTooHigh RetAdr+25 /* SP + 27 */ #define adcv0L r2 #define adcv0H r3 #define adcv2L r24 #define adcv2H r25 #define HiPinR_L r12 /* used to switch 680 Ohm to HighPin */ #define LoPinR_L r7 /* used to switch 680 Ohm to LowPin */ // uint8_t ii,jj; // tempory values #define StartADCmsk r10 /* Bit mask to start the ADC */ #define SelectLowPin r6 #define SelectHighPin r11 // Structure cap: .extern cap #define cval_max 4 #define esr 12 #define ca 16 #define cb 17 #define cpre_max 19 .extern EE_ESR_ZEROtab #ifdef ADC_Sleep_Mode // #define StartADCwait() ADCSRA = (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | AUTO_CLOCK_DIV; /* enable ADC and Interrupt */ // set_sleep_mode(SLEEP_MODE_ADC); // sleep_mode() /* Start ADC, return if ADC has finished */ .macro StartADCwait ldi r24, (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ sleep; /* wait for ADC */ ldi r24, (1 << SM0) | (0 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ .endm #else // #define StartADCwait() ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable ADC and start */ .macro StartADCwait sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk = r10 */ lds r24, ADCSRA; /* while (ADCSRA & (1 <<ADSC)) */ sbrc r24, ADSC; rjmp .-8 ; /* wait until conversion is done */ .endm #endif #define HALF_PULSE_LENGTH_TICS (F_CPU_HZ / 1000000) //================================================================= ; #define WITHOUT_PROLOGUE /* to use the local push / pop techniques */ ; without the local push/pop you can save 82 bytes Flash memory //================================================================= //void GetESR(uint8_t hipin, uint8_t lopin) { .section .text GetESR: #ifdef WITHOUT_PROLOGUE push r2; push r3; push r4; push r5; push r6; push r7; push r8; push r9; push r10; push r11; push r12; push r13; push r14; push r15; push r16; push r17; push r29; push r28; in r28, _SFR_IO_ADDR(SPL); in r29, _SFR_IO_ADDR(SPH); sbiw r28, 30 ; in r0, _SFR_IO_ADDR(SREG); cli out _SFR_IO_ADDR(SPH), r29; out _SFR_IO_ADDR(SREG), r0; out _SFR_IO_ADDR(SPL), r28; #else .extern __prologue_saves__ .extern __epilogue_restores__ ldi r26, 30 ; ldi r27, 0 ; ldi r30, lo8(gs(Retur2)) ; ldi r31, hi8(gs(Retur2)) ; jmp __prologue_saves__ ; Retur2: #endif #if TP_MIN > 0 subi r22, TP_MIN subi r24, TP_MIN #endif mov SelectLowPin, r22; mov SelectHighPin, r24; add r24, r22; std Y+1, r24; lds r18, PartFound; /* if (PartFound == PART_CAPACITOR) { */ cpi r18, PART_CAPACITOR; ; brne ad_35e4; brne load_max; lds r18, cap+cval_max; /* cap_val_nF = cap.cval_max; */ lds r19, cap+cval_max+1; lds r20, cap+cval_max+2; lds r21, cap+cval_max+3; sbrc r21, 7; /* negativ bit is set */ rjmp set_high lds r17, cap+cpre_max; /* prefix = cap.cpre_max; */ rjmp ad_35ba; ad_35ac: movw r24, r20; /* cval /= 10; // reduce value by factor ten */ movw r22, r18 ldi r18, 0x0A; 10 mov r19, zero_reg mov r20, zero_reg mov r21, zero_reg call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ subi r17, 0xFF; /* prefix++; // take next decimal prefix */ ad_35ba: cpi r17, -9; /* while (prefix < -9) { // set cval to nF unit */ brlt ad_35ac; /* } */ brne load_max; /* load max value for correction */ ; cpi r18, lo8(900/10); /* if (cap_val_nF < (900/10)) return(0xffff); //capacity lower than 90 nF */ ; ldi r22, hi8(900/10) cpi r18, lo8(200/10); /* if (cap_val_nF < (200/10)) return(0xffff); //capacity lower than 20 nF */ ldi r22, hi8(200/10) cpc r19, r22 cpc r20, zero_reg cpc r21, zero_reg brcc ad_35e4 set_high: ldi r24, 0xff; ldi r25, 0xff; rjmp ad_exit; ad_35e4: /* } */ cpi r17, -9; /* if ((pp > -9) || (cap_val_nF > 32000)) { */ brne load_max; ldi r24, lo8(32000); cp r18, r24 ldi r24, hi8(32000); cpc r19, r24; ; ldi r24, hlo8(32000); ; cpc r20, r24; cpc r20, r1; ; ldi r24, hhi8(32000); ; cpc r21, r24; cpc r20, r1; brcs store_cvn; load_max: ldi r18, lo8(32000); /* cap_val_nF = 65000 */ ldi r19, hi8(32000); ; ldi r20, hlo8(32000); /* upper word is allways zero */ ; ldi r21, hhi8(32000); /* upper word is allways zero */ store_cvn: std Y+cap_val_nF, r18 std Y+cap_val_nF+1, r19 ; std Y+cap_val_nF+2, r20; /* upper word is allways zero */ ; std Y+cap_val_nF+3, r21; /* upper word is allways zero */ #ifdef ADC_Sleep_Mode ldi r24, (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r24; /* SMCR = (1 << SM0) | (1 << SE); */ /* normal ADC-speed, ADC-Clock 8us */ ldi r25, (1<<ADEN) | (1<<ADIF) | (1<<ADIE) | AUTO_CLOCK_DIV; /* enable ADC and Interrupt */ mov StartADCmsk, r25; sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #else ldi r18, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable and start ADC */ mov StartADCmsk, r18; #endif #if (((PIN_RL1 + 1) != PIN_RH1) || ((PIN_RL2 + 1) != PIN_RH2) || ((PIN_RL3 + 1) != PIN_RH3)) LDIZ PinRLRHADCtab+6; /* LoADC = pgm_read_byte((&PinRLRHADCtab[6])+cap.ca) | TXD_MSK; */ #else LDIZ PinRLRHADCtab+3; /* LoADC = pgm_read_byte((&PinRLRHADCtab[3])+cap.ca) | TXD_MSK; */ #endif add r30, SelectLowPin; adc r31, zero_reg; lpm r24, Z+; ori r24, TXD_MSK; std Y+LoADC, r24; #if (((PIN_RL1 + 1) != PIN_RH1) || ((PIN_RL2 + 1) != PIN_RH2) || ((PIN_RL3 + 1) != PIN_RH3)) LDIZ PinRLRHADCtab+6; /* HiADC = pgm_read_byte((&PinRLRHADCtab[6])+cap.cb) | TXD_MSK; */ #else LDIZ PinRLRHADCtab+3; /* HiADC = pgm_read_byte((&PinRLRHADCtab[3])+cap.cb) | TXD_MSK; */ #endif add r30, SelectHighPin; adc r31, zero_reg; lpm r24, Z+; ori r24, TXD_MSK; std Y+HiADC, r24; LDIZ PinRLRHADCtab; /* LoPinR_L = pgm_read_byte(&PinRLRHADCtab[cap.ca]); //R_L mask for LowPin R_L load */ add r30, SelectLowPin; adc r31, zero_reg; lpm LoPinR_L, Z+; LDIZ PinRLRHADCtab; /* HiPinR_L = pgm_read_byte(&PinRLRHADCtab[cap.cb]); //R_L mask for HighPin R_L load */ add r30, SelectHighPin; adc r31, zero_reg; lpm HiPinR_L, Z+; #if (PROCESSOR_TYP == 640) || (PROCESSOR_TYP == 1280) /* ATmega640/1280/2560 1.1V Reference with REFS0=0 */ // SelectLowPin = (cap.ca | (1<<REFS1) | (0<<REFS0)); // switch ADC to LowPin, Internal Ref. ldi r25, (1<<REFS1)|(0<<REFS0); 0x80 or SelectLowPin, r25; // SelectHighPin = (cap.cb | (1<<REFS1) | (0<<REFS0)); // switch ADC to HighPin, Internal Ref. or SelectHighPin, r25; #else // SelectLowPin = (cap.ca | (1<<REFS1) | (1<<REFS0)); // switch ADC to LowPin, Internal Ref. ldi r25, (1<<REFS1)|(1<<REFS0); 0xC0 or SelectLowPin, r25; // SelectHighPin = (cap.cb | (1<<REFS1) | (1<<REFS0)); // switch ADC to HighPin, Internal Ref. or SelectHighPin, r25; #endif // Measurement of ESR of capacitors AC Mode ldi r24, 0x01; /* sumvolt0 = 1; // set sum of LowPin voltage to 1 to prevent divide by zero */ mov r14, r24; mov r15, zero_reg; mov r16, zero_reg; mov r17, zero_reg; std Y+sumvolt1, r24; /* sumvolt1 = 1; // clear sum of HighPin voltage with current */ // // offset is about (x*10*200)/34000 in 0.01 Ohm units std Y+sumvolt1+1, zero_reg; std Y+sumvolt1+2, zero_reg; std Y+sumvolt1+3, zero_reg; std Y+sumvolt2, zero_reg; /* sumvolt2 = 0; // clear sum of HighPin voltage without current */ std Y+sumvolt2+1, zero_reg; std Y+sumvolt2+2, zero_reg; std Y+sumvolt2+3, zero_reg; std Y+LowUpCount, zero_reg; std Y+HighUpCount, zero_reg; std Y+HighTooHigh, zero_reg; std Y+LowTooHigh, zero_reg; call EntladePins; /* EntladePins(); // discharge capacitor */ ldi r24, TXD_VAL; AOUT ADC_PORT, r24; /* ADC_PORT = TXD_VAL; // switch ADC-Port to GND */ sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; // set Mux input and Voltage Reference to internal 1.1V */ #ifdef NO_AREF_CAP call wait100us; /* time for voltage stabilization */ #else call wait10ms; /* time for voltage stabilization with 100nF */ #endif /* start voltage should be negativ */ ldd r19, Y+HiADC; /* ADC_DDR = HiADC; // switch High Pin to GND */ AOUT ADC_DDR, r19; /* switch High Pin to GND */ AOUT R_PORT, LoPinR_L /* r7 */ AOUT R_DDR, LoPinR_L /* r7 */ ldi r21, (HALF_PULSE_LENGTH_TICS/3) plop1: dec r21 brne plop1 #if (HALF_PULSE_LENGTH_TICS % 3) > 1 nop #endif #if (HALF_PULSE_LENGTH_TICS % 3) > 0 nop #endif AOUT R_DDR, zero_reg; /* R_DDR = 0 */ AOUT R_PORT, zero_reg; /* R_PORT = 0 */ // Measurement frequency is given by sum of ADC-Reads < 1116 Hz for normal ADC speed. // ADC Sample and Hold (SH) is done 1.5 ADC clock number after real start of conversion. // Real ADC-conversion is started with the next ADC-Clock (125kHz) after setting the ADSC bit. eor r13, r13; /* for(ii=0;ii<MAX_CNT;ii++) { */ // when time is too short, voltage is down before SH of ADC // when time is too long, capacitor will be overloaded. // That will cause too high voltage without current. // adcv[0] = ADCW; // Voltage LowPin with current // ADMUX = SelectHighPin; /* ********* Forward direction, connect Low side with GND *********** */ esr_loop: ldd r19, Y+LoADC; AOUT ADC_DDR, r19; /* ADC_DDR = LoADC; // switch Low-Pin to output (GND) */ AOUT R_PORT, LoPinR_L; /* R_PORT = LoPinR_L (r7) */ AOUT R_DDR, LoPinR_L; /* R_DDR = LoPinR_L (r7) */ sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; */ wdr ; /* wdt_reset(); */ ;=#= StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds adcv0L, ADCW; /* adcv[0] = ADCW; // Voltage LowPin reference */ lds adcv0H, ADCW+1; sts ADMUX, SelectHighPin; /* ADMUX = SelectHighPin; */ mov r20, HiPinR_L rcall strtADC_pulse ; start ADC, generate pulse and wait lds r18, ADCW; /* adcv[1] = ADCW; // Voltage HighPin with current */ lds r19, ADCW+1; #ifdef ADC_Sleep_Mode sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #endif ;======= std Y+adcvv1, r18; std Y+adcvv1+1, r19; /* ********* Reverse direction, connect High side with GND *********** */ ldd r19, Y+HiADC; /* ADC_DDR = HiADC; // switch High Pin to GND */ AOUT ADC_DDR, r19; /* ADC_DDR = HiADC; // switch High-Pin to output (GND) */ AOUT R_PORT, HiPinR_L; /* R_PORT = HiPinR_L (r12); // switch R-Port to VCC */ AOUT R_DDR, HiPinR_L; /* R_DDR = HiPinR_L (r12); // switch R_L port for HighPin to output (VCC) */ wdr ; /* wdt_reset(); */ sts ADMUX, SelectHighPin; /* ADMUX = SelectHighPin; */ ;=#= StartADCwait /* start ADC and wait */ StartADCwait /* start ADC and wait */ lds r22, ADCW; /* adcv[2] = ADCW; // Reverse Reference Voltage HighPin */ lds r23, ADCW+1; sts ADMUX, SelectLowPin; /* ADMUX = SelectLowPin; */ // ****** Polling mode big cap mov r20, LoPinR_L rcall strtADC_pulse ; start ADC, generate pulse and wait lds r20, ADCW; /* adcv[3] = ADCW; // Voltage LowPin with current */ lds r21, ADCW+1; #ifdef ADC_Sleep_Mode sts ADCSRA, StartADCmsk; /* ADCSRA = StartADCmsk; // enable ADC and Interrupt */ #endif AOUT R_DDR, zero_reg; /* R_DDR = 0; // switch current off */ movw r24, r22; /* adcv[2] */ add r24, adcv0L; /* adcv[0] + adcv[2] // add sum of both LowPin voltages with current */ adc r25, adcv0H; add r14, r24; /* r14:17 = sumvolt0 += (adcv[0] + adcv[2]); */ adc r15, r25; adc r16, zero_reg; adc r17, zero_reg; std Y+sumvolt0, r14; std Y+sumvolt0+1, r15; std Y+sumvolt0+2, r16; std Y+sumvolt0+3, r17; ldd r24, Y+adcvv1; /* add HighPin voltages with current */ ldd r25, Y+adcvv1+1; add r24, r20; /* adcv[1] + adcv[3] */ adc r25, r21; ldd r18, Y+sumvolt1; /* sumvolt1 += (adcv[1] + adcv[3]); */ ldd r19, Y+sumvolt1+1; ldd r22, Y+sumvolt1+2; ldd r23, Y+sumvolt1+3; add r18, r24; adc r19, r25; adc r22, zero_reg; adc r23, zero_reg; std Y+sumvolt1, r18; std Y+sumvolt1+1, r19; std Y+sumvolt1+2, r22; std Y+sumvolt1+3, r23; /*===================================================================================================*/ /* Range Check for voltages */ /* Y+adcvv1 is still the voltage of forward direction, r20:21 the voltage of reverse direction */ ldi r18, lo8(50); cp r18, r20; cpc zero_reg, r21; brcs is_ok1; /* r20:21 >= 50 */ AOUT R_PORT, LoPinR_L; /* R_PORT = LoPinR_L (r7); */ AOUT R_DDR, LoPinR_L; /* R_DDR = LoPinR_L (r7); // switch LowPin with 680 Ohm to VCC */ call wait1us; /* additional charge the capacitor */ AOUT R_DDR, zero_reg; // switch current off AOUT R_PORT, zero_reg; ldd r24, Y+LowUpCount; /* count additional load pulses at Low side */ inc r24; std Y+LowUpCount, r24; rjmp is_ok1b; is_ok1: cpi r20, lo8(1000); ldi r23, hi8(1000); cpc r21, r23; brcs is_ok1b; /* voltage reverse direction < 1000 */ ldd r24, Y+LowTooHigh; /* count pulses with too high voltage at Low side */ inc r24; std Y+LowTooHigh, r24; is_ok1b: ldd r24, Y+adcvv1; ldd r25, Y+adcvv1+1; cp r18, r24; cpc zero_reg, r25; /* adcvv1 >= 50 */ brcs is_ok2; ldd r19, Y+LoADC; AOUT ADC_DDR, r19; /* ADC_DDR = LoADC; // switch Low-Pin to output (GND) */ AOUT R_PORT, HiPinR_L; /* R_PORT = HiPinR_L (r12); // switch R-Port to VCC */ AOUT R_DDR, HiPinR_L; /* R_DDR = HiPinR_L (r12); // switch R_L port for HighPin to output (VCC) */ call wait1us; /* additional charge the capacitor */ ;## DelayBigCap; /* wait the time defined by macro */ AOUT R_DDR, zero_reg; /* R_DDR = 0; // switch current off, SH is 1.5 ADC clock behind real start */ AOUT R_PORT, zero_reg; /* R_PORT = 0; */ ldd r24, Y+HighUpCount; /* count additional load pulses at High side */ inc r24; std Y+HighUpCount, r24; rjmp is_ok2b; is_ok2: cpi r24, lo8(1000); ldi r23, hi8(1000); cpc r25, r23; brcs is_ok2b; /* voltage forward direction < 1000 */ ldd r24, Y+HighTooHigh; /* count pulses with too high voltage at High side */ inc r24; std Y+HighTooHigh, r24; is_ok2b: /*===================================================================================================*/ inc r13; /* for( ;ii<MAX_CNT;ii++) */ mov r21, r13; cpi r21, MAX_CNT; breq ad_38ac; #if FLASHEND > 0x3fff /* use additional 470k only with processors with more than 16k */ cpi r21, MAX_CNT/2; brne jesr_loop ; activate also the 470k resistors for half of samples #if (((PIN_RL1 + 1) != PIN_RH1) || ((PIN_RL2 + 1) != PIN_RH2) || ((PIN_RL3 + 1) != PIN_RH3)) LDIZ PinRLRHADCtab+3; /* HiPinR_H = pgm_read_byte(&PinRLRHADCtab[cap.cb+3]); //R_H mask for HighPin R_H load */ mov r21, SelectHighPin; andi r21, 0x03 add r30, r21; adc r31, zero_reg; lpm r21, Z+; add HiPinR_L, r21 ; enable also the 470k resistor LDIZ PinRLRHADCtab+3; /* LoPinR_H = pgm_read_byte(&PinRLRHADCtab[cap.ca+3]); //R_H mask for LowPin R_H load */ mov r21, SelectLowPin; andi r21, 0x03 add r30, r21; adc r31, zero_reg; lpm r21, Z+; add LoPinR_L, r21 ; enable also the 470k resistor #else mov r21, HiPinR_L add r21, r21 ; quick and dirty: usually is double HiPinR_H add HiPinR_L, r21 mov r21, LoPinR_L add r21, r21 ; quick and dirty: usually is double LoPinR_H add LoPinR_L, r21 #endif jesr_loop: #endif rjmp esr_loop; /* } // end for */ ad_38ac: #if RRpinMI == PIN_RM ldi r18, lo8(PIN_RM*10); ldi r19, hi8(PIN_RM*10); #else lds r4, RRpinMI; /* pin_rmi */ lds r5, RRpinMI+1; add r4, r4; RRpinMI*2 adc r5, r5; movw r18, r4; ldi r30, 4; ad_2r: add r18, r4; + 4*(2*RRpinMI) adc r19, r5; dec r30; brne ad_2r; add next (2*RRpinMI) #endif movw r4, r18; /* r4:5 = 10 * RRpinMI */ movw r10, r14; /* r10:13 = r14:17 = sumvolt0 */ movw r12, r16; ldd r6, Y+sumvolt1; ldd r7, Y+sumvolt1+1; ldd r8, Y+sumvolt1+2; ldd r9, Y+sumvolt1+3; /* ############################################################ */ lds r18, PartFound; /* if (PartFound == PART_CAPACITOR) { */ cpi r18, PART_CAPACITOR; brne no_sub; /* it is not a capacitor */ ; rjmp no_sub; /* ############## for debug */ /* First half of load pulse (13.5us) loads quicker than the second half of load pulse. */ /* Aproximation of 5000*(1 - exp(13.5e-6/(cap_val_nF*1.e-9*(0.1*(PIN_RM+PIN_RP+R_L_VAL)))) - 2500*(1 - exp(-27e-6/(cap_val_nF*1.e-9*(0.1*(PIN_RM+PIN_RP+R_L_VAL))))) */ /* is done by ((6744116/(PIN_RM+PIN_RP+R_L_VAL))*(6744116/(PIN_RM+PIN_RP+R_L_VAL))) / (cap_val_nF * (cap_val_nF + (137180/(PIN_RM+PIN_RP+R_L_VAL)))) */ /* is done by 872520 / (cap_val_nF * (cap_val_nF + 19)) */ ; #define FAKTOR_ESR (9537620/(PIN_RM+PIN_RP+R_L_VAL)) ldd r22, Y+cap_val_nF; /* sumvolt1 -= (1745098UL*MAX_CNT) / (cap_val_nF * (cap_val_nF + 19)); */ ldd r23, Y+cap_val_nF+1; ; ldd r24, Y+cap_val_nF+2; mov r24, r1 /* upper bits of cap_val_nF are allway zero */ ; ldd r25, Y+cap_val_nF+3; mov r25, r1 /* upper bits of cap_val_nF are allway zero */ ;#define FAKTOR_ESR (580000/(PIN_RM+PIN_RP+R_L_VAL)) /* 80 */ ;#define CAP_OFFSET (32000/(PIN_RM+PIN_RP+R_L_VAL)) /* 4 nF */ #if PROCESSOR_TYP == 644 #define FAKTOR_ESR (30250/(PIN_RM+PIN_RP+R_L_VAL)) /* 4 */ #else #define FAKTOR_ESR (550000/(PIN_RM+PIN_RP+R_L_VAL)) /* 76 */ #endif #define CAP_OFFSET (38000/(PIN_RM+PIN_RP+R_L_VAL)) /* 5 nF */ #if F_CPU == 16000000UL ;#define FAKTOR_ESR (920000/(PIN_RM+PIN_RP+R_L_VAL)) /* 127 */ ;#define CAP_OFFSET (410400/(PIN_RM+PIN_RP+R_L_VAL)) /* 57 nF */ ;#define FAKTOR_ESR (780000/(PIN_RM+PIN_RP+R_L_VAL)) /* 127 */ #else ;#define FAKTOR_ESR (920000/(PIN_RM+PIN_RP+R_L_VAL)) /* 127 */ ;#define CAP_OFFSET (433200/(PIN_RM+PIN_RP+R_L_VAL)) /* 60 nF */ #endif subi r22, lo8(CAP_OFFSET); 0xED; 237 sbci r23, hi8(CAP_OFFSET); 0xFF; 255 sbci r24, hlo8(CAP_OFFSET); 0xFF; 255 sbci r25, hhi8(CAP_OFFSET); 0xFF; 255 movw r18, r22; /* r18:21 = r22:25 = (cap_val_nF-60); */ movw r20, r24; call __mulsi3; /* (cap_val_nF - 60) * (cap_val_nF - 60) */ movw r18, r22; movw r20, r24; ldi r22, lo8(FAKTOR_ESR*FAKTOR_ESR*MAX_CNT); 0x36; 54 ldi r23, hi8(FAKTOR_ESR*FAKTOR_ESR*MAX_CNT); 0x29; 41 ldi r24, hlo8(FAKTOR_ESR*FAKTOR_ESR*MAX_CNT); 0x86; 134 ldi r25, hhi8(FAKTOR_ESR*FAKTOR_ESR*MAX_CNT); 0x1A; 26 call __udivmodsi4; sub r6, r18 sbc r7, r19 sbc r8, r20 sbc r9, r21 no_sub: /* } */ /* ############################################################ */ cp r10, r6; /* if (sumvolt1 > sumvolt0) { */ cpc r11, r7; cpc r12, r8; cpc r13, r9; brcc ad_396c; sub r6, r10; /* sumvolt1 -= sumvolt0; // difference HighPin - LowPin Voltage with current */ sbc r7, r11; sbc r8, r12; sbc r9, r13; rjmp ad_3972; /* } else { */ ad_396c: eor r6, r6; /* sumvolt1 = 0; */ eor r7, r7 movw r8, r6 ad_3972: #ifdef ESR_DEBUG movw r22, r6; /* DisplayValue(sumvolt1,0,'d',4); */ movw r24, r8 ldi r20, 0; ldi r18, 'd'; ldi r16, 4 ; call DisplayValue; call lcd_line3; ldd r24, Y+LowUpCount; ldi r25, 0; ldi r22, 0; ldi r20, '<'; ldi r18, 4 ; call DisplayValue16; ldd r24, Y+HighUpCount; ldi r25, 0; ldi r22, 0; ldi r20, '>'; ldi r18, 4 ; call DisplayValue16; ldd r24, Y+LowTooHigh; ldi r25, 0; ldi r22, 0; ldi r20, '+'; ldi r18, 4 ; call DisplayValue16; ldd r24, Y+HighTooHigh; ldi r25, 0; ldi r22, 0; ldi r20, '#'; ldi r18, 4 ; call DisplayValue16; call wait2s #endif movw r22, r4 ldi r24, 0x00; ldi r25, 0x00; /* r22:25 = 10 * (unsigned long)RRpinMI) */ /* jj = 0; */ // mean voltage at the capacitor is higher with current // sumvolt0 is the sum of voltages at LowPin, caused by output resistance of Port // RRpinMI is the port output resistance in 0.1 Ohm units. // we scale up the difference voltage with 10 to get 0.01 Ohm units of ESR /* esrvalue = (sumvolt1 * 10 * (unsigned long)RRpinMI) / sumvolt0; */ movw r18, r6; /* r18:21 = r6:9 = sumvolt1 */ movw r20, r8; call __mulsi3; /* r22:25 = r22:25 * r18:21 */ movw r18, r10; /* r18:21 = r10:13 = sumvolt0 */ movw r20, r12; call __udivmodsi4; /* r18:21 = r22:25 / r18:21 */ ldi r24, lo8(EE_ESR_ZEROtab); /* esr0 = (int8_t)eeprom_read_byte(&EE_ESR_ZEROtab[lopin+hipin]); */ ldi r25, hi8(EE_ESR_ZEROtab); ldd r23, Y+1; add r24, r23; adc r25, zero_reg; call eeprom_read_byte; mov r6, r24; movw r24,r18; /* r24:25 = r18:19 = esrvalue */ ldi r22, 16; ldi r23, 0; call __udivmodhi4 /* r22:23 = r24:25 / r22:23 */ add r18, r22; /* esrvalue += esrvalue / 16; */ adc r19, r23; movw r24,r18; /* esrvalue */ cp r6, r24; /* if (esrvalue > esr0) esrvalue -= esr0; */ cpc zero_reg, r25; brcc esr_too_less; sub r24, r6; /* - esr0 */ sbc r25, zero_reg; rjmp ad_exit; esr_too_less: #ifdef AUTO_CAL subi r24, lo8(-R_LIMIT_TO_UNCALIBRATED); /* + 0.20 Ohm */ sbci r25, hi8(-R_LIMIT_TO_UNCALIBRATED); /* esrvalue + 20 */ cp r24, r6; /* if ((esrvalue+20) < esr0) ; */ cpc r25, zero_reg; brcc esr_too_less2; ldd r24, Y+cap_val_nF; /* mark only, if cap_val_nF > 4500 */ ldd r25, Y+cap_val_nF+1; ; ldd r26, Y+cap_val_nF+2; /* the upper bits (cap_val_nF+2|3) are always zero */ cpi r24, lo8(4500); ldi r24, hi8(4500); cpc r25, r24; brcs esr_too_less2; call mark_as_uncalibrated; /* ldi r24,'<'; */ /* call lcd_data; */ esr_too_less2: #endif mov r24, zero_reg; mov r25, zero_reg; ad_exit: #ifdef ADC_Sleep_Mode out _SFR_IO_ADDR(SMCR), zero_reg; /* SMCR = 0 */ #endif #ifdef WITHOUT_PROLOGUE adiw r28, 30 ; in r0, _SFR_IO_ADDR(SREG); 63 cli out _SFR_IO_ADDR(SPH), r29; 62 out _SFR_IO_ADDR(SREG), r0; 63 out _SFR_IO_ADDR(SPL), r28; 61 pop r28; pop r29; pop r17; pop r16; pop r15; pop r14; pop r13; pop r12; pop r11; pop r10; pop r9; pop r8; pop r7; pop r6; pop r5; pop r4; pop r3; pop r2; ret; #else adiw r28, 30 ldi r30, 18 jmp __epilogue_restores__ #endif ; ##################################################################################### ; Start ADC and generate a Pulse around the sample and hold time, ; then wait for end of conversion and return. ; ##################################################################################### /* ************************************************************************************ */ /* Adjust the timing for switch off the load current for big capacitors */ /* ************************************************************************************ */ // With wdt_reset the timing can be fine adjusted. // The middle of current pulse should be at the SH time of ADC. // SH time of next ADC cycle is 20 us after last ADC ready. // The timing of the middle of the load pulse is critical // for capacitors with low capacity value (100 nF). // For resistors or capacitors with big capacity value the // voltage is constant or nearly constant. // For this reason the timing is extremly critical for // capacitors with low capacity value. // Charging of capacitor begins with negative voltage and // should be zero at SH time with a zero ESR capacitor. #if R_PORT < 0x40 #define OUT_DELAY 2 /* two AOUT take 2 tics (out instruction) */ #else #define OUT_DELAY 4 /* two AOUT take 4 tics (sts instruction) */ #endif ; #define WITHOUT_CNT_START strtADC_pulse: #ifdef WITHOUT_CNT_START StartADCwait /* start ADC and wait */ // Start Conversion, real start is next rising edge of ADC clock ldi r21, (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable ADC and start with ADSC */ sts ADCSRA, r21; /* ADCSRA = (1<<ADSC) | (1<<ADEN) | (1<<ADIF) | AUTO_CLOCK_DIV; // enable ADC and start */ #ifdef ADC_Sleep_Mode /* Wake up from sleep with Interrupt: 1+4+4T, jmp, rti, ldi, out takes 18 clock tics, */ #define PIN_HIGH_DELAY (9+2+4+OUT_DELAY + 5 + 3 + (F_CPU_HZ/4000000)) #else /* Polling mode: delay to pin high: lds,sbrc,sts and out Instructions are 7 clock tics */ #define PIN_HIGH_DELAY (6+OUT_DELAY + 3 + (F_CPU_HZ/4000000)) #endif #define WAST_TICS (((TICS_PER_ADC_CLOCK*5)/2) - HALF_PULSE_LENGTH_TICS - PIN_HIGH_DELAY) #else sts TCCR1B, r1 ; stop counter1 sts TCCR1A, r1 ; TCCR1A = 0 , normal port operation sts TIMSK1, r1 ; disable all timer1 interrupts sts OCR1BH, r1 ; OCR!B = 0 sts OCR1BL, r1 ldi r21, (1<<OCF1B) | (1<<OCF1A) | (1<<TOV1) AOUT TIFR1, r21 ; clear flags ldi r21, 0xff sts TCNT1H, r21 ; TCNT1 = -1 sts TCNT1L, r21 ldi r21, (1<<ADTS2) | (1<<ADTS0) ; Start ADC with counter1 compare B sts ADCSRB, r21 ldi r21, (1<<ADEN) | (1<<ADATE) | (1<<ADIF) | AUTO_CLOCK_DIV; /* enable ADC */ sts ADCSRA, r21; /* ADCSRA = (1<<ADEN) | (1<<ADSC) | (1<<ADIF) | AUTO_CLOCK_DIV; // enable ADC */ ldi r21, (1<<CS10) sts TCCR1B, r21 ; Start Counter 1 with full speed #define PIN_HIGH_DELAY (OUT_DELAY - 5 + (F_CPU_HZ/4000000)) #define WAST_TICS ((TICS_PER_ADC_CLOCK*2) - HALF_PULSE_LENGTH_TICS - PIN_HIGH_DELAY) #endif ; additional delay to the start of current pulse ldi r21, (WAST_TICS/3) wlop1: dec r21 brne wlop1 #if (WAST_TICS % 3) > 1 nop #endif #if (WAST_TICS % 3) > 0 nop #endif AOUT R_PORT, r20; /* R_PORT = HiPinR_L (r12); // switch R-Port to VCC */ AOUT R_DDR, r20; /* R_DDR = HiPinR_L (r12); // switch R_L port for HighPin to output (VCC) */ ; AOUT R_PORT, LoPinR_L; /* R_PORT = LoPinR_L (r7) ; */ ; AOUT R_DDR, LoPinR_L; /* R_DDR = LoPinR_L (r7) ; // switch LowPin with 680 Ohm to VCC */ #define FULL_PULSE_LENGTH_TICS ((HALF_PULSE_LENGTH_TICS*2)+(MHZ_CPU/14)) ldi r21, (FULL_PULSE_LENGTH_TICS/3) plop2: dec r21 brne plop2 #if (FULL_PULSE_LENGTH_TICS % 3) > 1 nop #endif #if (FULL_PULSE_LENGTH_TICS % 3) > 0 nop #endif AOUT R_DDR, zero_reg; /* R_DDR = 0; // switch current off, SH is 1.5 ADC clock behind real start */ AOUT R_PORT, zero_reg; /* R_PORT = 0; */ #ifndef WITHOUT_CNT_START sts TCCR1B, r1 ; stop counter1 #endif wadfin2: lds r24, ADCSRA; /* while (ADCSRA&(1<<ADSC)); // wait for conversion finished */ sbrs r24, ADIF; rjmp wadfin2; sts ADCSRA, r24 ; clear flags ret .endfunc
wagiminator/ATmega-Transistor-Tester
2,153
software/sources/RvalOut.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include <avr/eeprom.h> #include <stdlib.h> #include "config.h" #include "part_defs.h" /* #include <avr/io.h> */ /* #include <avr/eeprom.h> */ /* #include <avr/pgmspace.h> */ /* #include "Transistortester.h" */ /* void RvalOut(uint8_t nrr) { */ /* // output of resistor value */ /* #if FLASHEND > 0x1fff */ /* uint16_t rr; */ /* if ((resis[nrr].rx < 100) && (inductor_lpre == 0)) { */ /* rr = GetESR(resis[nrr].ra,resis[nrr].rb); */ /* DisplayValue(rr,-2,LCD_CHAR_OMEGA,3); */ /* } else { */ /* DisplayValue(resis[nrr].rx,-1,LCD_CHAR_OMEGA,4); */ /* } */ /* #else */ /* DisplayValue(resis[nrr].rx,-1,LCD_CHAR_OMEGA,4); */ /* #endif */ /* lcd_space(); */ /* } */ #define zero_reg r1 #define RCALL rcall .GLOBAL RvalOut .func RvalOut .extern DisplayValue .extern GetESR .extern lcd_space .extern ResistorVal .section .text RvalOut: ; void RvalOut(uint8_t nrr) push r16 mov r16, r24 LDIZ ResistorVal add r24, r24 ; nrr*2 add r24, r24 ; nrr*4 add r30, r24 adc r31, zero_reg ld r22, Z ; resis[rr].rx ldd r23, Z+1 ; 0x01 ldd r24, Z+2 ; 0x02 ldd r25, Z+3 ; 0x03 #if FLASHEND > 0x1fff cpi r22, 0x64 ; 100 cpc r23, r1 cpc r24, r1 cpc r25, r1 brcc ad1d8e ; (ResistorVal[nrr] < 100) lds r18, inductor_lpre sbrc r18, 7 ; minus bit set? rjmp ad1d8e ; (inductor_lpre >= 0) mov r24,r16 ACALL Rnum2pins; ; pins = Rnum2pins(nrr) mov r22, r25 ACALL GetESR ; rr = GetESR(resis[nrr].ra,resis[nrr].rb); ; movw r22, r24 ; ldi r24, 0 ; ldi r25, 0 ; ldi r20, -2 ; 254 ; ldi r16, 0x03 ; 3 ; rjmp ad1d94 ; DisplayValue(rr,-2,LCD_CHAR_OMEGA,3); ldi r22, -2 ldi r18, 3 ldi r20, LCD_CHAR_OMEGA RCALL DisplayValue16 ; DisplayValue16(rr,-2,LCD_OMEGA,3); rjmp ret_with_space ad1d8e: ; } else { #endif ; r22-r25 = ResistorVal[rr] ldi r20, -1 ; 255 ldi r16, 0x04 ; DisplayValue(resis[nrr].rx,-1,LCD_CHAR_OMEGA,4); ;ad1d94: ldi r18, LCD_CHAR_OMEGA ; 244 RCALL DisplayValue ret_with_space: RCALL lcd_space ; lcd_space(); pop r16 ret .endfunc
wagiminator/ATmega-Transistor-Tester
2,937
software/sources/sleep_5ms.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include <avr/common.h> #include "config.h" #include <stdlib.h> #define RCALL rcall .GLOBAL sleep_5ms .func sleep_5ms .extern wait5ms .section .text #define DELAY_10ms (((F_CPU_HZ / 100) - RESTART_DELAY_TICS) / TICS_PER_T2_COUNT) #define DELAY_5ms (((F_CPU_HZ / 200) - RESTART_DELAY_TICS) / TICS_PER_T2_COUNT) ;/* set the processor to sleep state */ ;/* wake up will be done with compare match interrupt of counter 2 */ ; void sleep_5ms(uint8_t spause){ sleep_5ms: ldi r25, 0x00 ; pause = spause; cpi r24, 201 brcs wloop ; if (spause > 200) ;// spause = 202 = 2s ;// spause = 203 = 3s ;// spause = 204 = 4s ;// spause = 205 = 5s subi r24, 0xC8 ; 200 pause = (spause-200) * 200; ldi r20, 0xC8 ; 200 mul r24, r20 ; (spause-200) * 200 movw r24, r0 ; r24:25 = (spause-200) * 200 eor r1, r1 wloop: sbiw r24, 0x00 ; 0 while (pause > 0) brne check_remain ; sts TIMSK2, r1 ; TIMSK2 = (0<<OCIE2B) | (0<<OCIE2A) | (0<<TOIE2); /* disable output compare match A interrupt */ ;#endif ret check_remain: #if (F_CPU_HZ / 400) > RESTART_DELAY_TICS lds r18, TCCR1B ; if (TCCR1B & ((1<<CS12)|(1<<CS11)|(1<<CS10)) != 0) andi r18, ((1<<CS12)|(1<<CS11)|(1<<CS10)) ; breq do_sleep ; timer 1 is running, don't use sleep RCALL wait5ms ; wait5ms(); sbiw r24, 1 ; pause -= 1; rjmp wloop do_sleep: cpi r24, 0x01 ; 1 cpc r25, r1 breq only_one ; if (pause > 1) sbiw r24, 0x02 ; pause -= 2; ; // Startup time is too long with 1MHz Clock!!!! ldi r19, DELAY_10ms ; /* set to 10ms above the actual counter */ rjmp set_cntr only_one: ldi r19, DELAY_5ms ; /* set to 5ms above the actual counter */ ldi r24, 0x00 ; pause = 0; ldi r25, 0x00 ; 0 set_cntr: lds r18, TCNT2 add r18, r19 ; + t2_offset sts OCR2A, r18 ; OCR2A = TCNT2 + t2_offset; /* set the compare value */ ldi r20, ((0<<OCIE2B) | (1<<OCIE2A) | (0<<TOIE2)); /* enable output compare match A interrupt */ sts TIMSK2, r20 ; TIMSK2 = (0<<OCIE2B) | (1<<OCIE2A) | (0<<TOIE2); /* enable output compare match A interrupt */ ;; ldi r18, (1 << SM1) | (1 << SM0) | (0 << SE); set_sleep_mode(SLEEP_MODE_PWR_SAVE) ;; out _SFR_IO_ADDR(SMCR), r18; /* SMCR = (1 <<SM1) | (1 << SM0) | (0 << SE); */ ldi r18, (1 << SM1) | (1 << SM0) | (1 << SE); out _SFR_IO_ADDR(SMCR), r18; /* SMCR = (1 <<SM1) | (1 << SM0) | (1 << SE); */ sleep ; ; // wake up after output compare match interrupt ldi r18, (1 << SM1) | (1 << SM0) | (0 << SE); out _SFR_IO_ADDR(SMCR), r18; /* SMCR = (1 << SM0) | (0 << SE); */ sts TIMSK2, r1 ; TIMSK2 = (0<<OCIE2B) | (0<<OCIE2A) | (0<<TOIE2); /* disable output compare match A interrupt */ wdr ; wdt_reset(); #else ; // restart delay ist too long, use normal delay of 5ms RCALL wait5ms ; wait5ms(); // wait5ms includes wdt_reset() sbiw r24, 1 ; pause -= 1; #endif rjmp wloop .endfunc
wagiminator/ATmega-Transistor-Tester
1,117
software/sources/CombineToLong.S
#ifndef __ASSEMBLER__ #define __ASSEMBLER__ #endif #include <avr/io.h> #include "config.h" #include <stdlib.h> .section .text .func CombineII2Long .global CombineBI2Long .global CombineII2Long // This tricky function replaces the long-winded way of gcc compiler // to build = high*65536 + low // if there is any way to shorten the gcc implementation, // this function can be omitted. ;//unsigned long CombineBI2Long(uint8_t high, unsigned int low) ; { CombineBI2Long: // r24 = high input (byte) // r22,r23 = low input // CombineToLong = (unsigned long)(((unsigned long)high * 65536) + low); //compute total // CombineToLong = r22-r25 clr r25 //in case of high is byte, clear upper byte // ret // because next function has nothing to do, use that return ;//unsigned long CombineII2Long(unsigned int high, unsigned int low) ; { CombineII2Long: // r24,r25 = high input // r22,r23 = low input // CombineToLong = (unsigned long)(((unsigned long)high * 65536) + low); //compute total // CombineToLong return value = r22-r25 // in case of high is unsigned int, nothing to do ret .endfunc
wagiminator/ATtiny85-TinyKnob
23,124
software/sources/usbdrv/usbdrvasm165.S
/* Name: usbdrvasm165.S * Project: AVR USB driver * Author: Christian Starkjohann * Creation Date: 2007-04-22 * Tabsize: 4 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt) * Revision: $Id$ */ /* Do not link this file! Link usbdrvasm.S instead, which includes the * appropriate implementation! */ /* General Description: This file is the 16.5 MHz version of the USB driver. It is intended for the ATTiny45 and similar controllers running on 16.5 MHz internal RC oscillator. This version contains a phase locked loop in the receiver routine to cope with slight clock rate deviations of up to +/- 1%. See usbdrv.h for a description of the entire driver. Since almost all of this code is timing critical, don't change unless you really know what you are doing! Many parts require not only a maximum number of CPU cycles, but even an exact number of cycles! */ ;Software-receiver engine. Strict timing! Don't change unless you can preserve timing! ;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled ;max allowable interrupt latency: 59 cycles -> max 52 cycles interrupt disable ;max stack usage: [ret(2), r0, SREG, YL, YH, shift, x1, x2, x3, x4, cnt] = 12 bytes ;nominal frequency: 16.5 MHz -> 11 cycles per bit ; 16.3125 MHz < F_CPU < 16.6875 MHz (+/- 1.1%) ; Numbers in brackets are clocks counted from center of last sync bit ; when instruction starts SIG_INTERRUPT0: ;order of registers pushed: r0, SREG [sofError], YL, YH, shift, x1, x2, x3, x4, cnt push r0 ;[-23] push only what is necessary to sync with edge ASAP in r0, SREG ;[-21] push r0 ;[-20] ;---------------------------------------------------------------------------- ; Synchronize with sync pattern: ;---------------------------------------------------------------------------- ;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] ;sync up with J to K edge during sync pattern -- use fastest possible loops ;first part has no timeout because it waits for IDLE or SE1 (== disconnected) waitForJ: sbis USBIN, USBMINUS ;[-18] wait for D- == 1 rjmp waitForJ waitForK: ;The following code results in a sampling window of < 1/4 bit which meets the spec. sbis USBIN, USBMINUS ;[-15] rjmp foundK ;[-14] sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK rjmp sofError foundK: ;[-12] ;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling] ;we have 1 bit time for setup purposes, then sample again. Numbers in brackets ;are cycles from center of first sync (double K) bit after the instruction push YL ;[-12] ; [---] ;[-11] push YH ;[-10] ; [---] ;[-9] lds YL, usbInputBufOffset;[-8] ; [---] ;[-7] clr YH ;[-6] subi YL, lo8(-(usbRxBuf));[-5] [rx loop init] sbci YH, hi8(-(usbRxBuf));[-4] [rx loop init] mov r0, x2 ;[-3] [rx loop init] sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early) rjmp haveTwoBitsK ;[-1] pop YH ;[0] undo the pushes from before pop YL ;[2] rjmp waitForK ;[4] this was not the end of sync, retry ; The entire loop from waitForK until rjmp waitForK above must not exceed two ; bit times (= 22 cycles). ;---------------------------------------------------------------------------- ; push more registers and initialize values while we sample the first bits: ;---------------------------------------------------------------------------- haveTwoBitsK: ;[1] push shift ;[1] push x1 ;[3] push x2 ;[5] push x3 ;[7] ldi shift, 0xff ;[9] [rx loop init] ori x3, 0xff ;[10] [rx loop init] == ser x3, clear zero flag in x1, USBIN ;[11] <-- sample bit 0 bst x1, USBMINUS ;[12] bld shift, 0 ;[13] push x4 ;[14] == phase ; [---] ;[15] push cnt ;[16] ; [---] ;[17] ldi phase, 0 ;[18] [rx loop init] ldi cnt, USB_BUFSIZE;[19] [rx loop init] rjmp rxbit1 ;[20] ; [---] ;[21] ;---------------------------------------------------------------------------- ; Receiver loop (numbers in brackets are cycles within byte after instr) ;---------------------------------------------------------------------------- /* byte oriented operations done during loop: bit 0: store data bit 1: SE0 check bit 2: overflow check bit 3: catch up bit 4: rjmp to achieve conditional jump range bit 5: PLL bit 6: catch up bit 7: jump, fixup bitstuff ; 87 [+ 2] cycles ------------------------------------------------------------------ */ continueWithBit5: in x2, USBIN ;[055] <-- bit 5 eor r0, x2 ;[056] or phase, r0 ;[057] sbrc phase, USBMINUS ;[058] lpm ;[059] optional nop3; modifies r0 in phase, USBIN ;[060] <-- phase eor x1, x2 ;[061] bst x1, USBMINUS ;[062] bld shift, 5 ;[063] andi shift, 0x3f ;[064] in x1, USBIN ;[065] <-- bit 6 breq unstuff5 ;[066] *** unstuff escape eor phase, x1 ;[067] eor x2, x1 ;[068] bst x2, USBMINUS ;[069] bld shift, 6 ;[070] didUnstuff6: ;[ ] in r0, USBIN ;[071] <-- phase cpi shift, 0x02 ;[072] brlo unstuff6 ;[073] *** unstuff escape didUnstuff5: ;[ ] nop2 ;[074] ; [---] ;[075] in x2, USBIN ;[076] <-- bit 7 eor x1, x2 ;[077] bst x1, USBMINUS ;[078] bld shift, 7 ;[079] didUnstuff7: ;[ ] eor r0, x2 ;[080] or phase, r0 ;[081] in r0, USBIN ;[082] <-- phase cpi shift, 0x04 ;[083] brsh rxLoop ;[084] ; [---] ;[085] unstuff7: ;[ ] andi x3, ~0x80 ;[085] ori shift, 0x80 ;[086] in x2, USBIN ;[087] <-- sample stuffed bit 7 nop ;[088] rjmp didUnstuff7 ;[089] ; [---] ;[090] ;[080] unstuff5: ;[067] eor phase, x1 ;[068] andi x3, ~0x20 ;[069] ori shift, 0x20 ;[070] in r0, USBIN ;[071] <-- phase mov x2, x1 ;[072] nop ;[073] nop2 ;[074] ; [---] ;[075] in x1, USBIN ;[076] <-- bit 6 eor r0, x1 ;[077] or phase, r0 ;[078] eor x2, x1 ;[079] bst x2, USBMINUS ;[080] bld shift, 6 ;[081] no need to check bitstuffing, we just had one in r0, USBIN ;[082] <-- phase rjmp didUnstuff5 ;[083] ; [---] ;[084] ;[074] unstuff6: ;[074] andi x3, ~0x40 ;[075] in x1, USBIN ;[076] <-- bit 6 again ori shift, 0x40 ;[077] nop2 ;[078] ; [---] ;[079] rjmp didUnstuff6 ;[080] ; [---] ;[081] ;[071] unstuff0: ;[013] eor r0, x2 ;[014] or phase, r0 ;[015] andi x2, USBMASK ;[016] check for SE0 in r0, USBIN ;[017] <-- phase breq didUnstuff0 ;[018] direct jump to se0 would be too long andi x3, ~0x01 ;[019] ori shift, 0x01 ;[020] mov x1, x2 ;[021] mov existing sample in x2, USBIN ;[022] <-- bit 1 again rjmp didUnstuff0 ;[023] ; [---] ;[024] ;[014] unstuff1: ;[024] eor r0, x1 ;[025] or phase, r0 ;[026] andi x3, ~0x02 ;[027] in r0, USBIN ;[028] <-- phase ori shift, 0x02 ;[029] mov x2, x1 ;[030] rjmp didUnstuff1 ;[031] ; [---] ;[032] ;[022] unstuff2: ;[035] eor r0, x2 ;[036] or phase, r0 ;[037] andi x3, ~0x04 ;[038] in r0, USBIN ;[039] <-- phase ori shift, 0x04 ;[040] mov x1, x2 ;[041] rjmp didUnstuff2 ;[042] ; [---] ;[043] ;[033] unstuff3: ;[043] in x2, USBIN ;[044] <-- bit 3 again eor r0, x2 ;[045] or phase, r0 ;[046] andi x3, ~0x08 ;[047] ori shift, 0x08 ;[048] nop ;[049] in r0, USBIN ;[050] <-- phase rjmp didUnstuff3 ;[051] ; [---] ;[052] ;[042] unstuff4: ;[053] andi x3, ~0x10 ;[054] in x1, USBIN ;[055] <-- bit 4 again ori shift, 0x10 ;[056] rjmp didUnstuff4 ;[057] ; [---] ;[058] ;[048] rxLoop: ;[085] eor x3, shift ;[086] reconstruct: x3 is 0 at bit locations we changed, 1 at others in x1, USBIN ;[000] <-- bit 0 st y+, x3 ;[001] ; [---] ;[002] eor r0, x1 ;[003] or phase, r0 ;[004] eor x2, x1 ;[005] in r0, USBIN ;[006] <-- phase ser x3 ;[007] bst x2, USBMINUS ;[008] bld shift, 0 ;[009] andi shift, 0xf9 ;[010] rxbit1: ;[ ] in x2, USBIN ;[011] <-- bit 1 breq unstuff0 ;[012] *** unstuff escape andi x2, USBMASK ;[013] SE0 check for bit 1 didUnstuff0: ;[ ] Z only set if we detected SE0 in bitstuff breq se0 ;[014] eor r0, x2 ;[015] or phase, r0 ;[016] in r0, USBIN ;[017] <-- phase eor x1, x2 ;[018] bst x1, USBMINUS ;[019] bld shift, 1 ;[020] andi shift, 0xf3 ;[021] didUnstuff1: ;[ ] in x1, USBIN ;[022] <-- bit 2 breq unstuff1 ;[023] *** unstuff escape eor r0, x1 ;[024] or phase, r0 ;[025] subi cnt, 1 ;[026] overflow check brcs overflow ;[027] in r0, USBIN ;[028] <-- phase eor x2, x1 ;[029] bst x2, USBMINUS ;[030] bld shift, 2 ;[031] andi shift, 0xe7 ;[032] didUnstuff2: ;[ ] in x2, USBIN ;[033] <-- bit 3 breq unstuff2 ;[034] *** unstuff escape eor r0, x2 ;[035] or phase, r0 ;[036] eor x1, x2 ;[037] bst x1, USBMINUS ;[038] in r0, USBIN ;[039] <-- phase bld shift, 3 ;[040] andi shift, 0xcf ;[041] didUnstuff3: ;[ ] breq unstuff3 ;[042] *** unstuff escape nop ;[043] in x1, USBIN ;[044] <-- bit 4 eor x2, x1 ;[045] bst x2, USBMINUS ;[046] bld shift, 4 ;[047] didUnstuff4: ;[ ] eor r0, x1 ;[048] or phase, r0 ;[049] in r0, USBIN ;[050] <-- phase andi shift, 0x9f ;[051] breq unstuff4 ;[052] *** unstuff escape rjmp continueWithBit5;[053] ; [---] ;[054] ;---------------------------------------------------------------------------- ; Processing of received packet (numbers in brackets are cycles after center of SE0) ;---------------------------------------------------------------------------- ;This is the only non-error exit point for the software receiver loop ;we don't check any CRCs here because there is no time left. #define token x1 se0: subi cnt, USB_BUFSIZE ;[5] neg cnt ;[6] cpi cnt, 3 ;[7] ldi x2, 1<<USB_INTR_PENDING_BIT ;[8] out USB_INTR_PENDING, x2;[9] clear pending intr and check flag later. SE0 should be over. brlo doReturn ;[10] this is probably an ACK, NAK or similar packet sub YL, cnt ;[11] sbci YH, 0 ;[12] ld token, y ;[13] cpi token, USBPID_DATA0 ;[15] breq handleData ;[16] cpi token, USBPID_DATA1 ;[17] breq handleData ;[18] ldd x2, y+1 ;[19] ADDR and 1 bit endpoint number mov x3, x2 ;[21] store for endpoint number andi x2, 0x7f ;[22] x2 is now ADDR lds shift, usbDeviceAddr;[23] cp x2, shift ;[25] overflow: ; This is a hack: brcs overflow will never have Z flag set brne ignorePacket ;[26] packet for different address cpi token, USBPID_IN ;[27] breq handleIn ;[28] cpi token, USBPID_SETUP ;[29] breq handleSetupOrOut ;[30] cpi token, USBPID_OUT ;[31] breq handleSetupOrOut ;[32] ; rjmp ignorePacket ;fallthrough, should not happen anyway. ignorePacket: clr shift sts usbCurrentTok, shift doReturn: pop cnt pop x4 pop x3 pop x2 pop x1 pop shift pop YH pop YL sofError: pop r0 out SREG, r0 pop r0 reti #if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_HAVE_INTRIN_ENDPOINT3 handleIn3: lds cnt, usbTxLen3 ;[43] sbrc cnt, 4 ;[45] rjmp sendCntAndReti ;[46] 48 + 16 = 64 until SOP sts usbTxLen3, x1 ;[47] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf3) ;[49] ldi YH, hi8(usbTxBuf3) ;[50] rjmp usbSendAndReti ;[51] 53 + 12 = 65 until SOP #endif ;Setup and Out are followed by a data packet two bit times (16 cycles) after ;the end of SE0. The sync code allows up to 40 cycles delay from the start of ;the sync pattern until the first bit is sampled. That's a total of 56 cycles. handleSetupOrOut: ;[34] #if USB_CFG_IMPLEMENT_FN_WRITEOUT /* if we have data for second OUT endpoint, set usbCurrentTok to -1 */ sbrc x3, 7 ;[34] skip if endpoint 0 ldi token, -1 ;[35] indicate that this is endpoint 1 OUT #endif sts usbCurrentTok, token;[36] pop cnt ;[38] pop x4 ;[40] pop x3 ;[42] pop x2 ;[44] pop x1 ;[46] pop shift ;[48] pop YH ;[50] pop YL ;[52] in r0, USB_INTR_PENDING;[54] sbrc r0, USB_INTR_PENDING_BIT;[55] check whether data is already arriving rjmp waitForJ ;[56] save the pops and pushes -- a new interrupt is aready pending rjmp sofError ;[57] not an error, but it does the pops and reti we want handleData: lds token, usbCurrentTok;[20] tst token ;[22] breq doReturn ;[23] lds x2, usbRxLen ;[24] tst x2 ;[26] brne sendNakAndReti ;[27] ; 2006-03-11: The following two lines fix a problem where the device was not ; recognized if usbPoll() was called less frequently than once every 4 ms. cpi cnt, 4 ;[28] zero sized data packets are status phase only -- ignore and ack brmi sendAckAndReti ;[29] keep rx buffer clean -- we must not NAK next SETUP sts usbRxLen, cnt ;[30] store received data, swap buffers sts usbRxToken, token ;[32] lds x2, usbInputBufOffset;[34] swap buffers ldi cnt, USB_BUFSIZE ;[36] sub cnt, x2 ;[37] sts usbInputBufOffset, cnt;[38] buffers now swapped rjmp sendAckAndReti ;[40] 42 + 17 = 59 until SOP handleIn: ;We don't send any data as long as the C code has not processed the current ;input data and potentially updated the output data. That's more efficient ;in terms of code size than clearing the tx buffers when a packet is received. lds x1, usbRxLen ;[30] cpi x1, 1 ;[32] negative values are flow control, 0 means "buffer free" brge sendNakAndReti ;[33] unprocessed input packet? ldi x1, USBPID_NAK ;[34] prepare value for usbTxLen #if USB_CFG_HAVE_INTRIN_ENDPOINT sbrc x3, 7 ;[35] x3 contains addr + endpoint rjmp handleIn1 ;[36] #endif lds cnt, usbTxLen ;[37] sbrc cnt, 4 ;[39] all handshake tokens have bit 4 set rjmp sendCntAndReti ;[40] 42 + 16 = 58 until SOP sts usbTxLen, x1 ;[41] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf) ;[43] ldi YH, hi8(usbTxBuf) ;[44] rjmp usbSendAndReti ;[45] 47 + 12 = 59 until SOP ; Comment about when to set usbTxLen to USBPID_NAK: ; We should set it back when we receive the ACK from the host. This would ; be simple to implement: One static variable which stores whether the last ; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the ; ACK. However, we set it back immediately when we send the package, ; assuming that no error occurs and the host sends an ACK. We save one byte ; RAM this way and avoid potential problems with endless retries. The rest of ; the driver assumes error-free transfers anyway. #if USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */ handleIn1: ;[38] #if USB_CFG_HAVE_INTRIN_ENDPOINT3 ; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint ldd x2, y+2 ;[38] sbrc x2, 0 ;[40] rjmp handleIn3 ;[41] #endif lds cnt, usbTxLen1 ;[42] sbrc cnt, 4 ;[44] all handshake tokens have bit 4 set rjmp sendCntAndReti ;[45] 47 + 16 = 63 until SOP sts usbTxLen1, x1 ;[46] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf1) ;[48] ldi YH, hi8(usbTxBuf1) ;[49] rjmp usbSendAndReti ;[50] 52 + 12 + 64 until SOP #endif ; USB spec says: ; idle = J ; J = (D+ = 0), (D- = 1) ; K = (D+ = 1), (D- = 0) ; Spec allows 7.5 bit times from EOP to SOP for replies bitstuff7: eor x1, x4 ;[4] ldi x2, 0 ;[5] nop2 ;[6] C is zero (brcc) rjmp didStuff7 ;[8] bitstuffN: eor x1, x4 ;[5] ldi x2, 0 ;[6] lpm ;[7] 3 cycle NOP, modifies r0 out USBOUT, x1 ;[10] <-- out rjmp didStuffN ;[0] #define bitStatus x3 sendNakAndReti: ldi cnt, USBPID_NAK ;[-19] rjmp sendCntAndReti ;[-18] sendAckAndReti: ldi cnt, USBPID_ACK ;[-17] sendCntAndReti: mov r0, cnt ;[-16] ldi YL, 0 ;[-15] R0 address is 0 ldi YH, 0 ;[-14] ldi cnt, 2 ;[-13] ; rjmp usbSendAndReti fallthrough ;usbSend: ;pointer to data in 'Y' ;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] ;uses: x1...x4, shift, cnt, Y ;Numbers in brackets are time since first bit of sync pattern is sent usbSendAndReti: ; 12 cycles until SOP in x2, USBDDR ;[-12] ori x2, USBMASK ;[-11] sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) in x1, USBOUT ;[-8] port mirror for tx loop out USBDDR, x2 ;[-7] <- acquire bus ; need not init x2 (bitstuff history) because sync starts with 0 ldi x4, USBMASK ;[-6] exor mask ldi shift, 0x80 ;[-5] sync byte is first byte sent ldi bitStatus, 0xff ;[-4] init bit loop counter, works for up to 12 bytes byteloop: bitloop: sbrs shift, 0 ;[8] [-3] eor x1, x4 ;[9] [-2] out USBOUT, x1 ;[10] [-1] <-- out ror shift ;[0] ror x2 ;[1] didStuffN: cpi x2, 0xfc ;[2] brcc bitstuffN ;[3] nop ;[4] subi bitStatus, 37 ;[5] 256 / 7 ~=~ 37 brcc bitloop ;[6] when we leave the loop, bitStatus has almost the initial value sbrs shift, 0 ;[7] eor x1, x4 ;[8] ror shift ;[9] didStuff7: out USBOUT, x1 ;[10] <-- out ror x2 ;[0] cpi x2, 0xfc ;[1] brcc bitstuff7 ;[2] ld shift, y+ ;[3] dec cnt ;[5] brne byteloop ;[6] ;make SE0: cbr x1, USBMASK ;[7] prepare SE0 [spec says EOP may be 21 to 25 cycles] lds x2, usbNewDeviceAddr;[8] out USBOUT, x1 ;[10] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle ;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: ;set address only after data packet was sent, not after handshake subi YL, 2 ;[0] sbci YH, 0 ;[1] breq skipAddrAssign ;[2] sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer skipAddrAssign: ;end of usbDeviceAddress transfer ldi x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag out USB_INTR_PENDING, x2;[5] ori x1, USBIDLE ;[6] in x2, USBDDR ;[7] cbr x2, USBMASK ;[8] set both pins to input mov x3, x1 ;[9] cbr x3, USBMASK ;[10] configure no pullup on both pins ldi x4, 4 ;[11] se0Delay: dec x4 ;[12] [15] [18] [21] brne se0Delay ;[13] [16] [19] [22] out USBOUT, x1 ;[23] <-- out J (idle) -- end of SE0 (EOP signal) out USBDDR, x2 ;[24] <-- release bus now out USBOUT, x3 ;[25] <-- ensure no pull-up resistors are active rjmp doReturn
wagiminator/ATtiny85-TinyKnob
18,682
software/sources/usbdrv/usbdrvasm16.S
/* Name: usbdrvasm16.S * Project: AVR USB driver * Author: Christian Starkjohann * Creation Date: 2007-06-15 * Tabsize: 4 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt) * Revision: $Id$ */ /* Do not link this file! Link usbdrvasm.S instead, which includes the * appropriate implementation! */ /* General Description: This file is the 16 MHz version of the asssembler part of the USB driver. It requires a 16 MHz crystal (not a ceramic resonator and not a calibrated RC oscillator). See usbdrv.h for a description of the entire driver. Since almost all of this code is timing critical, don't change unless you really know what you are doing! Many parts require not only a maximum number of CPU cycles, but even an exact number of cycles! */ ;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes ;nominal frequency: 16 MHz -> 10.6666666 cycles per bit, 85.333333333 cycles per byte ; Numbers in brackets are clocks counted from center of last sync bit ; when instruction starts SIG_INTERRUPT0: ;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt push YL ;[-25] push only what is necessary to sync with edge ASAP in YL, SREG ;[-23] push YL ;[-22] push YH ;[-20] ;---------------------------------------------------------------------------- ; Synchronize with sync pattern: ;---------------------------------------------------------------------------- ;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] ;sync up with J to K edge during sync pattern -- use fastest possible loops ;first part has no timeout because it waits for IDLE or SE1 (== disconnected) waitForJ: sbis USBIN, USBMINUS ;[-18] wait for D- == 1 rjmp waitForJ waitForK: ;The following code results in a sampling window of < 1/4 bit which meets the spec. sbis USBIN, USBMINUS ;[-15] rjmp foundK ;[-14] sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK rjmp sofError foundK: ;[-12] ;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling] ;we have 1 bit time for setup purposes, then sample again. Numbers in brackets ;are cycles from center of first sync (double K) bit after the instruction push bitcnt ;[-12] ; [---] ;[-11] lds YL, usbInputBufOffset;[-10] ; [---] ;[-9] clr YH ;[-8] subi YL, lo8(-(usbRxBuf));[-7] [rx loop init] sbci YH, hi8(-(usbRxBuf));[-6] [rx loop init] push shift ;[-5] ; [---] ;[-4] ldi bitcnt, 0x55 ;[-3] [rx loop init] sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early) rjmp haveTwoBitsK ;[-1] pop shift ;[0] undo the push from before pop bitcnt ;[2] undo the push from before rjmp waitForK ;[4] this was not the end of sync, retry ; The entire loop from waitForK until rjmp waitForK above must not exceed two ; bit times (= 21 cycles). ;---------------------------------------------------------------------------- ; push more registers and initialize values while we sample the first bits: ;---------------------------------------------------------------------------- haveTwoBitsK: push x1 ;[1] push x2 ;[3] push x3 ;[5] ldi shift, 0 ;[7] ldi x3, 1<<4 ;[8] [rx loop init] first sample is inverse bit, compensate that push x4 ;[9] == leap in x1, USBIN ;[11] <-- sample bit 0 andi x1, USBMASK ;[12] bst x1, USBMINUS ;[13] bld shift, 7 ;[14] push cnt ;[15] ldi leap, 0 ;[17] [rx loop init] ldi cnt, USB_BUFSIZE;[18] [rx loop init] rjmp rxbit1 ;[19] arrives at [21] ;---------------------------------------------------------------------------- ; Receiver loop (numbers in brackets are cycles within byte after instr) ;---------------------------------------------------------------------------- unstuff6: andi x2, USBMASK ;[03] ori x3, 1<<6 ;[04] will not be shifted any more andi shift, ~0x80;[05] mov x1, x2 ;[06] sampled bit 7 is actually re-sampled bit 6 subi leap, 3 ;[07] since this is a short (10 cycle) bit, enforce leap bit rjmp didUnstuff6 ;[08] unstuff7: ori x3, 1<<7 ;[09] will not be shifted any more in x2, USBIN ;[00] [10] re-sample bit 7 andi x2, USBMASK ;[01] andi shift, ~0x80;[02] subi leap, 3 ;[03] since this is a short (10 cycle) bit, enforce leap bit rjmp didUnstuff7 ;[04] unstuffEven: ori x3, 1<<6 ;[09] will be shifted right 6 times for bit 0 in x1, USBIN ;[00] [10] andi shift, ~0x80;[01] andi x1, USBMASK ;[02] breq se0 ;[03] subi leap, 3 ;[04] since this is a short (10 cycle) bit, enforce leap bit nop ;[05] rjmp didUnstuffE ;[06] unstuffOdd: ori x3, 1<<5 ;[09] will be shifted right 4 times for bit 1 in x2, USBIN ;[00] [10] andi shift, ~0x80;[01] andi x2, USBMASK ;[02] breq se0 ;[03] subi leap, 3 ;[04] since this is a short (10 cycle) bit, enforce leap bit nop ;[05] rjmp didUnstuffO ;[06] rxByteLoop: andi x1, USBMASK ;[03] eor x2, x1 ;[04] subi leap, 1 ;[05] brpl skipLeap ;[06] subi leap, -3 ;1 one leap cycle every 3rd byte -> 85 + 1/3 cycles per byte nop ;1 skipLeap: subi x2, 1 ;[08] ror shift ;[09] didUnstuff6: cpi shift, 0xfc ;[10] in x2, USBIN ;[00] [11] <-- sample bit 7 brcc unstuff6 ;[01] andi x2, USBMASK ;[02] eor x1, x2 ;[03] subi x1, 1 ;[04] ror shift ;[05] didUnstuff7: cpi shift, 0xfc ;[06] brcc unstuff7 ;[07] eor x3, shift ;[08] reconstruct: x3 is 1 at bit locations we changed, 0 at others st y+, x3 ;[09] store data rxBitLoop: in x1, USBIN ;[00] [11] <-- sample bit 0/2/4 andi x1, USBMASK ;[01] eor x2, x1 ;[02] andi x3, 0x3f ;[03] topmost two bits reserved for 6 and 7 subi x2, 1 ;[04] ror shift ;[05] cpi shift, 0xfc ;[06] brcc unstuffEven ;[07] didUnstuffE: lsr x3 ;[08] lsr x3 ;[09] rxbit1: in x2, USBIN ;[00] [10] <-- sample bit 1/3/5 andi x2, USBMASK ;[01] breq se0 ;[02] eor x1, x2 ;[03] subi x1, 1 ;[04] ror shift ;[05] cpi shift, 0xfc ;[06] brcc unstuffOdd ;[07] didUnstuffO: subi bitcnt, 0xab;[08] == addi 0x55, 0x55 = 0x100/3 brcs rxBitLoop ;[09] subi cnt, 1 ;[10] in x1, USBIN ;[00] [11] <-- sample bit 6 brcc rxByteLoop ;[01] rjmp ignorePacket; overflow ;---------------------------------------------------------------------------- ; Processing of received packet (numbers in brackets are cycles after center of SE0) ;---------------------------------------------------------------------------- ;This is the only non-error exit point for the software receiver loop ;we don't check any CRCs here because there is no time left. #define token x1 se0: subi cnt, USB_BUFSIZE ;[5] neg cnt ;[6] cpi cnt, 3 ;[7] ldi x2, 1<<USB_INTR_PENDING_BIT ;[8] out USB_INTR_PENDING, x2;[9] clear pending intr and check flag later. SE0 should be over. brlo doReturn ;[10] this is probably an ACK, NAK or similar packet sub YL, cnt ;[11] sbci YH, 0 ;[12] ld token, y ;[13] cpi token, USBPID_DATA0 ;[15] breq handleData ;[16] cpi token, USBPID_DATA1 ;[17] breq handleData ;[18] ldd x2, y+1 ;[19] ADDR and 1 bit endpoint number mov x3, x2 ;[21] store for endpoint number andi x2, 0x7f ;[22] x2 is now ADDR lds shift, usbDeviceAddr;[23] cp x2, shift ;[25] overflow: ; This is a hack: brcs overflow will never have Z flag set brne ignorePacket ;[26] packet for different address cpi token, USBPID_IN ;[27] breq handleIn ;[28] cpi token, USBPID_SETUP ;[29] breq handleSetupOrOut ;[30] cpi token, USBPID_OUT ;[31] breq handleSetupOrOut ;[32] ; rjmp ignorePacket ;fallthrough, should not happen anyway. ignorePacket: clr shift sts usbCurrentTok, shift doReturn: pop cnt pop x4 pop x3 pop x2 pop x1 pop shift pop bitcnt sofError: pop YH pop YL out SREG, YL pop YL reti #if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_HAVE_INTRIN_ENDPOINT3 handleIn3: lds cnt, usbTxLen3 ;[43] sbrc cnt, 4 ;[45] rjmp sendCntAndReti ;[46] 48 + 16 = 64 until SOP sts usbTxLen3, x1 ;[47] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf3) ;[49] ldi YH, hi8(usbTxBuf3) ;[50] rjmp usbSendAndReti ;[51] 53 + 12 = 65 until SOP #endif ;Setup and Out are followed by a data packet two bit times (16 cycles) after ;the end of SE0. The sync code allows up to 40 cycles delay from the start of ;the sync pattern until the first bit is sampled. That's a total of 56 cycles. handleSetupOrOut: ;[34] #if USB_CFG_IMPLEMENT_FN_WRITEOUT /* if we have data for second OUT endpoint, set usbCurrentTok to -1 */ sbrc x3, 7 ;[34] skip if endpoint 0 ldi token, -1 ;[35] indicate that this is endpoint 1 OUT #endif sts usbCurrentTok, token;[36] pop cnt ;[38] pop x4 ;[40] pop x3 ;[42] pop x2 ;[44] pop x1 ;[46] pop shift ;[48] pop bitcnt ;[50] in YL, USB_INTR_PENDING;[52] sbrc YL, USB_INTR_PENDING_BIT;[53] check whether data is already arriving rjmp waitForJ ;[54] save the pops and pushes -- a new interrupt is aready pending rjmp sofError ;[55] not an error, but it does the pops and reti we want handleData: lds token, usbCurrentTok;[20] tst token ;[22] breq doReturn ;[23] lds x2, usbRxLen ;[24] tst x2 ;[26] brne sendNakAndReti ;[27] ; 2006-03-11: The following two lines fix a problem where the device was not ; recognized if usbPoll() was called less frequently than once every 4 ms. cpi cnt, 4 ;[28] zero sized data packets are status phase only -- ignore and ack brmi sendAckAndReti ;[29] keep rx buffer clean -- we must not NAK next SETUP sts usbRxLen, cnt ;[30] store received data, swap buffers sts usbRxToken, token ;[32] lds x2, usbInputBufOffset;[34] swap buffers ldi cnt, USB_BUFSIZE ;[36] sub cnt, x2 ;[37] sts usbInputBufOffset, cnt;[38] buffers now swapped rjmp sendAckAndReti ;[40] 42 + 17 = 59 until SOP handleIn: ;We don't send any data as long as the C code has not processed the current ;input data and potentially updated the output data. That's more efficient ;in terms of code size than clearing the tx buffers when a packet is received. lds x1, usbRxLen ;[30] cpi x1, 1 ;[32] negative values are flow control, 0 means "buffer free" brge sendNakAndReti ;[33] unprocessed input packet? ldi x1, USBPID_NAK ;[34] prepare value for usbTxLen #if USB_CFG_HAVE_INTRIN_ENDPOINT sbrc x3, 7 ;[35] x3 contains addr + endpoint rjmp handleIn1 ;[36] #endif lds cnt, usbTxLen ;[37] sbrc cnt, 4 ;[39] all handshake tokens have bit 4 set rjmp sendCntAndReti ;[40] 42 + 16 = 58 until SOP sts usbTxLen, x1 ;[41] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf) ;[43] ldi YH, hi8(usbTxBuf) ;[44] rjmp usbSendAndReti ;[45] 47 + 12 = 59 until SOP ; Comment about when to set usbTxLen to USBPID_NAK: ; We should set it back when we receive the ACK from the host. This would ; be simple to implement: One static variable which stores whether the last ; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the ; ACK. However, we set it back immediately when we send the package, ; assuming that no error occurs and the host sends an ACK. We save one byte ; RAM this way and avoid potential problems with endless retries. The rest of ; the driver assumes error-free transfers anyway. #if USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */ handleIn1: ;[38] #if USB_CFG_HAVE_INTRIN_ENDPOINT3 ; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint ldd x2, y+2 ;[38] sbrc x2, 0 ;[40] rjmp handleIn3 ;[41] #endif lds cnt, usbTxLen1 ;[42] sbrc cnt, 4 ;[44] all handshake tokens have bit 4 set rjmp sendCntAndReti ;[45] 47 + 16 = 63 until SOP sts usbTxLen1, x1 ;[46] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf1) ;[48] ldi YH, hi8(usbTxBuf1) ;[49] rjmp usbSendAndReti ;[50] 52 + 12 + 64 until SOP #endif ; USB spec says: ; idle = J ; J = (D+ = 0), (D- = 1) ; K = (D+ = 1), (D- = 0) ; Spec allows 7.5 bit times from EOP to SOP for replies bitstuffN: eor x1, x4 ;[5] ldi x2, 0 ;[6] nop2 ;[7] nop ;[9] out USBOUT, x1 ;[10] <-- out rjmp didStuffN ;[0] bitstuff6: eor x1, x4 ;[4] ldi x2, 0 ;[5] nop2 ;[6] C is zero (brcc) rjmp didStuff6 ;[8] bitstuff7: eor x1, x4 ;[3] ldi x2, 0 ;[4] rjmp didStuff7 ;[5] sendNakAndReti: ldi x3, USBPID_NAK ;[-18] rjmp sendX3AndReti ;[-17] sendAckAndReti: ldi cnt, USBPID_ACK ;[-17] sendCntAndReti: mov x3, cnt ;[-16] sendX3AndReti: ldi YL, 20 ;[-15] x3==r20 address is 20 ldi YH, 0 ;[-14] ldi cnt, 2 ;[-13] ; rjmp usbSendAndReti fallthrough ;usbSend: ;pointer to data in 'Y' ;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] ;uses: x1...x4, btcnt, shift, cnt, Y ;Numbers in brackets are time since first bit of sync pattern is sent ;We don't match the transfer rate exactly (don't insert leap cycles every third ;byte) because the spec demands only 1.5% precision anyway. usbSendAndReti: ; 12 cycles until SOP in x2, USBDDR ;[-12] ori x2, USBMASK ;[-11] sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) in x1, USBOUT ;[-8] port mirror for tx loop out USBDDR, x2 ;[-7] <- acquire bus ; need not init x2 (bitstuff history) because sync starts with 0 ldi x4, USBMASK ;[-6] exor mask ldi shift, 0x80 ;[-5] sync byte is first byte sent txByteLoop: ldi bitcnt, 0x2a ;[-4] [6] binary 00101010 txBitLoop: sbrs shift, 0 ;[-3] [7] eor x1, x4 ;[-2] [8] out USBOUT, x1 ;[-1] [9] <-- out N ror shift ;[0] [10] ror x2 ;[1] didStuffN: cpi x2, 0xfc ;[2] brcc bitstuffN ;[3] lsr bitcnt ;[4] brcc txBitLoop ;[5] brne txBitLoop ;[6] sbrs shift, 0 ;[7] eor x1, x4 ;[8] ror shift ;[9] didStuff6: out USBOUT, x1 ;[-1] [10] <-- out 6 ror x2 ;[0] [11] cpi x2, 0xfc ;[1] brcc bitstuff6 ;[2] sbrs shift, 0 ;[3] eor x1, x4 ;[4] ror shift ;[5] ror x2 ;[6] didStuff7: nop ;[7] nop2 ;[8] out USBOUT, x1 ;[-1][10] <-- out 7 cpi x2, 0xfc ;[0] [11] brcc bitstuff7 ;[1] ld shift, y+ ;[2] dec cnt ;[4] brne txByteLoop ;[4] ;make SE0: cbr x1, USBMASK ;[7] prepare SE0 [spec says EOP may be 21 to 25 cycles] lds x2, usbNewDeviceAddr;[8] out USBOUT, x1 ;[10] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle ;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: ;set address only after data packet was sent, not after handshake subi YL, 2 ;[0] sbci YH, 0 ;[1] breq skipAddrAssign ;[2] sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer skipAddrAssign: ;end of usbDeviceAddress transfer ldi x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag out USB_INTR_PENDING, x2;[5] ori x1, USBIDLE ;[6] in x2, USBDDR ;[7] cbr x2, USBMASK ;[8] set both pins to input mov x3, x1 ;[9] cbr x3, USBMASK ;[10] configure no pullup on both pins ldi x4, 4 ;[11] se0Delay: dec x4 ;[12] [15] [18] [21] brne se0Delay ;[13] [16] [19] [22] out USBOUT, x1 ;[23] <-- out J (idle) -- end of SE0 (EOP signal) out USBDDR, x2 ;[24] <-- release bus now out USBOUT, x3 ;[25] <-- ensure no pull-up resistors are active rjmp doReturn
wagiminator/ATtiny85-TinyKnob
23,046
software/sources/usbdrv/usbdrvasm12.S
/* Name: usbdrvasm12.S * Project: AVR USB driver * Author: Christian Starkjohann * Creation Date: 2004-12-29 * Tabsize: 4 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt) * This Revision: $Id: usbdrvasm12.S 353 2007-06-21 19:05:08Z cs $ */ /* Do not link this file! Link usbdrvasm.S instead, which includes the * appropriate implementation! */ /* General Description: This file is the 12 MHz version of the asssembler part of the USB driver. It requires a 12 MHz crystal (not a ceramic resonator and not a calibrated RC oscillator). See usbdrv.h for a description of the entire driver. Since almost all of this code is timing critical, don't change unless you really know what you are doing! Many parts require not only a maximum number of CPU cycles, but even an exact number of cycles! Timing constraints according to spec (in bit times): timing subject min max CPUcycles --------------------------------------------------------------------------- EOP of OUT/SETUP to sync pattern of DATA0 (both rx) 2 16 16-128 EOP of IN to sync pattern of DATA0 (rx, then tx) 2 7.5 16-60 DATAx (rx) to ACK/NAK/STALL (tx) 2 7.5 16-60 */ ;Software-receiver engine. Strict timing! Don't change unless you can preserve timing! ;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled ;max allowable interrupt latency: 34 cycles -> max 25 cycles interrupt disable ;max stack usage: [ret(2), YL, SREG, YH, shift, x1, x2, x3, cnt, x4] = 11 bytes ;Numbers in brackets are maximum cycles since SOF. SIG_INTERRUPT0: ;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt push YL ;2 [35] push only what is necessary to sync with edge ASAP in YL, SREG ;1 [37] push YL ;2 [39] ;---------------------------------------------------------------------------- ; Synchronize with sync pattern: ;---------------------------------------------------------------------------- ;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] ;sync up with J to K edge during sync pattern -- use fastest possible loops ;first part has no timeout because it waits for IDLE or SE1 (== disconnected) waitForJ: sbis USBIN, USBMINUS ;1 [40] wait for D- == 1 rjmp waitForJ ;2 waitForK: ;The following code results in a sampling window of 1/4 bit which meets the spec. sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK rjmp sofError foundK: ;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling] ;we have 1 bit time for setup purposes, then sample again. Numbers in brackets ;are cycles from center of first sync (double K) bit after the instruction push YH ;2 [2] lds YL, usbInputBufOffset;2 [4] clr YH ;1 [5] subi YL, lo8(-(usbRxBuf));1 [6] sbci YH, hi8(-(usbRxBuf));1 [7] sbis USBIN, USBMINUS ;1 [8] we want two bits K [sample 1 cycle too early] rjmp haveTwoBitsK ;2 [10] pop YH ;2 [11] undo the push from before rjmp waitForK ;2 [13] this was not the end of sync, retry haveTwoBitsK: ;---------------------------------------------------------------------------- ; push more registers and initialize values while we sample the first bits: ;---------------------------------------------------------------------------- push shift ;2 [16] push x1 ;2 [12] push x2 ;2 [14] in x1, USBIN ;1 [17] <-- sample bit 0 ldi shift, 0xff ;1 [18] bst x1, USBMINUS ;1 [19] bld shift, 0 ;1 [20] push x3 ;2 [22] push cnt ;2 [24] in x2, USBIN ;1 [25] <-- sample bit 1 ser x3 ;1 [26] [inserted init instruction] eor x1, x2 ;1 [27] bst x1, USBMINUS ;1 [28] bld shift, 1 ;1 [29] ldi cnt, USB_BUFSIZE;1 [30] [inserted init instruction] rjmp rxbit2 ;2 [32] ;---------------------------------------------------------------------------- ; Receiver loop (numbers in brackets are cycles within byte after instr) ;---------------------------------------------------------------------------- unstuff0: ;1 (branch taken) andi x3, ~0x01 ;1 [15] mov x1, x2 ;1 [16] x2 contains last sampled (stuffed) bit in x2, USBIN ;1 [17] <-- sample bit 1 again ori shift, 0x01 ;1 [18] rjmp didUnstuff0 ;2 [20] unstuff1: ;1 (branch taken) mov x2, x1 ;1 [21] x1 contains last sampled (stuffed) bit andi x3, ~0x02 ;1 [22] ori shift, 0x02 ;1 [23] nop ;1 [24] in x1, USBIN ;1 [25] <-- sample bit 2 again rjmp didUnstuff1 ;2 [27] unstuff2: ;1 (branch taken) andi x3, ~0x04 ;1 [29] ori shift, 0x04 ;1 [30] mov x1, x2 ;1 [31] x2 contains last sampled (stuffed) bit nop ;1 [32] in x2, USBIN ;1 [33] <-- sample bit 3 rjmp didUnstuff2 ;2 [35] unstuff3: ;1 (branch taken) in x2, USBIN ;1 [34] <-- sample stuffed bit 3 [one cycle too late] andi x3, ~0x08 ;1 [35] ori shift, 0x08 ;1 [36] rjmp didUnstuff3 ;2 [38] unstuff4: ;1 (branch taken) andi x3, ~0x10 ;1 [40] in x1, USBIN ;1 [41] <-- sample stuffed bit 4 ori shift, 0x10 ;1 [42] rjmp didUnstuff4 ;2 [44] unstuff5: ;1 (branch taken) andi x3, ~0x20 ;1 [48] in x2, USBIN ;1 [49] <-- sample stuffed bit 5 ori shift, 0x20 ;1 [50] rjmp didUnstuff5 ;2 [52] unstuff6: ;1 (branch taken) andi x3, ~0x40 ;1 [56] in x1, USBIN ;1 [57] <-- sample stuffed bit 6 ori shift, 0x40 ;1 [58] rjmp didUnstuff6 ;2 [60] ; extra jobs done during bit interval: ; bit 0: store, clear [SE0 is unreliable here due to bit dribbling in hubs] ; bit 1: se0 check ; bit 2: overflow check ; bit 3: recovery from delay [bit 0 tasks took too long] ; bit 4: none ; bit 5: none ; bit 6: none ; bit 7: jump, eor rxLoop: eor x3, shift ;1 [0] reconstruct: x3 is 0 at bit locations we changed, 1 at others in x1, USBIN ;1 [1] <-- sample bit 0 st y+, x3 ;2 [3] store data ser x3 ;1 [4] nop ;1 [5] eor x2, x1 ;1 [6] bst x2, USBMINUS;1 [7] bld shift, 0 ;1 [8] in x2, USBIN ;1 [9] <-- sample bit 1 (or possibly bit 0 stuffed) andi x2, USBMASK ;1 [10] breq se0 ;1 [11] SE0 check for bit 1 andi shift, 0xf9 ;1 [12] didUnstuff0: breq unstuff0 ;1 [13] eor x1, x2 ;1 [14] bst x1, USBMINUS;1 [15] bld shift, 1 ;1 [16] rxbit2: in x1, USBIN ;1 [17] <-- sample bit 2 (or possibly bit 1 stuffed) andi shift, 0xf3 ;1 [18] breq unstuff1 ;1 [19] do remaining work for bit 1 didUnstuff1: subi cnt, 1 ;1 [20] brcs overflow ;1 [21] loop control eor x2, x1 ;1 [22] bst x2, USBMINUS;1 [23] bld shift, 2 ;1 [24] in x2, USBIN ;1 [25] <-- sample bit 3 (or possibly bit 2 stuffed) andi shift, 0xe7 ;1 [26] breq unstuff2 ;1 [27] didUnstuff2: eor x1, x2 ;1 [28] bst x1, USBMINUS;1 [29] bld shift, 3 ;1 [30] didUnstuff3: andi shift, 0xcf ;1 [31] breq unstuff3 ;1 [32] in x1, USBIN ;1 [33] <-- sample bit 4 eor x2, x1 ;1 [34] bst x2, USBMINUS;1 [35] bld shift, 4 ;1 [36] didUnstuff4: andi shift, 0x9f ;1 [37] breq unstuff4 ;1 [38] nop2 ;2 [40] in x2, USBIN ;1 [41] <-- sample bit 5 eor x1, x2 ;1 [42] bst x1, USBMINUS;1 [43] bld shift, 5 ;1 [44] didUnstuff5: andi shift, 0x3f ;1 [45] breq unstuff5 ;1 [46] nop2 ;2 [48] in x1, USBIN ;1 [49] <-- sample bit 6 eor x2, x1 ;1 [50] bst x2, USBMINUS;1 [51] bld shift, 6 ;1 [52] didUnstuff6: cpi shift, 0x02 ;1 [53] brlo unstuff6 ;1 [54] nop2 ;2 [56] in x2, USBIN ;1 [57] <-- sample bit 7 eor x1, x2 ;1 [58] bst x1, USBMINUS;1 [59] bld shift, 7 ;1 [60] didUnstuff7: cpi shift, 0x04 ;1 [61] brsh rxLoop ;2 [63] loop control unstuff7: andi x3, ~0x80 ;1 [63] ori shift, 0x80 ;1 [64] in x2, USBIN ;1 [65] <-- sample stuffed bit 7 nop ;1 [66] rjmp didUnstuff7 ;2 [68] ;---------------------------------------------------------------------------- ; Processing of received packet (numbers in brackets are cycles after end of SE0) ;---------------------------------------------------------------------------- ;This is the only non-error exit point for the software receiver loop ;we don't check any CRCs here because there is no time left. #define token x1 se0: ; [0] subi cnt, USB_BUFSIZE ;1 [1] neg cnt ;1 [2] cpi cnt, 3 ;1 [3] ldi x2, 1<<USB_INTR_PENDING_BIT ;1 [4] out USB_INTR_PENDING, x2;1 [5] clear pending intr and check flag later. SE0 should be over. brlo doReturn ;1 [6] this is probably an ACK, NAK or similar packet sub YL, cnt ;1 [7] sbci YH, 0 ;1 [8] ld token, y ;2 [10] cpi token, USBPID_DATA0 ;1 [11] breq handleData ;1 [12] cpi token, USBPID_DATA1 ;1 [13] breq handleData ;1 [14] ldd x2, y+1 ;2 [16] ADDR and 1 bit endpoint number mov x3, x2 ;1 [17] store for endpoint number andi x2, 0x7f ;1 [18] x2 is now ADDR lds shift, usbDeviceAddr;2 [20] cp x2, shift ;1 [21] overflow: ; This is a hack: brcs overflow will never have Z flag set brne ignorePacket ;1 [22] packet for different address cpi token, USBPID_IN ;1 [23] breq handleIn ;1 [24] cpi token, USBPID_SETUP ;1 [25] breq handleSetupOrOut ;1 [26] cpi token, USBPID_OUT ;1 [27] breq handleSetupOrOut ;1 [28] ; rjmp ignorePacket ;fallthrough, should not happen anyway. ignorePacket: clr shift sts usbCurrentTok, shift doReturn: pop cnt pop x3 pop x2 pop x1 pop shift pop YH sofError: pop YL out SREG, YL pop YL reti #if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_HAVE_INTRIN_ENDPOINT3 handleIn3: ;1 [38] (branch taken) lds cnt, usbTxLen3 ;2 [40] sbrc cnt, 4 ;2 [42] rjmp sendCntAndReti ;0 43 + 17 = 60 until SOP sts usbTxLen3, x1 ;2 [44] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf3) ;1 [45] ldi YH, hi8(usbTxBuf3) ;1 [46] rjmp usbSendAndReti ;2 [48] + 13 = 61 until SOP (violates the spec by 1 cycle) #endif ;Setup and Out are followed by a data packet two bit times (16 cycles) after ;the end of SE0. The sync code allows up to 40 cycles delay from the start of ;the sync pattern until the first bit is sampled. That's a total of 56 cycles. handleSetupOrOut: ;1 [29] (branch taken) #if USB_CFG_IMPLEMENT_FN_WRITEOUT /* if we have data for second OUT endpoint, set usbCurrentTok to -1 */ sbrc x3, 7 ;1 [30] skip if endpoint 0 ldi token, -1 ;1 [31] indicate that this is endpoint 1 OUT #endif sts usbCurrentTok, token;2 [33] pop cnt ;2 [35] pop x3 ;2 [37] pop x2 ;2 [39] pop x1 ;2 [41] pop shift ;2 [43] pop YH ;2 [45] in YL, USB_INTR_PENDING;1 [46] sbrc YL, USB_INTR_PENDING_BIT;1 [47] check whether data is already arriving rjmp waitForJ ;2 [49] save the pops and pushes -- a new interrupt is aready pending rjmp sofError ;2 not an error, but it does the pops and reti we want handleData: ;1 [15] (branch taken) lds token, usbCurrentTok;2 [17] tst token ;1 [18] breq doReturn ;1 [19] lds x2, usbRxLen ;2 [21] tst x2 ;1 [22] brne sendNakAndReti ;1 [23] ; 2006-03-11: The following two lines fix a problem where the device was not ; recognized if usbPoll() was called less frequently than once every 4 ms. cpi cnt, 4 ;1 [24] zero sized data packets are status phase only -- ignore and ack brmi sendAckAndReti ;1 [25] keep rx buffer clean -- we must not NAK next SETUP sts usbRxLen, cnt ;2 [27] store received data, swap buffers sts usbRxToken, token ;2 [29] lds x2, usbInputBufOffset;2 [31] swap buffers ldi cnt, USB_BUFSIZE ;1 [32] sub cnt, x2 ;1 [33] sts usbInputBufOffset, cnt;2 [35] buffers now swapped rjmp sendAckAndReti ;2 [37] + 19 = 56 until SOP handleIn: ;1 [25] (branch taken) ;We don't send any data as long as the C code has not processed the current ;input data and potentially updated the output data. That's more efficient ;in terms of code size than clearing the tx buffers when a packet is received. lds x1, usbRxLen ;2 [27] cpi x1, 1 ;1 [28] negative values are flow control, 0 means "buffer free" brge sendNakAndReti ;1 [29] unprocessed input packet? ldi x1, USBPID_NAK ;1 [30] prepare value for usbTxLen #if USB_CFG_HAVE_INTRIN_ENDPOINT sbrc x3, 7 ;2 [33] x3 contains addr + endpoint rjmp handleIn1 ;0 #endif lds cnt, usbTxLen ;2 [34] sbrc cnt, 4 ;2 [36] all handshake tokens have bit 4 set rjmp sendCntAndReti ;0 37 + 17 = 54 until SOP sts usbTxLen, x1 ;2 [38] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf) ;1 [39] ldi YH, hi8(usbTxBuf) ;1 [40] rjmp usbSendAndReti ;2 [42] + 14 = 56 until SOP ; Comment about when to set usbTxLen to USBPID_NAK: ; We should set it back when we receive the ACK from the host. This would ; be simple to implement: One static variable which stores whether the last ; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the ; ACK. However, we set it back immediately when we send the package, ; assuming that no error occurs and the host sends an ACK. We save one byte ; RAM this way and avoid potential problems with endless retries. The rest of ; the driver assumes error-free transfers anyway. #if USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */ handleIn1: ;1 [33] (branch taken) #if USB_CFG_HAVE_INTRIN_ENDPOINT3 ; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint ldd x2, y+2 ;2 [35] sbrc x2, 0 ;2 [37] rjmp handleIn3 ;0 #endif lds cnt, usbTxLen1 ;2 [39] sbrc cnt, 4 ;2 [41] all handshake tokens have bit 4 set rjmp sendCntAndReti ;0 42 + 17 = 59 until SOP sts usbTxLen1, x1 ;2 [43] x1 == USBPID_NAK from above ldi YL, lo8(usbTxBuf1) ;1 [44] ldi YH, hi8(usbTxBuf1) ;1 [45] rjmp usbSendAndReti ;2 [47] + 13 = 60 until SOP #endif ;---------------------------------------------------------------------------- ; Transmitting data ;---------------------------------------------------------------------------- bitstuff0: ;1 (for branch taken) eor x1, x4 ;1 ldi x2, 0 ;1 out USBOUT, x1 ;1 <-- out rjmp didStuff0 ;2 branch back 2 cycles earlier bitstuff1: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff1 ;2 we know that C is clear, jump back to do OUT and ror 0 into x2 bitstuff2: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff2 ;2 jump back 4 cycles earlier and do out and ror 0 into x2 bitstuff3: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff3 ;2 jump back earlier and ror 0 into x2 bitstuff4: ;1 (for branch taken) eor x1, x4 ;1 ldi x2, 0 ;1 out USBOUT, x1 ;1 <-- out rjmp didStuff4 ;2 jump back 2 cycles earlier sendNakAndReti: ;0 [-19] 19 cycles until SOP ldi x3, USBPID_NAK ;1 [-18] rjmp usbSendX3 ;2 [-16] sendAckAndReti: ;0 [-19] 19 cycles until SOP ldi x3, USBPID_ACK ;1 [-18] rjmp usbSendX3 ;2 [-16] sendCntAndReti: ;0 [-17] 17 cycles until SOP mov x3, cnt ;1 [-16] usbSendX3: ;0 [-16] ldi YL, 20 ;1 [-15] 'x3' is R20 ldi YH, 0 ;1 [-14] ldi cnt, 2 ;1 [-13] ; rjmp usbSendAndReti fallthrough ; USB spec says: ; idle = J ; J = (D+ = 0), (D- = 1) or USBOUT = 0x01 ; K = (D+ = 1), (D- = 0) or USBOUT = 0x02 ; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles) ;usbSend: ;pointer to data in 'Y' ;number of bytes in 'cnt' -- including sync byte ;uses: x1...x4, shift, cnt, Y ;Numbers in brackets are time since first bit of sync pattern is sent usbSendAndReti: ;0 [-13] timing: 13 cycles until SOP in x2, USBDDR ;1 [-12] ori x2, USBMASK ;1 [-11] sbi USBOUT, USBMINUS;2 [-9] prepare idle state; D+ and D- must have been 0 (no pullups) in x1, USBOUT ;1 [-8] port mirror for tx loop out USBDDR, x2 ;1 [-7] <- acquire bus ; need not init x2 (bitstuff history) because sync starts with 0 push x4 ;2 [-5] ldi x4, USBMASK ;1 [-4] exor mask ldi shift, 0x80 ;1 [-3] sync byte is first byte sent txLoop: ; [62] sbrs shift, 0 ;1 [-2] [62] eor x1, x4 ;1 [-1] [63] out USBOUT, x1 ;1 [0] <-- out bit 0 ror shift ;1 [1] ror x2 ;1 [2] didStuff0: cpi x2, 0xfc ;1 [3] brsh bitstuff0 ;1 [4] sbrs shift, 0 ;1 [5] eor x1, x4 ;1 [6] ror shift ;1 [7] didStuff1: out USBOUT, x1 ;1 [8] <-- out bit 1 ror x2 ;1 [9] cpi x2, 0xfc ;1 [10] brsh bitstuff1 ;1 [11] sbrs shift, 0 ;1 [12] eor x1, x4 ;1 [13] ror shift ;1 [14] didStuff2: ror x2 ;1 [15] out USBOUT, x1 ;1 [16] <-- out bit 2 cpi x2, 0xfc ;1 [17] brsh bitstuff2 ;1 [18] sbrs shift, 0 ;1 [19] eor x1, x4 ;1 [20] ror shift ;1 [21] didStuff3: ror x2 ;1 [22] cpi x2, 0xfc ;1 [23] out USBOUT, x1 ;1 [24] <-- out bit 3 brsh bitstuff3 ;1 [25] nop2 ;2 [27] ld x3, y+ ;2 [29] sbrs shift, 0 ;1 [30] eor x1, x4 ;1 [31] out USBOUT, x1 ;1 [32] <-- out bit 4 ror shift ;1 [33] ror x2 ;1 [34] didStuff4: cpi x2, 0xfc ;1 [35] brsh bitstuff4 ;1 [36] sbrs shift, 0 ;1 [37] eor x1, x4 ;1 [38] ror shift ;1 [39] didStuff5: out USBOUT, x1 ;1 [40] <-- out bit 5 ror x2 ;1 [41] cpi x2, 0xfc ;1 [42] brsh bitstuff5 ;1 [43] sbrs shift, 0 ;1 [44] eor x1, x4 ;1 [45] ror shift ;1 [46] didStuff6: ror x2 ;1 [47] out USBOUT, x1 ;1 [48] <-- out bit 6 cpi x2, 0xfc ;1 [49] brsh bitstuff6 ;1 [50] sbrs shift, 0 ;1 [51] eor x1, x4 ;1 [52] ror shift ;1 [53] didStuff7: ror x2 ;1 [54] cpi x2, 0xfc ;1 [55] out USBOUT, x1 ;1 [56] <-- out bit 7 brsh bitstuff7 ;1 [57] mov shift, x3 ;1 [58] dec cnt ;1 [59] brne txLoop ;1/2 [60/61] ;make SE0: cbr x1, USBMASK ;1 [61] prepare SE0 [spec says EOP may be 15 to 18 cycles] pop x4 ;2 [63] ;brackets are cycles from start of SE0 now out USBOUT, x1 ;1 [0] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle nop2 ;2 [2] ;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: ;set address only after data packet was sent, not after handshake lds x2, usbNewDeviceAddr;2 [4] subi YL, 20 + 2 ;1 [5] sbci YH, 0 ;1 [6] breq skipAddrAssign ;2 [8] sts usbDeviceAddr, x2;0 if not skipped: SE0 is one cycle longer skipAddrAssign: ;end of usbDeviceAddress transfer ldi x2, 1<<USB_INTR_PENDING_BIT;1 [9] int0 occurred during TX -- clear pending flag out USB_INTR_PENDING, x2;1 [10] ori x1, USBIDLE ;1 [11] in x2, USBDDR ;1 [12] cbr x2, USBMASK ;1 [13] set both pins to input mov x3, x1 ;1 [14] cbr x3, USBMASK ;1 [15] configure no pullup on both pins out USBOUT, x1 ;1 [16] <-- out J (idle) -- end of SE0 (EOP signal) out USBDDR, x2 ;1 [17] <-- release bus now out USBOUT, x3 ;1 [18] <-- ensure no pull-up resistors are active rjmp doReturn bitstuff5: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff5 ;2 same trick as above... bitstuff6: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff6 ;2 same trick as above... bitstuff7: ;1 (for branch taken) eor x1, x4 ;1 rjmp didStuff7 ;2 same trick as above...
wagiminator/ATtiny85-TinyKnob
8,840
software/sources/usbdrv/usbdrvasm.S
/* Name: usbdrvasm.S * Project: AVR USB driver * Author: Christian Starkjohann * Creation Date: 2007-06-13 * Tabsize: 4 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt) * Revision: $Id: usbdrvasm.S 722 2009-03-16 19:03:57Z cs $ */ /* General Description: This module is the assembler part of the USB driver. This file contains general code (preprocessor acrobatics and CRC computation) and then includes the file appropriate for the given clock rate. */ #define __SFR_OFFSET 0 /* used by avr-libc's register definitions */ #include "usbportability.h" #include "usbdrv.h" /* for common defs */ /* register names */ #define x1 r16 #define x2 r17 #define shift r18 #define cnt r19 #define x3 r20 #define x4 r21 #define x5 r22 #define bitcnt x5 #define phase x4 #define leap x4 /* Some assembler dependent definitions and declarations: */ #ifdef __IAR_SYSTEMS_ASM__ extern usbRxBuf, usbDeviceAddr, usbNewDeviceAddr, usbInputBufOffset extern usbCurrentTok, usbRxLen, usbRxToken, usbTxLen extern usbTxBuf, usbTxStatus1, usbTxStatus3 # if USB_COUNT_SOF extern usbSofCount # endif public usbCrc16 public usbCrc16Append COMMON INTVEC # ifndef USB_INTR_VECTOR ORG INT0_vect # else /* USB_INTR_VECTOR */ ORG USB_INTR_VECTOR # undef USB_INTR_VECTOR # endif /* USB_INTR_VECTOR */ # define USB_INTR_VECTOR usbInterruptHandler rjmp USB_INTR_VECTOR RSEG CODE #else /* __IAR_SYSTEMS_ASM__ */ # ifndef USB_INTR_VECTOR /* default to hardware interrupt INT0 */ # define USB_INTR_VECTOR SIG_INTERRUPT0 # endif .text .global USB_INTR_VECTOR .type USB_INTR_VECTOR, @function .global usbCrc16 .global usbCrc16Append #endif /* __IAR_SYSTEMS_ASM__ */ #if USB_INTR_PENDING < 0x40 /* This is an I/O address, use in and out */ # define USB_LOAD_PENDING(reg) in reg, USB_INTR_PENDING # define USB_STORE_PENDING(reg) out USB_INTR_PENDING, reg #else /* It's a memory address, use lds and sts */ # define USB_LOAD_PENDING(reg) lds reg, USB_INTR_PENDING # define USB_STORE_PENDING(reg) sts USB_INTR_PENDING, reg #endif #define usbTxLen1 usbTxStatus1 #define usbTxBuf1 (usbTxStatus1 + 1) #define usbTxLen3 usbTxStatus3 #define usbTxBuf3 (usbTxStatus3 + 1) ;---------------------------------------------------------------------------- ; Utility functions ;---------------------------------------------------------------------------- #ifdef __IAR_SYSTEMS_ASM__ /* Register assignments for usbCrc16 on IAR cc */ /* Calling conventions on IAR: * First parameter passed in r16/r17, second in r18/r19 and so on. * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer) * Result is passed in r16/r17 * In case of the "tiny" memory model, pointers are only 8 bit with no * padding. We therefore pass argument 1 as "16 bit unsigned". */ RTMODEL "__rt_version", "3" /* The line above will generate an error if cc calling conventions change. * The value "3" above is valid for IAR 4.10B/W32 */ # define argLen r18 /* argument 2 */ # define argPtrL r16 /* argument 1 */ # define argPtrH r17 /* argument 1 */ # define resCrcL r16 /* result */ # define resCrcH r17 /* result */ # define ptrL ZL # define ptrH ZH # define ptr Z # define byte r22 # define bitCnt r19 # define polyL r20 # define polyH r21 # define scratch r23 #else /* __IAR_SYSTEMS_ASM__ */ /* Register assignments for usbCrc16 on gcc */ /* Calling conventions on gcc: * First parameter passed in r24/r25, second in r22/23 and so on. * Callee must preserve r1-r17, r28/r29 * Result is passed in r24/r25 */ # define argLen r22 /* argument 2 */ # define argPtrL r24 /* argument 1 */ # define argPtrH r25 /* argument 1 */ # define resCrcL r24 /* result */ # define resCrcH r25 /* result */ # define ptrL XL # define ptrH XH # define ptr x # define byte r18 # define bitCnt r19 # define polyL r20 # define polyH r21 # define scratch r23 #endif ; extern unsigned usbCrc16(unsigned char *data, unsigned char len); ; data: r24/25 ; len: r22 ; temp variables: ; r18: data byte ; r19: bit counter ; r20/21: polynomial ; r23: scratch ; r24/25: crc-sum ; r26/27=X: ptr usbCrc16: mov ptrL, argPtrL mov ptrH, argPtrH ldi resCrcL, 0 ldi resCrcH, 0 ldi polyL, lo8(0xa001) ldi polyH, hi8(0xa001) com argLen ; argLen = -argLen - 1 crcByteLoop: subi argLen, -1 brcc crcReady ; modified loop to ensure that carry is set below ld byte, ptr+ ldi bitCnt, -8 ; strange loop counter to ensure that carry is set where we need it eor resCrcL, byte crcBitLoop: ror resCrcH ; carry is always set here ror resCrcL brcs crcNoXor eor resCrcL, polyL eor resCrcH, polyH crcNoXor: subi bitCnt, -1 brcs crcBitLoop rjmp crcByteLoop crcReady: ret ; Thanks to Reimar Doeffinger for optimizing this CRC routine! ; extern unsigned usbCrc16Append(unsigned char *data, unsigned char len); usbCrc16Append: rcall usbCrc16 st ptr+, resCrcL st ptr+, resCrcH ret #undef argLen #undef argPtrL #undef argPtrH #undef resCrcL #undef resCrcH #undef ptrL #undef ptrH #undef ptr #undef byte #undef bitCnt #undef polyL #undef polyH #undef scratch #if USB_CFG_HAVE_MEASURE_FRAME_LENGTH #ifdef __IAR_SYSTEMS_ASM__ /* Register assignments for usbMeasureFrameLength on IAR cc */ /* Calling conventions on IAR: * First parameter passed in r16/r17, second in r18/r19 and so on. * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer) * Result is passed in r16/r17 * In case of the "tiny" memory model, pointers are only 8 bit with no * padding. We therefore pass argument 1 as "16 bit unsigned". */ # define resL r16 # define resH r17 # define cnt16L r30 # define cnt16H r31 # define cntH r18 #else /* __IAR_SYSTEMS_ASM__ */ /* Register assignments for usbMeasureFrameLength on gcc */ /* Calling conventions on gcc: * First parameter passed in r24/r25, second in r22/23 and so on. * Callee must preserve r1-r17, r28/r29 * Result is passed in r24/r25 */ # define resL r24 # define resH r25 # define cnt16L r24 # define cnt16H r25 # define cntH r26 #endif # define cnt16 cnt16L ; extern unsigned usbMeasurePacketLength(void); ; returns time between two idle strobes in multiples of 7 CPU clocks .global usbMeasureFrameLength usbMeasureFrameLength: ldi cntH, 6 ; wait ~ 10 ms for D- == 0 clr cnt16L clr cnt16H usbMFTime16: dec cntH breq usbMFTimeout usbMFWaitStrobe: ; first wait for D- == 0 (idle strobe) sbiw cnt16, 1 ;[0] [6] breq usbMFTime16 ;[2] sbic USBIN, USBMINUS ;[3] rjmp usbMFWaitStrobe ;[4] usbMFWaitIdle: ; then wait until idle again sbis USBIN, USBMINUS ;1 wait for D- == 1 rjmp usbMFWaitIdle ;2 ldi cnt16L, 1 ;1 represents cycles so far clr cnt16H ;1 usbMFWaitLoop: in cntH, USBIN ;[0] [7] adiw cnt16, 1 ;[1] breq usbMFTimeout ;[3] andi cntH, USBMASK ;[4] brne usbMFWaitLoop ;[5] usbMFTimeout: #if resL != cnt16L mov resL, cnt16L mov resH, cnt16H #endif ret #undef resL #undef resH #undef cnt16 #undef cnt16L #undef cnt16H #undef cntH #endif /* USB_CFG_HAVE_MEASURE_FRAME_LENGTH */ ;---------------------------------------------------------------------------- ; Now include the clock rate specific code ;---------------------------------------------------------------------------- #ifndef USB_CFG_CLOCK_KHZ # define USB_CFG_CLOCK_KHZ 12000 #endif #if USB_CFG_CHECK_CRC /* separate dispatcher for CRC type modules */ # if USB_CFG_CLOCK_KHZ == 18000 # include "usbdrvasm18-crc.inc" # else # error "USB_CFG_CLOCK_KHZ is not one of the supported crc-rates!" # endif #else /* USB_CFG_CHECK_CRC */ # if USB_CFG_CLOCK_KHZ == 12000 # include "usbdrvasm12.inc" # elif USB_CFG_CLOCK_KHZ == 12800 # include "usbdrvasm128.inc" # elif USB_CFG_CLOCK_KHZ == 15000 # include "usbdrvasm15.inc" # elif USB_CFG_CLOCK_KHZ == 16000 # include "usbdrvasm16.inc" # elif USB_CFG_CLOCK_KHZ == 16500 # include "usbdrvasm165.inc" # elif USB_CFG_CLOCK_KHZ == 20000 # include "usbdrvasm20.inc" # else # error "USB_CFG_CLOCK_KHZ is not one of the supported non-crc-rates!" # endif #endif /* USB_CFG_CHECK_CRC */
wagiminator/CH32V003-MacroPad-plus
23,229
software/macropad_plus/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-Mouse-Wiggler
23,229
software/capsblock/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-Mouse-Wiggler
23,229
software/mousewiggler/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-USB-Joystick
23,229
software/joystick/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-USB-Joystick
23,229
software/mousestick/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-Mouse-Wiggler
23,229
software/rubberducky/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-USB-Knob
23,229
software/custom_knob/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-USB-Knob
23,229
software/volume_knob/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/CH32V003-USB-Knob
23,229
software/mousewheel_knob/src/usb_handler.S
// =================================================================================== // Software USB Handler for CH32V003 * v1.0 * // =================================================================================== // // This file contains a copy of rv003usb.S (https://github.com/cnlohr/rv003usb), // copyright (c) 2023 CNLohr (MIT License). #include "ch32v003.h" #include "usb_handler.h" #define CFGLR_OFFSET 0 #define INDR_OFFSET 8 #define BSHR_OFFSET 16 #define LOCAL_CONCAT(A, B) A##B #define LOCAL_EXP(A, B) LOCAL_CONCAT(A,B) #define SYSTICK_CNT 0xE000F008 // This is 6 * n + 3 cylces #define nx6p3delay( n, freereg ) li freereg, ((n)+1); 1: c.addi freereg, -1; c.bnez freereg, 1b //See RV003USB_DEBUG_TIMING note in .c file. #if defined( RV003USB_DEBUG_TIMING ) && RV003USB_DEBUG_TIMING #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x24) // for debug #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #else #define DEBUG_TICK_SETUP la x4, (TIM1_BASE + 0x58) // for debug (Go nowhere) #define DEBUG_TICK_MARK .balign 4; sw x0, 0(x4) #define RESTORE_DEBUG_MARKER(x) lw x4, x(sp) #define SAVE_DEBUG_MARKER(x) sw x4, x(sp) #endif .global test_memory .global rv003usb_internal_data .global rv003usb_handle_packet .global usb_send_data .global usb_send_empty .global main .global always0 /* Register map zero, ra, sp, gp, tp, t0, t1, t2 Compressed: s0, s1, a0, a1, a2, a3, a4, a5 */ .section .text.vector_handler .global EXTI7_0_IRQHandler .balign 4 EXTI7_0_IRQHandler: addi sp,sp,-80 sw a0, 0(sp) sw a5, 20(sp) la a5, USB_GPIO_BASE c.lw a0, INDR_OFFSET(a5) // MUST check SE0 immediately. c.andi a0, USB_DMASK sw a1, 4(sp) sw a2, 8(sp) sw a3, 12(sp) sw a4, 16(sp) sw s1, 28(sp) SAVE_DEBUG_MARKER( 48 ); DEBUG_TICK_SETUP c.lw a1, INDR_OFFSET(a5) c.andi a1, USB_DMASK; // Finish jump to se0 c.beqz a0, handle_se0_keepalive c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; bne a0, a1, syncout c.j syncout syncout: sw s0, 24(sp) li a2, 0 sw t0, 32(sp) // XXX NOTE: This is actually unused register - remove some day? sw t1, 36(sp) // We are coarsely sync'd here. // This will be called when we have synchronized our USB. We can put our // preamble detect code here. But we have a whole free USB bit cycle to // do whatever we feel like. // A little weird, but this way, the USB packet is always aligned. #define DATA_PTR_OFFSET (59+4) // This is actually somewhat late. // The preamble loop should try to make it earlier. .balign 4 preamble_loop: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // SE0 here? c.xor a0, a1; c.xor a1, a0; // Recover a1. j 1f; 1: // 4 cycles? c.beqz a0, done_preamble j 1f; 1: // 4 cycles? c.lw s0, INDR_OFFSET(a5); c.andi s0, USB_DMASK; c.xor s0, a1 // TRICKY: This helps retime the USB sync. // If s0 is nonzero, then it's changed (we're going too slow) c.bnez s0, 2f; // This code takes 6 cycles or 8 cycles, depending. c.j 1f; 1: 2: j preamble_loop // 4 cycles .balign 4 done_preamble: sw t2, 40(sp) sw ra, 52(sp) // 16-byte temporary buffer at 56+sp // XXX TODO: Do one byte here to determine the header byte and from that set the CRC. c.li s1, 8 // This is the first bit that matters. c.li s0, 6 // 1 runs. c.nop; // 8 extra cycles here cause errors. // -5 cycles is too much. // -4 to +6 cycles is OK //XXX NOTE: It actuall wouldn't be too bad to inser an *extra* cycle here. /* register meanings: * x4 = TP = used for triggering debug. * T0 = Totally unushed. * T1 = TEMPORARY * T2 = Pointer to the memory address we are writing to. * A0 = temp / current bit value. * A1 = last-frame's GPIO values. * A2 = The running word * A3 = Running CRC * a4 = Polynomial * A5 = GPIO Offset * S0 = Bit Stuff Place * S1 = # output bits remaining. */ .balign 4 packet_type_loop: // Up here to delay loop a tad, and we need to execute them anyway. // TODO: Maybe we could further sync bits here instead of take up time? // I.e. can we do what we're doing above, here, and take less time, but sync // up when possible. li a3, 0xffff // Starting CRC of 0. Because USB doesn't respect reverse CRCing. li a4, 0xa001 addi t2, sp, DATA_PTR_OFFSET //rv003usb_internal_data la t0, 0x80 c.nop DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, done_usb_message // Not se0 complete, that can't happen here and be valid. c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle // a0 = 00 for 1 and 11 for 0 // No CRC for the header. //c.srli a0, USB_PIN_DP //c.addi a0, 1 // 00 -> 1, 11 -> 100 //c.andi a0, 1 // If 1, 1 if 0, 0 c.nop seqz a0, a0 // Write header into byte in reverse order, because we can. c.slli a2, 1 c.or a2, a0 // Handle bit stuffing rules. c.addi a0, -1 // 0->0xffffffff 1->0 c.or s0, a0 c.andi s0, 7 c.addi s0, -1 c.addi s1, -1 c.bnez s1, packet_type_loop /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// // XXX Here, figure out CRC polynomial. li s1, (USB_BUFFER_SIZE*8) // # of bits we culd read. // WARNING: a0 is bit-wise backwards here. // 0xb4 for instance is a setup packet. // // When we get here, packet type is loaded in A2. // If packet type is 0xXX01 or 0xXX11 // the LSBs are the inverted packet type. // we can branch off of bit 2. andi a0, a2, 0x0c // if a0 is 1 then it's DATA (full CRC) otheriwse, // (0) for setup or PARTIAL CRC. // Careful: This has to take a constant amount of time either way the branch goes. c.beqz a0, data_crc c.li a4, 0x14 c.li a3, 0x1e .word 0x00000013 // nop, for alignment of data_crc. data_crc: #define HANDLE_EOB_YES \ sb a2, 0(t2); /* Save the byte off. TODO: Is unaligned byte access to RAM slow? */ \ .word 0x00138393; /*addi t2, t2, 1;*/ /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// .balign 4 is_end_of_byte: HANDLE_EOB_YES // end-of-byte. .balign 4 bit_process: // Debug blip // c.lw a4, INDR_OFFSET(a5); DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.xor a0, a1; //XXX GOOD #define HANDLE_NEXT_BYTE(is_end_of_byte, jumptype) \ c.addi s1, -1; \ andi a0, s1, 7; /* s1 could be really really big */ \ c.jumptype a0, is_end_of_byte /* 4 cycles for this section. (Checked) (Sometimes 5)? */ c.beqz a0, handle_one_bit handle_zero_bit: c.xor a1, a0; // Recover a1, for next cycle // TODO: Do we have time to do time fixup here? // Can we resync time here? // If they are different, we need to sloowwww dowwwnnn // There is some free time. Could do something interesting here!!! // I was thinking we could put the resync code here. c.j 1f; 1: //Delay 4 cycles. c.li s0, 6 // reset runs-of-one. c.beqz a1, se0_complete // Handle CRC (0 bit) (From @Domkeykong) slli a0,a3,31 // Put a3s LSB into a0s MSB c.srai a0,31 // Copy MSB into all other bits c.srli a3,1 c.and a0, a4 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message .balign 4 handle_one_bit: c.addi s0, -1; // Count # of runs of 1 (subtract 1) //HANDLE_CRC (1 bit) andi a0, a3, 1 c.addi a0, -1 c.and a0, a4 c.srli a3, 1 c.xor a3, a0 c.srli a2, 1; // shift a2 down by 1 ori a2, a2, 0x80 c.beqz s0, handle_bit_stuff; HANDLE_NEXT_BYTE(is_end_of_byte, beqz) c.nop // Need extra delay here because we need more time if it's end-of-byte. c.nop c.nop c.bnez s1, bit_process // + 4 cycles c.j done_usb_message handle_bit_stuff: // We want to wait a little bit, then read another byte, and make // sure everything is well, before heading back into the main loop // Debug blip HANDLE_NEXT_BYTE(not_is_end_of_byte_and_bit_stuffed, bnez) HANDLE_EOB_YES not_is_end_of_byte_and_bit_stuffed: DEBUG_TICK_MARK c.lw a0, INDR_OFFSET(a5); c.andi a0, USB_DMASK; c.beqz a0, se0_complete c.xor a0, a1; c.xor a1, a0; // Recover a1, for next cycle. // If A0 is a 0 then that's bad, we just did a bit stuff // and A0 == 0 means there was no signal transition c.beqz a0, done_usb_message // Reset bit stuff, delay, then continue onto the next actual bit c.li s0, 6; c.nop; nx6p3delay( 2, a0 ) c.bnez s1, bit_process // + 4 cycles .balign 4 se0_complete: // This is triggered when we finished getting a packet. andi a0, s1, 7; // Make sure we received an even number of bytes. c.bnez a0, done_usb_message // Special: handle ACKs? // Now we have to decide what we're doing based on the // packet type. addi a1, sp, DATA_PTR_OFFSET XW_C_LBU(a0, a1, 0); //lbu a0, 0(a1) c.addi a1, 1 // 0010 => 01001011 => ACK // 0011 => 11000011 => DATA0 // 1011 => 11010010 => DATA1 // 1001 => 10010110 => PID IN // 0001 => 10000111 => PID_OUT // 1101 => 10110100 => SETUP (OK) // a0 contains first 4 bytes. la ra, done_usb_message_in // Common return address for all function calls. // For ACK don't worry about CRC. addi a5, a0, -0b01001011 RESTORE_DEBUG_MARKER(48) // restore x4 for whatever in C land. la a4, rv003usb_internal_data // ACK doesn't need good CRC. c.beqz a5, usb_pid_handle_ack // Next, check for tokens. c.bnez a3, crc_for_tokens_would_be_bad_maybe_data may_be_a_token: // Our CRC is 0, so we might be a token. // Do token-y things. XW_C_LHU( a2, a1, 0 ) andi a0, a2, 0x7f // addr c.srli a2, 7 c.andi a2, 0xf // endp li s0, ENDPOINTS bgeu a2, s0, done_usb_message // Make sure < ENDPOINTS c.beqz a0, yes_check_tokens // Otherwise, we might have our assigned address. XW_C_LBU(s0, a4, MY_ADDRESS_OFFSET_BYTES); // lbu s0, MY_ADDRESS_OFFSET_BYTES(a4) bne s0, a0, done_usb_message // addr != 0 && addr != ours. yes_check_tokens: addi a5, a5, (0b01001011-0b10000111) c.beqz a5, usb_pid_handle_out c.addi a5, (0b10000111-0b10010110) c.beqz a5, usb_pid_handle_in c.addi a5, (0b10010110-0b10110100) c.beqz a5, usb_pid_handle_setup c.j done_usb_message_in // CRC is nonzero. (Good for Data packets) crc_for_tokens_would_be_bad_maybe_data: li s0, 0xb001 // UGH: You can't use the CRC16 in reverse :( c.sub a3, s0 c.bnez a3, done_usb_message_in // Good CRC!! sub a3, t2, a1 //a3 = # of bytes read.. c.addi a3, 1 addi a5, a5, (0b01001011-0b11000011) c.li a2, 0 c.beqz a5, usb_pid_handle_data c.addi a5, (0b11000011-0b11010010) c.li a2, 1 c.beqz a5, usb_pid_handle_data done_usb_message: done_usb_message_in: lw s0, 24(sp) lw s1, 28(sp) lw t0, 32(sp) lw t1, 36(sp) lw t2, 40(sp) lw ra, 52(sp) ret_from_se0: lw s1, 28(sp) RESTORE_DEBUG_MARKER(48) lw a2, 8(sp) lw a3, 12(sp) lw a4, 16(sp) lw a1, 4(sp) interrupt_complete: // Acknowledge interrupt. // EXTI->INTFR = 1<<4 c.j 1f; 1: // Extra little bit of delay to make sure we don't accidentally false fire. la a5, EXTI_BASE + 20 li a0, (1<<USB_PIN_DM) sw a0, 0(a5) // Restore stack. lw a0, 0(sp) lw a5, 20(sp) addi sp,sp,80 mret /////////////////////////////////////////////////////////////////////////////// // High level functions. #ifdef RV003USB_OPTIMIZE_FLASH /* void usb_pid_handle_ack( uint32_t dummy, uint8_t * data, uint32_t dummy1, uint32_t dummy2, struct rv003usb_internal * ist ) { struct usb_endpoint * e = &ist->eps[ist->current_endpoint]; e->toggle_in = !e->toggle_in; e->count++; return; } */ usb_pid_handle_ack: c.lw a2, 0(a4) //ist->current_endpoint -> endp; c.slli a2, 5 c.add a2, a4 c.addi a2, ENDP_OFFSET // usb_endpoint eps[ENDPOINTS]; c.lw a0, (EP_TOGGLE_IN_OFFSET)(a2) // toggle_in=!toggle_in c.li a1, 1 c.xor a0, a1 c.sw a0, (EP_TOGGLE_IN_OFFSET)(a2) c.lw a0, (EP_COUNT_OFFSET)(a2) // count_in c.addi a0, 1 c.sw a0, (EP_COUNT_OFFSET)(a2) c.j done_usb_message_in /* //Received a setup for a specific endpoint. void usb_pid_handle_setup( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) { ist->current_endpoint = endp; struct usb_endpoint * e = &ist->eps[endp]; e->toggle_out = 0; e->count = 0; e->toggle_in = 1; ist->setup_request = 1; }*/ usb_pid_handle_setup: c.sw a2, 0(a4) // ist->current_endpoint = endp c.li a1, 1 c.sw a1, SETUP_REQUEST_OFFSET(a4) //ist->setup_request = 1; c.slli a2, 3+2 c.add a2, a4 c.sw a1, (ENDP_OFFSET+EP_TOGGLE_IN_OFFSET)(a2) //e->toggle_in = 1; c.li a1, 0 c.sw a1, (ENDP_OFFSET+EP_COUNT_OFFSET)(a2) //e->count = 0; c.sw a1, (ENDP_OFFSET+EP_OPAQUE_OFFSET)(a2) //e->opaque = 0; c.sw a1, (ENDP_OFFSET+EP_TOGGLE_OUT_OFFSET)(a2) //e->toggle_out = 0; c.j done_usb_message_in #endif //We need to handle this here because we could have an interrupt in the middle of a control or big transfer. //This will correctly swap back the endpoint. usb_pid_handle_out: //void usb_pid_handle_out( uint32_t addr, uint8_t * data, uint32_t endp, uint32_t unused, struct rv003usb_internal * ist ) //sb a2, 0(a4) //ist->current_endpoint = endp; XW_C_SB( a2, a4, 0 ); // current_endpoint = endp c.j done_usb_message_in handle_se0_keepalive: // In here, we want to do smart stuff with the // 1ms tick. la a0, SYSTICK_CNT la a4, rv003usb_internal_data c.lw a1, LAST_SE0_OFFSET(a4) //last cycle count last_se0_cyccount c.lw a2, 0(a0) //this cycle count c.sw a2, LAST_SE0_OFFSET(a4) //store it back to last_se0_cyccount c.sub a2, a1 c.sw a2, DELTA_SE0_OFFSET(a4) //record delta_se0_cyccount li a1, 48000 c.sub a2, a1 // This is our deviance from 48MHz. // Make sure we aren't in left field. li a5, 4000 bge a2, a5, ret_from_se0 li a5, -4000 blt a2, a5, ret_from_se0 c.lw a1, SE0_WINDUP_OFFSET(a4) // load windup se0_windup c.add a1, a2 c.sw a1, SE0_WINDUP_OFFSET(a4) // save windup // No further adjustments beqz a1, ret_from_se0 // 0x40021000 = RCC.CTLR la a4, 0x40021000 lw a0, 0(a4) srli a2, a0, 3 // Extract HSI Trim. andi a2, a2, 0b11111 li a5, 0xffffff07 and a0, a0, a5 // Mask off non-HSI // Decimate windup - use as HSIrim. neg a1, a1 srai a2, a1, 9 addi a2, a2, 16 // add hsi offset. // Put trim in place in register. slli a2, a2, 3 or a0, a0, a2 sw a0, 0(a4) j ret_from_se0 ////////////////////////////////////////////////////////////////////////////// // SEND DATA ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// .balign 4 //void usb_send_empty( uint32_t token ); usb_send_empty: c.mv a3, a0 la a0, always0 li a1, 2 c.mv a2, a1 //void usb_send_data( uint8_t * data, uint32_t length, uint32_t poly_function, uint32_t token ); usb_send_data: addi sp,sp,-16 sw s0, 0(sp) sw s1, 4(sp) la a5, USB_GPIO_BASE // ASAP: Turn the bus around and send our preamble + token. c.lw a4, CFGLR_OFFSET(a5) li s1, ~((0b1111<<(USB_PIN_DP*4)) | (0b1111<<(USB_PIN_DM*4))) and a4, s1, a4 // Convert D+/D- into 2MHz outputs li s1, ((0b0010<<(USB_PIN_DP*4)) | (0b0010<<(USB_PIN_DM*4))) or a4, s1, a4 li s1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) c.sw s1, BSHR_OFFSET(a5) //00: Universal push-pull output mode c.sw a4, CFGLR_OFFSET(a5) li t1, (1<<USB_PIN_DP) | (1<<(USB_PIN_DM+16)) | (1<<USB_PIN_DM) | (1<<(USB_PIN_DP+16)); SAVE_DEBUG_MARKER( 8 ) // Save off our preamble and token. c.slli a3, 7 //Put token further up so it gets sent later. ori s0, a3, 0x40 li t0, 0x0000 c.bnez a2, done_poly_check li t0, 0xa001 li a2, 0xffff done_poly_check: c.slli a1, 3 // bump up one extra to be # of bits mv t2, a1 // t0 is our polynomial // a2 is our running CRC. // a3 is our token. DEBUG_TICK_SETUP c.li a4, 6 // reset bit stuffing. c.li a1, 15 // 15 bits. //c.nop; c.nop; c.nop; c.j pre_and_tok_send_inner_loop //////////////////////////////////////////////////////////////////////////// // Send preamble + token .balign 4 pre_and_tok_send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.srli s0, 1 // Shift down into the next bit. c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.addi a4, -1 c.bnez a3, pre_and_tok_send_one_bit //pre_and_tok_send_one_bit: //Send 0 bit. (Flip) // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. // DO NOT flip. Allow a4 to increment. // Deliberately unaligned for timing purposes. .balign 4 pre_and_tok_send_one_bit: sw s1, BSHR_OFFSET(a5) //Bit stuffing doesn't happen. c.addi a1, -1 c.beqz a1, pre_and_tok_done_sending_data nx6p3delay( 2, a3 ); c.nop; // Free time! c.j pre_and_tok_send_inner_loop .balign 4 pre_and_tok_done_sending_data: //////////////////////////////////////////////////////////////////////////// // We have very little time here. Just enough to do this. //Restore size. mv a1, t2//lw a1, 12(sp) c.beqz a1, no_really_done_sending_data //No actual payload? Bail! c.addi a1, -1 // beqz t2, no_really_done_sending_data bnez t0, done_poly_check2 li a2, 0xffff done_poly_check2: // t0 is used for CRC // t1 is free // t2 is a backup of size. // s1 is our last "state" // bit 0 is last "physical" state, // // s0 is our current "bit" / byte / temp. // a0 is our data // a1 is is our length // a2 our CRC // a3 is TEMPORARY // a4 is used for bit stuffing. // a5 is the output address. //xor s1, s1, t1 //c.sw s1, BSHR_OFFSET(a5) // This creates a preamble, which is alternating 1's and 0's // and then it sets the same state. // li s0, 0b10000000 // c.j send_inner_loop .balign 4 load_next_byte: // CH32v003 has the XW extension. // this replaces: lb s0, 0(a0) XW_C_LBU(s0, a0, 0); //lb s0, 0(a0) // .long 0x00150513 // addi a0, a0, 1 (For alignment's sake) c.addi a0, 1 send_inner_loop: /* High-level: * extract the LSB from s0 * If it's 0, we FLIP the USB pin state. * If it's 1, we don't flip. * Regardless of the state, we still compute CRC. * We have to decrement our bit stuffing index. * If it is 0, we can reset our bit stuffing index. */ // a3 is now the lsb of s0 (the 'next bit' to read out) c.mv a3, s0 c.andi a3, 1 // If a3 is 0, we should FLIP // if a3 is 1, we should NOT flip. c.beqz a3, send_zero_bit c.srli s0, 1 // Shift down into the next bit. //send_one_bit: //HANDLE_CRC (1 bit) andi a3, a2, 1 c.addi a3, -1 and a3, a3, t0 c.srli a2, 1 c.xor a2, a3 c.addi a4, -1 c.beqz a4, insert_stuffed_bit c.j cont_after_jump //Send 0 bit. (Flip) .balign 4 send_zero_bit: c.srli s0, 1 // Shift down into the next bit. // Handle CRC (0 bit) // a2 is our running CRC // a3 is temp // t0 is polynomial. // XXX WARNING: this was by https://github.com/cnlohr/rv003usb/issues/7 // TODO Check me! slli a3,a2,31 // Put a3s LSB into a0s MSB c.srai a3,31 // Copy MSB into all other bits // Flip s1 (our bshr setting) by xoring it. // 10.....01 // 11.....11 (xor with) // 01.....10 xor s1, s1, t1 sw s1, BSHR_OFFSET(a5) c.li a4, 6 // reset bit stuffing. // XXX XXX CRC down here to make bit stuffing timings line up. c.srli a2,1 and a3,a3,t0 c.xor a2,a3 .balign 4 cont_after_jump: send_end_bit_complete: c.beqz a1, done_sending_data andi a3, a1, 7 c.addi a1, -1 c.beqz a3, load_next_byte // Wait an extra few cycles. c.j 1f; 1: c.j send_inner_loop .balign 4 done_sending_data: // BUT WAIT!! MAYBE WE NEED TO CRC! beqz t0, no_really_done_sending_data srli t0, t0, 8 // reset poly - we don't want it anymore. li a1, 7 // Load 8 more bits out beqz t0, send_inner_loop //Second CRC byte // First CRC byte not s0, a2 // get read to send out the CRC. c.j send_inner_loop .balign 4 no_really_done_sending_data: // c.bnez a2, poly_function TODO: Uncomment me! nx6p3delay( 2, a3 ); // Need to perform an SE0. li s1, (1<<(USB_PIN_DM+16)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) nx6p3delay( 7, a3 ); li s1, (1<<(USB_PIN_DM)) | (1<<(USB_PIN_DP+16)) c.sw s1, BSHR_OFFSET(a5) lw s1, CFGLR_OFFSET(a5) // Convert D+/D- into inputs. li a3, ~((0b11<<(USB_PIN_DP*4)) | (0b11<<(USB_PIN_DM*4))) and s1, a3, s1 // 01: Floating input mode. li a3, ((0b01<<(USB_PIN_DP*4+2)) | (0b01<<(USB_PIN_DM*4+2))) or s1, a3, s1 sw s1, CFGLR_OFFSET(a5) lw s0, 0(sp) lw s1, 4(sp) RESTORE_DEBUG_MARKER( 8 ) addi sp,sp,16 ret .balign 4 // TODO: This seems to be either 222 or 226 (not 224) in cases. // It's off by 2 clock cycles. Probably OK, but, hmm. insert_stuffed_bit: nx6p3delay(3, a3) xor s1, s1, t1 c.li a4, 6 // reset bit stuffing. c.nop c.nop sw s1, BSHR_OFFSET(a5) c.j send_end_bit_complete ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifdef USE_TINY_BOOT // Absolutey bare-bones hardware initialization for bringing the chip up, // setting up the envrionment for C, switching to 48MHz clock, and booting // into main... as well as providing EXTI7_0_IRQHandler jump at interrupt .section .init .global InterruptVector InterruptVector: .align 2 .option push .option norelax la gp, __global_pointer$ mv sp, gp //_eusrstack #if __GNUC__ > 10 .option arch, +zicsr #endif li a0, 0x80 csrw mstatus, a0 c.li a0, 3 csrw mtvec, a0 addi a0, gp, -2048 // will be 0x20000000 c.li a4, 0 1: c.sw a4, 0(a0) // Clear RAM c.addi a0, 4 blt a0, gp, 1b // Iterate over RAM until it's cleared. 2: //XXX WARNING: NO .DATA SECTION IS AVAILABLE HERE! /* SystemInit48HSI */ la a2, RCC_BASE la a3, FLASH_R_BASE li a1, 0x00000001 | 0x01000000 | 0x80 /* RCC->CTLR RCC_HSION | RCC_PLLON | ((HSITRIM) << 3) */ c.sw a1, 0(a2) c.li a1, 0x01 /* FLASH_ACTLR_LATENCY_1 */ c.sw a1, 0(a3) /* FLASH->ACTLR = FLASH_ACTLR_LATENCY_1 */ c.li a1, 0x00000002 /* RCC->CFGR0 = RCC_SW_PLL */ c.sw a1, 4(a2) la a1, main csrw mepc, a1 .option pop mret // CAREFUL THIS MUST BE EXACTLY AT 0x50 . = 0x52 // Weird... I don't know why this has to be 0x52, for it to be at 0x50. .word EXTI7_0_IRQHandler /* EXTI Line 7..0 */ always0: .byte 0x00 // Automatically expands out to 4 bytes. .align 0 .balign 0 #else .balign 4 always0: .word 0x00 #endif
wagiminator/C64-Collection
9,428
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/mouse.s
;-------------------------------------------------------------------- ; Atari 8-bit mouse routines -- 05/07/2000 Freddy Offenga ; Some changes by Christian Groessler, Ullrich von Bassewitz ; ; The following devices are supported: ; - Atari trak-ball ; - ST mouse ; - Amiga mouse ; ; Mouse checks are done in the timer 1 IRQ and the mouse arrow is ; drawn in player 0 during the vertical blank ;-------------------------------------------------------------------- .export _mouse_init, _mouse_done, _mouse_box .export _mouse_show, _mouse_hide, _mouse_move .export _mouse_buttons, _mouse_pos, _mouse_info .constructor initmouse,27 .import popax .importzp ptr1 .include "atari.inc" TRAK_BALL = 0 ; device Atari trak-ball ST_MOUSE = 1 ; device ST mouse AMIGA_MOUSE = 2 ; device Amiga mouse MAX_TYPE = 3 ; first illegal device type ; the default values force the mouse cursor inside the test screen (no access to border) defxmin = 48 ; default x minimum defymin = 31 ; default y minimum defxmax = 204 ; default x maximum defymax = 211 ; default y maximum pmsize = 16 ; y size pm shape xinit = defxmin ; init. x pos. yinit = defymin ; init. y pos. ;-------------------------------------------------------------------- ; reserve memory for the mouse pointer initmouse: lda APPMHI+1 and #%11111000 ; make 2k aligned sec sbc #%00001000 ; reserve 2k tax adc #3 ; add 4 (C = 1) sta mouse_pm0 lda #0 sta APPMHI stx APPMHI+1 rts ;-------------------------------------------------------------------- ; Initialize mouse routines ; void __fastcall__ mouse_init (unsigned char type); _mouse_init: cmp #MAX_TYPE+1 ; Check for a valid type bcc setup ifail: lda #0 ; init. failed tax rts setup: tax lda lvectab,x sta mouse_vec+1 lda hvectab,x sta mouse_vec+2 jsr pminit lda VTIMR1 sta old_t1 lda VTIMR1+1 sta old_t1+1 lda #<t1_vec sta VTIMR1 lda #>t1_vec sta VTIMR1+1 lda #%00000001 sta AUDCTL lda #0 sta AUDC1 lda #15 sta AUDF1 sta STIMER sei lda POKMSK ora #%00000001 ; timer 1 enable sta POKMSK sta IRQEN cli lda VVBLKI sta vbi_jmp+1 lda VVBLKI+1 sta vbi_jmp+2 lda #6 ldy #<vbi ldx #>vbi jsr SETVBV lda #$C0 sta NMIEN ldx #0 lda #1 sta mouse_off rts ;-------------------------------------------------------------------- ; Finish mouse routines ; void mouse_done(void) _mouse_done: sei lda POKMSK and #%11111110 ; timer 1 disable sta IRQEN sta POKMSK cli lda old_t1 sta VTIMR1 lda old_t1+1 sta VTIMR1+1 lda #$40 sta NMIEN lda #6 ldy vbi_jmp+1 ldx vbi_jmp+2 jsr SETVBV ldx #0 stx GRACTL stx HPOSP0 inx stx mouse_off rts ;-------------------------------------------------------------------- ; Set mouse limits ; void __fastcall__ mouse_box(int xmin, int ymin, int xmax, int ymax) _mouse_box: sta ymax jsr popax ; always ignore high byte sta xmax jsr popax sta ymin jsr popax sta xmin rts ;-------------------------------------------------------------------- ; Set mouse position ; void __fastcall__ mouse_move(int xpos, int ypos) _mouse_move: sta mousey ; always ignore high byte jsr popax sta mousex rts ;-------------------------------------------------------------------- ; Show mouse arrow ; void mouse_show(void) _mouse_show: lda mouse_off ; Already on? beq @L1 dec mouse_off @L1: rts ;-------------------------------------------------------------------- ; Hide mouse arrow ; void mouse_hide(void) _mouse_hide: inc mouse_off rts ;-------------------------------------------------------------------- ; Ask mouse button ; unsigned char mouse_buttons(void) _mouse_buttons: ldx #0 lda STRIG0 bne nobut ; lda #14 ;??? sta COLOR1 lda #1 rts nobut: txa rts ;-------------------------------------------------------------------- ; Get the mouse position ; void mouse_pos (struct mouse_pos* pos); _mouse_pos: sta ptr1 stx ptr1+1 ; Store argument pointer ldy #0 lda mousex ; X position sta (ptr1),y lda #0 iny sta (ptr1),y lda mousey ; Y position iny sta (ptr1),y lda #0 iny sta (ptr1),y rts ;-------------------------------------------------------------------- ; Get the mouse position and button information ; void mouse_info (struct mouse_info* info); _mouse_info: ; We're cheating here to keep the code smaller: The first fields of the ; mouse_info struct are identical to the mouse_pos struct, so we will just ; call _mouse_pos to initialize the struct pointer and fill the position ; fields. jsr _mouse_pos ; Fill in the button state jsr _mouse_buttons ; Will not touch ptr1 ldy #4 sta (ptr1),y rts ;-------------------------------------------------------------------- ; Atari trak-ball check, A,Y = 4-bit port value trak_check: eor oldval and #%00001000 beq horiz tya and #%00000100 beq mmup inc mousey bne horiz mmup: dec mousey horiz: tya eor oldval and #%00000010 beq mmexit tya and #%00000001 beq mmleft inc mousex bne mmexit mmleft: dec mousex mmexit: sty oldval rts ;-------------------------------------------------------------------- ; ST mouse check, A,Y = 4-bit port value st_check: and #%00000011 ora dumx tax lda sttab,x bmi nxst beq xist dec mousex ; 1 = left bne nxst xist: inc mousex ; 0 = right nxst: tya and #%00001100 ora dumy tax lda sttab,x bmi nyst bne yst dec mousey ; 0 = up bne nyst yst: inc mousey ; 1 = down ; store old readings nyst: tya and #%00000011 asl asl sta dumx tya and #%00001100 lsr lsr sta dumy rts ;-------------------------------------------------------------------- ; Amiga mouse check, A,Y = 4-bit port value amiga_check: lsr and #%00000101 ora dumx tax lda amitab,x bmi nxami bne xiami dec mousex ; 0 = left bne nxami xiami: inc mousex ; 1 = right nxami: tya and #%00000101 ora dumy tax lda amitab,x bmi nyami bne yiami dec mousey ; 0 = up bne nyami yiami: inc mousey ; 1 = down ; store old readings nyami: tya and #%00001010 sta dumx tya and #%00000101 asl sta dumy rts ;-------------------------------------------------------------------- ; timer 1 IRQ routine - check mouse t1_vec: tya pha txa pha .ifdef DEBUG lda RANDOM sta COLBK ; debug .endif lda PORTA tay mouse_vec: jsr st_check ; will be modified; won't be ROMmable pla tax pla tay pla rti ;-------------------------------------------------------------------- ; VBI - check mouse limits and display mouse arrow vbi: lda mousex cmp xmin bcs ok1 ; xmin <= mousex lda xmin sta mousex ok1: lda mousey cmp ymin bcs ok2 ; ymin <= mousey lda ymin sta mousey ok2: lda xmax cmp mousex bcs ok3 ; xmax >= mousex lda xmax sta mousex ok3: lda ymax cmp mousey bcs ok4 ; ymax >= mousey lda ymax sta mousey ok4: jsr clrpm lda mouse_off beq mon lda #0 sta HPOSP0 beq moff mon: jsr drwpm lda mousey sta omy lda #3 moff: sta GRACTL vbi_jmp: jmp SYSVBV ; will be modified; won't be ROMmable ;-------------------------------------------------------------------- ; initialize mouse pm pminit: lda mouse_pm0 sta mpatch1+2 sta mpatch2+2 sta mpatch3+2 ldx #0 txa mpatch1: clpm: sta $1000,x ; will be patched inx bne clpm lda mouse_pm0 sec sbc #4 sta PMBASE lda #62 sta SDMCTL lda #1 sta GPRIOR lda #0 sta PCOLR0 sta SIZEP0 rts ;-------------------------------------------------------------------- ; draw new mouse pm drwpm: lda mousex sta HPOSP0 lda mousey tax ldy #0 fmp2: lda mskpm,y mpatch2: sta $1000,x ; will be patched inx iny cpy #pmsize bne fmp2 rts ;-------------------------------------------------------------------- ; clear old mouse pm clrpm: lda omy tax ldy #0 tya mpatch3: fmp1: sta $1000,x ; will be patched inx iny cpy #pmsize bne fmp1 rts ;-------------------------------------------------------------------- .rodata ; mouse arrow - pm shape mskpm: .byte %00000000 .byte %10000000 .byte %11000000 .byte %11000000 .byte %11100000 .byte %11100000 .byte %11110000 .byte %11100000 .byte %11100000 .byte %00100000 .byte %00100000 .byte %00110000 .byte %00110000 .byte %00000000 .byte %00000000 .byte %00000000 ; ST mouse lookup table sttab: .byte $FF,$01,$00,$01 .byte $00,$FF,$00,$01 .byte $01,$00,$FF,$00 .byte $01,$00,$01,$FF ; Amiga mouse lookup table amitab: .byte $FF,$01,$00,$FF .byte $00,$FF,$FF,$01 .byte $01,$FF,$FF,$00 .byte $FF,$00,$01,$FF ; Device vectors lvectab: .byte <trak_check, <st_check, <amiga_check hvectab: .byte >trak_check, >st_check, >amiga_check ; default values xmin: .byte defxmin ymin: .byte defymin xmax: .byte defxmax ymax: .byte defymax mousex: .byte xinit mousey: .byte yinit ;-------------------------------------------------------------------- .bss ; Misc. vars old_t1: .res 2 ; old timer interrupt vector oldval: .res 1 ; used by trakball routines dumx: .res 1 dumy: .res 1 omy: .res 1 ; old y pos mouse_off: .res 1 mouse_pm0: .res 1
wagiminator/C64-Collection
3,576
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/lseek.s
; ; Christian Groessler, May 2002 ; ; this file provides the lseek() function ; ; off_t __fastcall__ lseek(int fd, off_t offset, int whence); ; .export _lseek .import incsp6,__oserror .import __inviocb,ldax0sp,ldaxysp,fdtoiocb .import __dos_type .import fd_table .importzp sreg,ptr1,ptr2,ptr3,ptr4 .importzp tmp1,tmp2,tmp3 .include "atari.inc" .include "errno.inc" .include "fd.inc" ; seeking not supported, return -1 and ENOSYS errno value no_supp:jsr incsp6 lda #<ENOSYS jsr __seterrno ; set __errno, return zero in A sta __oserror lda #$FF tax sta sreg sta sreg+1 rts parmerr: iocberr:jsr incsp6 ldx #255 stx sreg stx sreg+1 jmp __inviocb ; lseek() entry point .proc _lseek cpx #0 ; sanity check whence parameter bne parmerr cmp #3 ; valid values are 0..2 bcs parmerr sta tmp1 ; remember whence ldy #5 jsr ldaxysp ; get fd jsr fdtoiocb ; convert to iocb in A, fd_table index in X bmi iocberr sta tmp3 ; remember iocb jsr chk_supp ; check, whether seeking is supported by DOS/Disk bcc no_supp ldx tmp1 ; whence beq cur dex beq end ; SEEK_SET dex stx ptr3 stx ptr3+1 stx ptr4 stx ptr4+1 beq cont ; SEEK_CUR cur: ldx tmp3 lda #38 ; NOTE sta ICCOM,x jsr CIOV ; read it bmi xxerr l01: lda ICAX3,x ; low byte of position sta ptr3 lda ICAX4,x ; med byte of position sta ptr3+1 lda ICAX5,x ; high byte of position sta ptr4 lda #0 sta ptr4+1 beq cont ; SEEK_END end: ldx tmp3 lda #39 ; get file size sta ICCOM,x jsr CIOV bpl l01 ; error returned from CIO xxerr: sty __oserror bmi iocberr ; check for offset 0, SEEK_CUR (get current position) cont: ldy #3 jsr ldaxysp ; get upper word sta ptr1 stx ptr1+1 jsr ldax0sp ; get lower word stx tmp2 ora tmp2 ora ptr1 ora ptr1+1 bne seek lda tmp1 ; whence (0 = SEEK_CUR) bne seek ; offset 0, SEEK_CUR: return current fp ret: jsr incsp6 lda ptr4+1 sta sreg+1 lda ptr4 sta sreg ldx ptr3+1 lda ptr3 .if 0 ; return exactly the position DOS has ldx tmp3 lda #38 ; NOTE sta ICCOM,x jsr CIOV ; read it bmi xxerr lda #0 sta sreg+1 lda ICAX5,x ; high byte of position sta sreg lda ICAX3,x ; low byte of position pha lda ICAX4,x ; med byte of position tax pla .endif rts parmerr1: jmp parmerr ; we have to call POINT seek: jsr ldax0sp ; get lower word of new offset clc adc ptr3 sta ptr3 txa adc ptr3+1 sta ptr3+1 lda ptr1 adc ptr4 sta ptr4 lda ptr1+1 adc ptr4+1 sta ptr4+1 bne parmerr1 ; resulting value too large ldx tmp3 ; IOCB lda ptr3 sta ICAX3,x lda ptr3+1 sta ICAX4,x lda ptr4 sta ICAX5,x lda #37 ;POINT sta ICCOM,x jsr CIOV bpl ret bmi xxerr .endproc ; check, whether seeking is supported ; tmp3: iocb ; X: index into fd_table ; ; On non-SpartaDOS, seeking is not supported. ; We check, whether CIO function 39 (get file size) returns OK. ; If yes, NOTE and POINT work with real file offset. ; If not, NOTE and POINT work with the standard ScNum/Offset values. ; We remember a successful check in fd_table.ft_flag, bit 3. chk_supp: lda fd_table+ft_flag,x and #8 bne supp ; do the test lda __dos_type cmp #SPARTADOS bne ns1 txa pha lda DOS+1 ; get SpartaDOS version cmp #$40 bcs supp1 ; SD-X (ver 4.xx) supports seeking on all disks ldx tmp3 ; iocb to use lda #39 ; get file size sta ICCOM,x jsr CIOV bmi notsupp ; error code ? should be 168 (invalid command) ; seeking is supported on this DOS/Disk combination supp1: pla tax lda #8 ora fd_table+ft_flag,x sta fd_table+ft_flag,x supp: sec rts notsupp:pla ns1: clc rts
wagiminator/C64-Collection
1,437
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/savevec.s
; ; save and restore system vectors ; originally by Mark Keates ; ; void _save_vecs(void); ; void _rest_vecs(void); ; .export __save_vecs,__rest_vecs .include "atari.inc" .bss old_dli: .res 2 old_dlist: .res 2 old_vbi: .res 2 old_vbd: .res 2 old_gra: .res 1 old_dma: .res 1 old_prior: .res 1 old_cols: .res 8 old_set: .res 1 old_rmargin: .res 1 ; lmargin saved in startup code .code .proc __save_vecs lda VDSLST sta old_dli lda VDSLST+1 sta old_dli+1 lda SDLSTL sta old_dlist lda SDLSTL+1 sta old_dlist+1 lda VVBLKI sta old_vbi lda VVBLKI+1 sta old_vbi+1 lda VVBLKD sta old_vbd lda VVBLKD+1 sta old_vbd+1 lda GRACTL sta old_gra lda SDMCTL sta old_dma lda GPRIOR sta old_prior lda CHBAS sta old_set lda RMARGN sta old_rmargin ldy #7 SETUP1: lda PCOLR0,y sta old_cols,y dey bpl SETUP1 rts .endproc .proc __rest_vecs lda #6 ldx old_vbi+1 ldy old_vbi jsr SETVBV lda #7 ldx old_vbd+1 ldy old_vbd jsr SETVBV lda old_dli sta VDSLST lda old_dli+1 sta VDSLST+1 lda old_dlist sta SDLSTL lda old_dlist+1 sta SDLSTL+1 lda old_gra sta GRACTL lda old_prior sta GPRIOR lda old_dma sta SDMCTL lda old_set sta CHBAS lda old_rmargin sta RMARGN lda #$FF sta CH ldy #7 SETUP2: lda old_cols,Y sta PCOLR0,Y dey bpl SETUP2 rts .endproc
wagiminator/C64-Collection
2,407
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/ucase_fn.s
; ; Christian Groessler, Dec-2001 ; ; ucase_fn ; helper routine to convert a string (file name) to uppercase ; used by open.s and remove.s ; ; Calling parameters: ; AX - points to filename ; Return parameters: ; C - 0/1 for OK/Error (filename too long) ; AX - points to uppercased version of the filename on the stack ; tmp3 - amount of bytes used on the stack (needed for cleanup) ; Uses: ; ptr4 - scratch pointer used to remember original AX pointer ; ; .include "atari.inc" .ifdef DEFAULT_DEVICE .importzp tmp2 .ifdef DYNAMIC_DD .import __defdev .endif .endif .importzp tmp3,ptr4,sp .import _strupr,subysp .export ucase_fn .proc ucase_fn ; we make sure that the filename doesn't contain lowercase letters ; we copy the filename we got onto the stack, uppercase it and use this ; one to open the iocb ; we're using tmp3, ptr4 ; save the original pointer sta ptr4 stx ptr4+1 .ifdef DEFAULT_DEVICE ldy #1 sty tmp2 ; initialize flag: device present in passed string lda #':' cmp (ptr4),y beq hasdev iny cmp (ptr4),y beq hasdev sta tmp2 ; set flag: no device in passed string hasdev: .endif ; now we need the length of the name ldy #0 loop: lda (ptr4),y beq str_end cmp #ATEOL ; we also accept Atari EOF char as end of string beq str_end iny bne loop ; not longer than 255 chars (127 real limit) toolong:sec ; indicate error rts str_end:iny ; room for terminating zero cpy #128 ; we only can handle lenght < 128 bcs toolong sty tmp3 ; save size jsr subysp ; make room on the stack ; copy filename to the temp. place on the stack lda #0 ; end-of-string sta (sp),y ; Y still contains length + 1 dey loop2: lda (ptr4),y sta (sp),y dey bpl loop2 ; bpl: this way we only support a max. length of 127 .ifdef DEFAULT_DEVICE lda tmp2 cmp #1 ; was device present in passed string? beq hasdev2 ; yes, don't prepend something inc tmp3 ; no, prepend "D:" inc tmp3 ; adjust stack size used inc tmp3 ldy #3 jsr subysp ; adjust stack pointer ldy #2 lda #':' sta (sp),y ; insert ':' dey .ifdef DYNAMIC_DD lda __defdev+1 .else lda #'0'+DEFAULT_DEVICE .endif sta (sp),y ; insert device number dey lda #'D' sta (sp),y ; insert 'D' hasdev2: .endif ; uppercase the temp. filename ldx sp+1 lda sp jsr _strupr ; leave A and X pointing to the modified filename lda sp ldx sp+1 clc ; indicate success rts .endproc
wagiminator/C64-Collection
1,391
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/sysmkdir.s
; ; Initial version: Stefan Haubenthal, 2005-12-24 ; Some fixes: Christian Groessler, 2009-01-28 ; ; unsigned char _sysmkdir (const char* name, ...); ; for SpartaDOS and MYDOS ; .include "atari.inc" .include "errno.inc" .import addysp .import popax .import findfreeiocb .importzp tmp4 .ifdef UCASE_FILENAME .importzp tmp3 .import ucase_fn .endif .export __sysmkdir .proc __sysmkdir dey ; parm count < 2 shouldn't be needed to be... dey ; ...checked (it generates a C compiler warning) beq parmok ; branch if parameter count ok jsr addysp ; fix stack, throw away unused parameters parmok: jsr popax ; get name pha ; save input parameter txa pha jsr findfreeiocb beq iocbok ; we found one pla pla ; fix up stack lda #TMOF ; too many open files rts iocbok: stx tmp4 ; remember IOCB index pla tax pla ; get argument again .ifdef UCASE_FILENAME jsr ucase_fn bcc ucok1 lda #182 ; see oserror.s rts ucok1: .endif ; defined UCASE_FILENAME ldy tmp4 ; IOCB index sta ICBAL,y ; store pointer to filename txa sta ICBAH,y tya tax lda #42 sta ICCOM,x lda #8 sta ICAX1,x lda #0 sta ICAX2,x sta ICBLL,x sta ICBLH,x jsr CIOV .ifdef UCASE_FILENAME tya pha ldy tmp3 ; get size jsr addysp ; free used space on the stack pla tay .endif ; defined UCASE_FILENAME bmi cioerr lda #0 rts cioerr: tya rts .endproc ; __sysmkdir
wagiminator/C64-Collection
1,586
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/getdefdev.s
; ; Freddy Offenga & Christian Groessler, December 2004 ; ; function to get default device: char *_getdefdev(void); ; ; SpartaDOS: ; the ZCRNAME routine is only used to get the default drive because ; ZCRNAME has two disadvantages: ; 1. It will convert D: into D1: instead of Dn: (n = default drive) ; 2. It will give a 'no arguments' status if it detects something ; like Dn: (without filename). ; ; OS/A+ DOS: ; ZCRNAME is slightly different from SpartaDOS. It will convert D: ; into Dn: where n is the default drive. .include "atari.inc" .import __dos_type .export __getdefdev ; get default device (e.g. "D1:") .ifdef DYNAMIC_DD .export __defdev .endif ; Get default device (LBUF will be destroyed!!) __getdefdev: .ifdef DEFAULT_DEVICE lda #'0'+DEFAULT_DEVICE sta __defdev+1 .endif lda __dos_type ; which DOS? cmp #ATARIDOS beq finish cmp #MYDOS beq finish ldy #BUFOFF lda #0 sta (DOSVEC),y ; reset buffer offset ; Store dummy argument ldy #LBUF lda #'X' sta (DOSVEC),y iny lda #ATEOL sta (DOSVEC),y ; One extra store to avoid the buggy sequence from OS/A+ DOS: ; <D><RETURN><:> => drive number = <RETURN> iny sta (DOSVEC),y ; Create crunch vector ldy #ZCRNAME+1 lda (DOSVEC),y sta crvec+1 iny lda (DOSVEC),y sta crvec+2 crvec: jsr $FFFF ; will be set to crunch vector ; Get default device ldy #COMFNAM ; COMFNAM is always "Dn:" lda (DOSVEC),y sta __defdev iny lda (DOSVEC),y sta __defdev+1 ; Return pointer to default device finish: lda #<__defdev ldx #>__defdev rts .data ; Default device __defdev: .byte "D1:", 0
wagiminator/C64-Collection
2,913
C64_xu1541/software/tools/cc65-2.13.2/libsrc/atari/crt0.s
; ; Startup code for cc65 (ATARI version) ; ; Contributing authors: ; Mark Keates ; Freddy Offenga ; Christian Groessler ; .export _exit .export __STARTUP__ : absolute = 1 ; Mark as startup .constructor initsp, 26 .import initlib, donelib, callmain .import zerobss, pushax .import _main, __filetab, getfd .import __STARTUP_LOAD__, __ZPSAVE_LOAD__ .import __RESERVED_MEMORY__ .ifdef DYNAMIC_DD .import __getdefdev .endif .include "zeropage.inc" .include "atari.inc" .include "_file.inc" ; ------------------------------------------------------------------------ ; EXE header .segment "EXEHDR" .word $FFFF .word __STARTUP_LOAD__ .word __ZPSAVE_LOAD__ - 1 ; ------------------------------------------------------------------------ ; Actual code .segment "STARTUP" rts ; fix for SpartaDOS / OS/A+ ; they first call the entry point from AUTOSTRT and ; then the load addess (this rts here). ; We point AUTOSTRT directly after the rts. ; Real entry point: ; Save the zero page locations we need ldx #zpspace-1 L1: lda sp,x sta zpsave,x dex bpl L1 ; Clear the BSS data jsr zerobss ; setup the stack tsx stx spsave ; report memory usage lda APPMHI sta appmsav ; remember old APPMHI value lda APPMHI+1 sta appmsav+1 sec lda MEMTOP sbc #<__RESERVED_MEMORY__ sta APPMHI ; initialize our APPMHI value lda MEMTOP+1 sbc #>__RESERVED_MEMORY__ sta APPMHI+1 ; Call module constructors jsr initlib .ifdef DYNAMIC_DD jsr __getdefdev .endif ; set left margin to 0 lda LMARGN sta old_lmargin lda #0 sta LMARGN ; set keyb to upper/lowercase mode ldx SHFLOK stx old_shflok sta SHFLOK ; Initialize conio stuff lda #$FF sta CH ; set stdio stream handles lda #0 jsr getfd sta __filetab + (0 * .sizeof(_FILE)); setup stdin lda #0 jsr getfd sta __filetab + (1 * .sizeof(_FILE)); setup stdout lda #0 jsr getfd sta __filetab + (2 * .sizeof(_FILE)); setup stderr ; Push arguments and call main jsr callmain ; Call module destructors. This is also the _exit entry. _exit: jsr donelib ; Run module destructors ; Restore system stuff ldx spsave txs ; Restore stack pointer ; restore left margin lda old_lmargin sta LMARGN ; restore kb mode lda old_shflok sta SHFLOK ; restore APPMHI lda appmsav sta APPMHI lda appmsav+1 sta APPMHI+1 ; Copy back the zero page stuff ldx #zpspace-1 L2: lda zpsave,x sta sp,x dex bpl L2 ; turn on cursor inx stx CRSINH ; Back to DOS rts ; *** end of main startup code ; setup sp .segment "INIT" initsp: lda APPMHI sta sp lda APPMHI+1 sta sp+1 rts .segment "ZPSAVE" zpsave: .res zpspace .bss spsave: .res 1 appmsav: .res 1 old_shflok: .res 1 old_lmargin: .res 1 .segment "AUTOSTRT" .word RUNAD ; defined in atari.h .word RUNAD+1 .word __STARTUP_LOAD__ + 1