avrusb 18MHz port incl crc check

General discussions about V-USB, our firmware-only implementation of a low speed USB device on Atmel's AVR microcontrollers
Post Reply
habicht

avrusb 18MHz port incl crc check

Post by habicht » Wed Jan 21, 2009 12:18 pm

I modified the avrusb driver (the 20MHz version to be precise) to 18MHz. As I'm planning to use it in an environment where data integrity necessary I added an on-the-fly crc checker for data packets. I did this by using an rather fast table driven CRC algorithm and massive loop unrolling. So the code is somewhat blown up, without any user functions and with standard config it now has 2260 bytes.
Unfortunately I don't have a micro controller available right now so I was not able to test it in hardware.
If someone of you is willing to test and or use it feel free to do so. If you've found a bug, please inform me (see mail below). You may find a copy of my version (including the driver and a blank AVR Studio 4 project) at: http://5n07.it-htl.at/~habicht/ujtag.zip
All the documentation I wrote is inline, so just see usbdrvasm18.inc in usbdrv folder. I also did some changes ot asmcommon.inc
If you have any further questions or found bugs, e-mail at: crcavrusb@5n07.it-htl.at

habicht

Post by habicht » Sat Feb 07, 2009 8:19 pm

Hi!

Im debugging the 18MHz port right now. However is found some strange behavoir: in some cases the data-out packets of a setup transfer are one byte to short. In fact a se0 is detected at bit3 of the last expected byte (second crc byte). (As this byte is incomplete it is discarded) For testing purposes i modified usbProcessRx in usbdrv.c to accept this short packet. The strange thing is: it works, winXP is able to enumerate the device correctly.
I don't believe this is a hardware issue as packet before and after this strange one are ok.
Here is the debug-output (i modified it to show the received crc values).

Code: Select all

//start up sequence 
ff:
ff:
ff:
1d: 80 06 00 01 00 00 40 00 dd 94
20: 4b 12 01 10 01 ff 00 00 08 21 63
20: c3 c0 16 dc 05 03 01 01 02 ca ec
20: 4b 00 01 3f 8f
ff:
ff:
1d: 00 05 02 00 00 00 00 00 eb 16      // packet ok
20: 4b 00 00
1d: 80 06 00 01 00 00 12 00 e0 f4      // packet ok
20: 4b 12 01 10 01 ff 00 00 08 21 63
20: c3 c0 16 dc 05 03 01 01 02 ca ec
20: 4b 00 01 3f 8f
1d: 80 06 00 02 00 00 09 00 ae 04      // packet ok
20: 4b 09 02 12 00 01 01 00 80 0e b0
20: c3 32 c1 6a
1d: 80 06 00 02 00 00 2f 48 27          // packet is one byte to short (and the crc is strange)   
20: 4b 09 02 12 00 01 01 00 80 0e b0
20: c3 32 09 04 00 00 00 00 00 a5 bd
20: 4b 00 00 fe 4f
1d: 80 06 00 03 00 00 2f a0 26         // short packet
20: 4b 04 03 09 04 09 78
1d: 80 06 02 03 09 04 2f b8 dc         // short packet
20: 4b 0e 03 55 00 53 00 42 00 20 99
20: c3 61 00 73 00 70 00 c8 d1
1d: 80 06 00 03 00 00 2f a0 26         // short packet
20: 4b 04 03 09 04 09 78
1d: 80 06 02 03 09 04 2f b8 dc         // short packet
20: 4b 0e 03 55 00 53 00 42 00 20 99
20: c3 61 00 73 00 70 00 c8 d1



Here is my asm-receiver code, it is simmilar to the 12MHz version:

Code: Select all

/* Name: usbdrvasm18.inc
 * Project: AVR USB driver
 * Author: Jeroen Benschop
 * Mods by: Lukas Schrittwieser
 * Based on usbdrvasm16.inc from Christian Starkjohann
 * Creation Date: 2008-03-05
 * Mods added: 2009-01-20
 * Tabsize: 4
 * Copyright: (c) 2008 by Jeroen Benschop and OBJECTIVE DEVELOPMENT Software GmbH
 * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
 * Revision: $Id: usbdrvasm20.inc 692 2008-11-07 15:07:40Z cs $
 */

/* Do not link this file! Link usbdrvasm.S instead, which includes the
 * appropriate implementation!
 */

/*
General Description:
This file is the 18 MHz version of the asssembler part of the USB driver. It
requires a 18 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!
*/


#ifdef __IAR_SYSTEMS_ASM__
#define nextInst    $+2
#else
#define nextInst    .+0
#endif

;max stack usage: [ret(2), YL, SREG, YH, [sofError], bitcnt(x5), shift, x1, x2, x3, x4, cnt, ZL, ZH] = 14 bytes
;nominal frequency: 18 MHz -> 12 cycles per bit
; Numbers in brackets are clocks counted from center of last sync bit
; when instruction starts
;register use in receive loop to receive the data bytes:
; shift assembles the byte currently being received
; x1 holds the D+ and D- line state
; x2 holds the previous line state
; cnt holds the number of bytes left in the receive buffer
; x3 holds the higher crc byte (see algorithm below)
; x4 is used as temporary register for the crc algorithm
; x5 is used for unstaffing: when unstaffing the last received bit is inverted in shift (to prevent further
;    unstaffing calls. In the same time the corresponding bit in x5 is cleared to mark the bit as beening iverted
; zl lower crc value and crc table index
; zh used for crc table accesses

;--------------------------------------------------------------------------------------------------------------
; CRC mods:
;  table driven crc checker, Z points to table in prog space
;   ZL is the lower crc byte, x3 is the higher crc byte
;   x4 is used as temp register to store different results
;   the initialization of the crc register is not 0xFFFF but 0xFE54. This is because during the receipt of the
;   first data byte an virtual zero data byte is added to the crc register, this results in the correct initial
;   value of 0xFFFF at beginning of the second data byte before the first data byte is added to the crc
;   the magic number 0xFE54 results form the crc table: At tabH[0x54] = 0xFF = crcH (required) and
;   tabL[0x54] = 0x01  ->  crcL = 0x01 xor 0xFE = 0xFF
;  bitcnt is renamed to x5 and is used for unstaffing purposes, the unstaffing works like in the 12MHz version


;--------------------------------------------------------------------------------------------------------------
; CRC algorithm:
;   The crc register is formed by x3 (higher byte) and ZL (lower byte). The algorithm uses a 'reversed' form
;   i.e. that it takes the least significant bit first and shifts to the right. So in fact the highest order
;   bit seen from the polynomial devision point of view is the lsb of ZL. (If this sounds strange to you i
;   propose you to do an internet research on CRC :-) )
;   Each data byte received is xored to ZL the lower crc byte. This byte now builds the crc
;   table index. Next the new high byte is loaded from the table and stored in x4 until we have space in x3
;   (its destination).
;   Afterwards the lower table is loaded from the table and stored in ZL (the old index is overwritten as
;   we don't need it anymore. In fact this is a right shift by 8 bits.) Now the old crc high value is xored
;   to ZL, this is the second shift of the old crc value. Now x4 (the temp reg) is moved to x3 and the crc
;    calculation is done.
;   Prior to the first byte the two CRC register have to be initialized to 0xFFFF (as defined in usb spec)
;   however the crc engine also runs during the receipt of the first byte, therefore x3 and zl are initialized
;   to a magic number which results in a crc value of 0xFFFF after the first complete byte.

;   This algorithm is split into the extra cycles of the different bits:
;   bit7:   XOR the received byte to ZL
;   bit4:   load the new high byte to x4
;   bit5:   load the lower xor byte from the table
;   bit6:   xor zl and x3, store result in zl, the new crc low value
;         move x4 (the new high byte) to x3, the crc value is ready
;



                        
macro POP_STANDARD ; 18 cycles
    pop      ZH
    pop      ZL
   pop     cnt
    pop     x5
    pop     x3
    pop     x2
    pop     x1
    pop     shift
    pop     x4
    endm
macro POP_RETI     ; 7 cycles
    pop     YH
    pop     YL
    out     SREG, YL
    pop     YL
    endm                        
                        




USB_INTR_VECTOR:
;order of registers pushed: YL, SREG, YH, [sofError], x4, shift, x1, x2, x3, x5, cnt, ZL, ZH
    push    YL                  ;[-28] push only what is necessary to sync with edge ASAP
    in      YL, SREG            ;[-26]
    push    YL                  ;[-25]
    push    YH                  ;[-23]
;----------------------------------------------------------------------------
; 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
;The first part waits at most 1 bit long since we must be in sync pattern.
;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
;waitForJ, ensure that this prerequisite is met.
waitForJ:
    inc     YL
    sbis    USBIN, USBMINUS
    brne    waitForJ        ; just make sure we have ANY timeout
waitForK:
;The following code results in a sampling window of < 1/4 bit which meets the spec.
    sbis    USBIN, USBMINUS     ;[-17]
    rjmp    foundK              ;[-16]
    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
    sbis    USBIN, USBMINUS
    rjmp    foundK
    sbis    USBIN, USBMINUS
    rjmp    foundK
    sbis    USBIN, USBMINUS
    rjmp    foundK
#if USB_COUNT_SOF
    lds     YL, usbSofCount
    inc     YL
    sts     usbSofCount, YL
#endif  /* USB_COUNT_SOF */
#ifdef USB_SOF_HOOK
    USB_SOF_HOOK
#endif
    rjmp    sofError
foundK:                         ;[-15]
;{3, 5} after falling D- edge, average delay: 4 cycles
;bit0 should be at 30  (2.5 bits) for center sampling. Currently at 4 so 26 cylces till bit 0 sample
;use 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    x4              ;[-14]
;   [---]                       ;[-13]
    lds     YL, usbInputBufOffset;[-12] used to toggle the two usb receive buffers
;   [---]                       ;[-11]
    clr     YH                  ;[-10]
    subi    YL, lo8(-(usbRxBuf));[-9] [rx loop init]
    sbci    YH, hi8(-(usbRxBuf));[-8] [rx loop init]
    push    shift               ;[-7]
;   [---]                       ;[-6]
    ldi      shift, 0x80         ;[-5] the last bit is the end of byte marker for the pid receiver loop
    clc                           ;[-4] the carry has to be clear for receipt of pid bit 0
    sbis    USBIN, USBMINUS     ;[-3] we want two bits K (sample 3 cycles too early)
    rjmp    haveTwoBitsK        ;[-2]
    pop     shift               ;[-1] undo the push from before
    pop     x4              ;[1]
    rjmp    waitForK            ;[3] this was not the end of sync, retry
; The entire loop from waitForK until rjmp waitForK above must not exceed two
; bit times (= 24 cycles).

;----------------------------------------------------------------------------
; push more registers and initialize values while we sample the first bits:
;----------------------------------------------------------------------------
haveTwoBitsK:
    push    x1                  ;[0]
    push    x2                  ;[2]
    push    x3                  ;[4] crc high byte
    ldi     x2, 1<<USBPLUS      ;[6] [rx loop init] current line state is K state. D+=="1", D-=="0"
    push    x5                  ;[7]
    push    cnt                 ;[9]
    ldi     cnt, USB_BUFSIZE    ;[11]
   

;--------------------------------------------------------------------------------------------------------------
; receives the pid byte
; there is no real unstaffing algorithm implemented here as a stuffing bit is impossible in the pid byte.
; That's because the last four bits of the byte are the inverted of the first four bits. If we detect a
; unstaffing condition something went wrong and we abort
; shift has to be initialized to 0x80
;--------------------------------------------------------------------------------------------------------------

; pid bit 0 - used for even more register saving (we need the z pointer)
   in      x1, USBIN           ;[0] sample line state
    andi    x1, USBMASK         ;[1] filter only D+ and D- bits
    eor      x2, x1            ;[2] generate inverted of actual bit
   sbrc   x2, USBMINUS      ;[3] if the bit is set we received a zero
   sec                     ;[4]
   ror      shift            ;[5] we perform no unstuffing check here as this is the first bit
   mov      x2, x1            ;[6]
   push   ZL               ;[7]
                        ;[8]
   push   ZH               ;[9]
                        ;[10]
   ldi      x3, 0xFE         ;[11] x3 is the high order crc value
   


bitloopPid:                  
   in      x1, USBIN           ;[0] sample line state
      andi    x1, USBMASK         ;[1] filter only D+ and D- bits
    breq    nse0                ;[2] both lines are low so handle se0   
   eor      x2, x1            ;[3] generate inverted of actual bit
   sbrc   x2, USBMINUS      ;[4] set the carry if we received a zero
   sec                     ;[5]
   ror      shift            ;[6]
   ldi      ZL, 0x54         ;[7] ZL is the low order crc value
   ser      x4               ;[8] the is no bit stuffing check here as the pid bit can't be stuffed. if so
                        ; some error occured. In this case the paket is discarded later on anyway.
   mov      x2, x1            ;[9] prepare for the next cycle
   brcc   bitloopPid         ;[10] while 0s drop out of shift we get the next bit
   eor      x4, shift         ;[11] invert all bits in shift and store result in x4

;--------------------------------------------------------------------------------------------------------------
; receives data bytes and calculates the crc
; the last USBIN state has to be in x2
; this is only the first half, due to branch distanc limitations the second half of the loop is near the end
; of this asm file
;--------------------------------------------------------------------------------------------------------------

rxDataStart:
    in      x1, USBIN           ;[0] sample line state (note: a se0 check is not useful due to bit dribbling)
    ser      x5               ;[1] prepare the unstaff marker register
    eor      x2, x1                ;[2] generates the inverted of the actual bit
    bst      x2, USBMINUS          ;[3] copy the bit from x2
    bld      shift, 0           ;[4] and store it in shift
    mov      x2, shift           ;[5] make a copy of shift for unstuffing check
    andi   x2, 0xF9            ;[6] mask the last six bits, if we got six zeros (which are six ones in fact)
    breq   unstuff0            ;[7] then Z is set now and we branch to the unstaffing handler
didunstaff0:                  
   subi    cnt, 1               ;[8] cannot use dec because it doesn't affect the carry flag
    brcs    nOverflow          ;[9] Too many bytes received. Ignore packet                     
    st      Y+, x4            ;[10] store the last received byte
                        ;[11] st needs two cycles
                        
; bit1                     
   in      x2, USBIN         ;[0] sample line state
    andi   x2, USBMASK         ;[1] check for se0
    breq   nse0            ;[2]
    eor      x1, x2            ;[3]
    bst      x1, USBMINUS      ;[4]
    bld    shift, 1          ;[5]
    mov      x1, shift         ;[6]
    andi   x1, 0xF3         ;[7]
    breq   unstuff1         ;[8]
didunstaff1:
   nop2                  ;[9]
                        ;[10]
   nop                     ;[11]   

; bit2                                             
   in      x1, USBIN           ;[0] sample line state
    andi   x1, USBMASK         ;[1] check for se0 (as there is nothing else to do here
   breq   nse0             ;[2]
    eor      x2, x1              ;[3] generates the inverted of the actual bit
    bst      x2, USBMINUS      ;[4]
    bld      shift, 2         ;[5] store the bit
    mov      x2, shift         ;[6]
    andi   x2, 0xE7         ;[7] if we have six zeros here (which means six 1 in the stream)
    breq   unstuff2         ;[8] the next bit is a stuffing bit
didunstaff2:
   nop2                  ;[9]
                        ;[10]
   nop                     ;[11]               
                                              
; bit3                     
   in      x2, USBIN         ;[0] sample line state
    andi   x2, USBMASK         ;[1] check for se0
    breq   nse0            ;[2]
    eor      x1, x2            ;[3]
    bst      x1, USBMINUS      ;[4]
    bld    shift, 3          ;[5]
    mov      x1, shift         ;[6]
    andi   x1, 0xCF         ;[7]
    breq   unstuff3         ;[8]
didunstaff3:
   nop                     ;[9]
   rjmp    rxDataBit4         ;[10]
                        ;[11]            

; the avr branch instructions allow an offset of +63 insturction only, so we need this
; 'local copy' of se0
nse0:      
   rjmp   se0               ;[4]
                        ;[5]
; the same same as for se0 is needed for overflow and StuffErr
nOverflow:
nStuffErrPid:
   rjmp   overflow


unstuff0:                  ;[8] this is the branch delay of breq unstaffX
   nop                     ;[9]
   ori      shift, 0x01         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xFE         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x2, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x1, x2            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x1, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x1, x2            ;[4] the next bit expects the last state to be in x1
   nop                     ;[5]
   rjmp    didunstaff0         ;[6]
                        ;[7] jump delay of rjmp didunstaffX   
                        
unstuff1:                  ;[9] this is the jump delay of breq unstaffX
   ori      shift, 0x02         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xFD         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x1, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x2, x1            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x2, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x2, x1            ;[4] the next bit expects the last state to be in x2
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff1         ;[7]
                        ;[8] jump delay of rjmp didunstaffX      
                        
unstuff2:                  ;[9] this is the jump delay of breq unstaffX
   ori      shift, 0x04         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xFB         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x2, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x1, x2            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x1, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x1, x2            ;[4] the next bit expects the last state to be in x1
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff2         ;[7]
                        ;[8] jump delay of rjmp didunstaffX   
                        
unstuff3:                  ;[9] this is the jump delay of breq unstaffX
   ori      shift, 0x08         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xF7         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x1, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x2, x1            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x2, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x2, x1            ;[4] the next bit expects the last state to be in x2
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff3         ;[7]
                        ;[8] jump delay of rjmp didunstaffX         



; the include has to be here due to branch distance restirctions
#define __USE_CRC__   
#include "asmcommon.inc"

   

; 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
; 7.5 bit times is 90 cycles. ...there is plenty of time


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

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      ;[-6] <- acquire bus
   ldi      x2, 0         ;[-6] init x2 (bitstuff history) because sync starts with 0
    ldi     x4, USBMASK     ;[-5] exor mask
    ldi     shift, 0x80     ;[-4] sync byte is first byte sent
txByteLoop:
    ldi     bitcnt, 0x40    ;[-3]=[9]     binary 01000000
txBitLoop:               ; the loop sends the first 7 bits of the byte
    sbrs    shift, 0        ;[-2]=[10] if we have to send a 1 don't change the line state
    eor     x1, x4          ;[-1]=[11]
    out     USBOUT, x1      ;[0]
    ror     shift           ;[1] 
    ror     x2              ;[2] transfers the last sent bit to the stuffing history
didStuffN:
    nop                       ;[3]
    nop                     ;[4]
    cpi     x2, 0xfc        ;[5] if we sent six consecutive ones
    brcc    bitstuffN       ;[6]
    lsr     bitcnt          ;[7]
    brne    txBitLoop       ;[8] restart the loop while the 1 is still in the bitcount

; transmit bit 7
    sbrs    shift, 0        ;[9]
    eor     x1, x4          ;[10]
didStuff7:
    ror     shift           ;[11]
   out     USBOUT, x1      ;[0] transfer bit 7 to the pins
    ror     x2              ;[1] move the bit into the stuffing history   
    cpi     x2, 0xfc        ;[2]
    brcc    bitstuff7       ;[3]
    ld      shift, y+       ;[4] get next byte to transmit
    dec     cnt             ;[5] decrement byte counter
    brne    txByteLoop      ;[7] if we have more bytes start next one
                      ;[8] branch delay
                      
;make SE0:
    cbr     x1, USBMASK     ;[8]       prepare SE0 [spec says EOP may be 25 to 30 cycles]
    lds     x2, usbNewDeviceAddr;[9]
    lsl     x2              ;[11]       we compare with left shifted address
    out     USBOUT, x1      ;[0]       <-- out SE0 -- from now 2 bits = 24 cycles until bus idle
    subi    YL, 20 + 2      ;[1]       Only assign address on data packets, not ACK/NAK in x3
    sbci    YH, 0           ;[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
    breq    skipAddrAssign  ;[3]
    sts     usbDeviceAddr, x2      ; if not skipped: SE0 is one cycle longer
skipAddrAssign:
;end of usbDeviceAddress transfer
    ldi     x2, 1<<USB_INTR_PENDING_BIT;[5] int0 occurred during TX -- clear pending flag
    USB_STORE_PENDING(x2)   ;[6]
    ori     x1, USBIDLE     ;[7]
    in      x2, USBDDR      ;[8]
    cbr     x2, USBMASK     ;[9] set both pins to input
    mov     x3, x1          ;[10]
    cbr     x3, USBMASK     ;[11] configure no pullup on both pins
    ldi     x4, 4           ;[12]
se0Delay:
    dec     x4              ;[13] [16] [19] [22]
    brne    se0Delay        ;[14] [17] [20] [23]
    out     USBOUT, x1      ;[24] <-- out J (idle) -- end of SE0 (EOP signal)
    out     USBDDR, x2      ;[25] <-- release bus now
    out     USBOUT, x3      ;[26] <-- ensure no pull-up resistors are active
    rjmp    doReturn

   

bitstuffN:
    eor     x1, x4          ;[8] generate a zero
    ldi     x2, 0           ;[9] reset the bit stuffing history
    nop2                    ;[10]
    out     USBOUT, x1      ;[0] <-- send the stuffing bit
    rjmp    didStuffN       ;[1]
   
bitstuff7:
    eor     x1, x4          ;[5]
    ldi     x2, 0           ;[6] reset bit stuffing history
    clc                  ;[7] fill a zero into the shift register
    rol     shift           ;[8] compensate for ror shift at branch destination
    rjmp    didStuff7       ;[9]
                      ;[10] jump delay
   
;--------------------------------------------------------------------------------------------------------------
; receives data bytes and calculates the crc
; second half of the data byte receiver loop
; most parts of the crc algorithm are here
;--------------------------------------------------------------------------------------------------------------
      
rxDataBit4:
   in      x1, USBIN           ;[0] sample line state
    nop                     ;[1] the last byte has already been xored to ZL which is the lower crc value
    ldi      ZH, hi8(ctabH)       ;[2] use the table for the higher byte
    eor      x2, x1              ;[3]
    bst      x2, USBMINUS      ;[4]
    bld      shift, 4         ;[5]
    mov      x2, shift         ;[6]
    andi   x2, 0x9F         ;[7]
    breq   unstuff4         ;[8]
didunstaff4:
   lpm      x4, Z            ;[9] load the higher crc xor-byte and store it for later use
                        ;[10] lpm needs 3 cycles
                        ;[11]         

; bit5                     
   in      x2, USBIN         ;[0] sample line state
    ldi      ZH, hi8(ctabL)   ;[1] load the lower crc xor byte adress
    nop                     ;[2]   
    eor      x1, x2            ;[3]
    bst      x1, USBMINUS      ;[4]
    bld    shift, 5          ;[5]
    mov      x1, shift         ;[6]
    andi   x1, 0x3F         ;[7]
    breq   unstuff5         ;[8]
didunstaff5:
   lpm      ZL, Z            ;[9] load the lower xor crc byte
                        ;[10] lpm needs 3 cycles
                         ;[11]
                        
; bit6                      
   in      x1, USBIN           ;[0] sample line state
    eor      ZL, x3            ;[1] xor the old high crc byte with the low xor-byte
   mov      x3, x4            ;[2] move the new high order crc value from temp to its destination
    eor      x2, x1              ;[3]
    bst      x2, USBMINUS      ;[4]
    bld      shift, 6         ;[5]
    mov      x2, shift         ;[6]
    andi   x2, 0x7E         ;[7]
    breq   unstuff6         ;[8]
didunstaff6:
   nop2                  ;[9]
                        ;[10]
   nop                     ;[11]      
         
; bit7                     
   in      x2, USBIN         ;[0] sample line state
    eor      x1, x2            ;[1]
    bst      x1, USBMINUS      ;[2]
    bld    shift, 7          ;[3] now shift holds the complete but inverted data byte
    mov      x1, shift         ;[4]
    andi   x1, 0xFC         ;[5]
    breq   unstuff7         ;[6]
didunstaff7:
   eor      x5, shift         ;[7] x5 marks all bits which have not been inverted by the unstaffing subs
   mov      x4, x5            ;[8] keep a copy of the data byte it will be stored during next bit0
   eor      ZL, x4            ;[9] feed the actual byte into the crc algorithm
   rjmp   rxDataStart         ;[10] next byte
                        ;[11] during the reception of the next byte this one will be fed int the crc algorithm

unstuff4:                  ;[9] this is the jump delay of rjmp unstaffX
   ori      shift, 0x10         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xEF         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x2, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x1, x2            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x1, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr2         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x1, x2            ;[4] the next bit expects the last state to be in x1
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff4         ;[7]
                        ;[8] jump delay of rjmp didunstaffX   
                        
unstuff5:                  ;[9] this is the jump delay of rjmp unstaffX
   ori      shift, 0x20         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xDF         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x1, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x2, x1            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x2, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr2         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x2, x1            ;[4] the next bit expects the last state to be in x2
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff3         ;[7]
                        ;[8] jump delay of rjmp didunstaffX                                          
                        
unstuff6:                  ;[9] this is the jump delay of rjmp unstaffX
   ori      shift, 0x40         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0xBF         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x2, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x1, x2            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x1, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr2         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x1, x2            ;[4] the next bit expects the last state to be in x1
   nop2                  ;[5]
                        ;[6]
   rjmp    didunstaff6         ;[7]
                        ;[8] jump delay of rjmp didunstaffX   
                        
unstuff7:                  ;[7] this is the jump delay of rjmp unstaffX
   nop                     ;[8]
   nop                     ;[9]
   ori      shift, 0x80         ;[10] invert the last received bit to prevent furhter unstaffing
   andi   x5, 0x7F         ;[11] mark this bit as inverted (will be corrected before storing shift)
   in      x1, USBIN         ;[0] we have some free cycles so we could check for bit stuffing errors
   eor      x2, x1            ;[1] x1 and x2 have to be different because the staff is always a zero
   andi   x2, USBMASK         ;[2] mask the interesting bits
   nop; breq   stuffErr2         ;[3] if the stuff bit is a 1-bit something went wrong
   mov    x2, x1            ;[4] the next bit expects the last state to be in x2
   rjmp    didunstaff7         ;[5]
                        ;[6] jump delay of rjmp didunstaff7                                          

; local copy of the staffErr desitnation for the second half of the receiver loop                           
stuffErr2:
   rjmp   stuffErr   
   
.balign 256
ctabL:   // omitted here
.balign 256
ctabH:// omitted here

christian
Objective Development
Objective Development
Posts: 1443
Joined: Thu Nov 09, 2006 11:46 am

Post by christian » Wed Feb 11, 2009 4:25 pm

Sorry for not posting to this thread so far... I'm very interested in a CRC enabled version, but I currently don't have the time to put any work into it myself.

If you have questions about any details of the driver, please contact me through the support system.

Habicht

Post by Habicht » Sun Feb 15, 2009 7:39 pm

Hi christian!

The problems in the post above turned out to be a wrong branch destination and in the stuffing check for bit0.
I updated the packet at http://5n07.it-htl.at/~habicht/ it seems to be fine. I tested it by copying several megabytes of data from the pc to the avr and back.

The code I wrote is in usbdrvasm18.inc, some modifications are in asmcommon.inc Documentation is in-line, the crc algorithm is described at the beginning of usbdrvasm18.inc

Features:
clk freq: 18MHz (run stable on an atmega8)
crc: the crc of received data packets is checked during reception, if it's wrong no ack is sent to the host. To do this it uses a table driven crc algorithm (256 entries a 16 bits) and an unrolled receiver loop like the 12mhz version.
bitStuffing: bit stuffing errors are detected

Limitations:
no crc check for token pakets
needs more code space due to the table and the fact that the table has to be aligned on an 8-bit adress boundary

Feel free to modify and / or publish the code under GNU. If you have questions contact me at the e-mail address given in the first post.

Yours,
Habicht

Post Reply