Commit e625cbd9 authored by Alessandro Rubini's avatar Alessandro Rubini

Run ./scripts/Lindent on all .c and .h files

This is massive: 4k lines changed (but only 840 if you ignore
space-only changes).  In this case "git blame -w" won't always find
the right patch, and it may fall on this patch -- because those
800 lines changed in content too.

This has been done with

   find . -name '*.[ch]' | xargs -n 1 ./scripts/Lindent

Statistics: all changes and ignoring blank space:

   morgana% git diff --stat HEAD~1 | tail -1
    77 files changed, 3774 insertions(+), 3709 deletions(-)
   morgana% git diff -w --stat HEAD~1 | tail -1
    61 files changed, 894 insertions(+), 829 deletions(-)

However, after this step I hand-fixed some very ugly long expressions
(leaving them long: no content change at all is there).
Signed-off-by: Alessandro Rubini's avatarAlessandro Rubini <rubini@gnudd.com>
parent 1d24ecfb
...@@ -2,38 +2,36 @@ ...@@ -2,38 +2,36 @@
void disable_irq() void disable_irq()
{ {
unsigned int ie, im; unsigned int ie, im;
unsigned int Mask = ~1; unsigned int Mask = ~1;
/* disable peripheral interrupts in case they were enabled */ /* disable peripheral interrupts in case they were enabled */
asm volatile ("rcsr %0,ie":"=r"(ie)); asm volatile ("rcsr %0,ie":"=r" (ie));
ie &= (~0x1); ie &= (~0x1);
asm volatile ("wcsr ie, %0"::"r"(ie)); asm volatile ("wcsr ie, %0"::"r" (ie));
/* disable mask-bit in im */ /* disable mask-bit in im */
asm volatile ("rcsr %0, im":"=r"(im)); asm volatile ("rcsr %0, im":"=r" (im));
im &= Mask; im &= Mask;
asm volatile ("wcsr im, %0"::"r"(im)); asm volatile ("wcsr im, %0"::"r" (im));
} }
void enable_irq() void enable_irq()
{ {
unsigned int ie, im; unsigned int ie, im;
unsigned int Mask = 1; unsigned int Mask = 1;
/* disable peripheral interrupts in-case they were enabled*/ /* disable peripheral interrupts in-case they were enabled */
asm volatile ("rcsr %0,ie":"=r"(ie)); asm volatile ("rcsr %0,ie":"=r" (ie));
ie &= (~0x1); ie &= (~0x1);
asm volatile ("wcsr ie, %0"::"r"(ie)); asm volatile ("wcsr ie, %0"::"r" (ie));
/* enable mask-bit in im */ /* enable mask-bit in im */
asm volatile ("rcsr %0, im":"=r"(im)); asm volatile ("rcsr %0, im":"=r" (im));
im |= Mask; im |= Mask;
asm volatile ("wcsr im, %0"::"r"(im)); asm volatile ("wcsr im, %0"::"r" (im));
ie |= 0x1; ie |= 0x1;
asm volatile ("wcsr ie, %0"::"r"(ie)); asm volatile ("wcsr ie, %0"::"r" (ie));
} }
...@@ -10,4 +10,4 @@ int board_init() ...@@ -10,4 +10,4 @@ int board_init()
int board_update() int board_update()
{ {
} }
\ No newline at end of file
...@@ -10,4 +10,4 @@ int board_init() ...@@ -10,4 +10,4 @@ int board_init()
int board_update() int board_update()
{ {
} }
\ No newline at end of file
...@@ -6,44 +6,44 @@ ...@@ -6,44 +6,44 @@
#define DNA_SHIFT 3 #define DNA_SHIFT 3
#define DNA_READ 2 #define DNA_READ 2
void dna_read(uint32_t *lo, uint32_t *hi) void dna_read(uint32_t * lo, uint32_t * hi)
{ {
uint64_t dna = 0; uint64_t dna = 0;
int i; int i;
gpio_out(DNA_DATA, 0); gpio_out(DNA_DATA, 0);
delay(10); delay(10);
gpio_out(DNA_CLK, 0); gpio_out(DNA_CLK, 0);
delay(10); delay(10);
gpio_out(DNA_READ, 1); gpio_out(DNA_READ, 1);
delay(10); delay(10);
gpio_out(DNA_SHIFT, 0); gpio_out(DNA_SHIFT, 0);
delay(10); delay(10);
delay(10); delay(10);
gpio_out(DNA_CLK, 1); gpio_out(DNA_CLK, 1);
delay(10); delay(10);
if(gpio_in(DNA_DATA)) dna |= 1; if (gpio_in(DNA_DATA))
delay(10); dna |= 1;
gpio_out(DNA_CLK, 0); delay(10);
delay(10); gpio_out(DNA_CLK, 0);
gpio_out(DNA_READ, 0); delay(10);
gpio_out(DNA_SHIFT, 1); gpio_out(DNA_READ, 0);
delay(10); gpio_out(DNA_SHIFT, 1);
delay(10);
for (i = 0; i < 57; i++) {
for(i=0;i<57;i++) dna <<= 1;
{ delay(10);
dna <<= 1; delay(10);
delay(10); gpio_out(DNA_CLK, 1);
delay(10); delay(10);
gpio_out(DNA_CLK, 1); if (gpio_in(DNA_DATA))
delay(10); dna |= 1;
if(gpio_in(DNA_DATA)) dna |= 1; delay(10);
delay(10); gpio_out(DNA_CLK, 0);
gpio_out(DNA_CLK, 0); delay(10);
delay(10); }
}
*hi = (uint32_t) (dna >> 32); *hi = (uint32_t) (dna >> 32);
*lo = (uint32_t) dna; *lo = (uint32_t) dna;
......
...@@ -50,210 +50,219 @@ uint8_t has_eeprom = 0; ...@@ -50,210 +50,219 @@ uint8_t has_eeprom = 0;
uint8_t eeprom_present(uint8_t i2cif, uint8_t i2c_addr) uint8_t eeprom_present(uint8_t i2cif, uint8_t i2c_addr)
{ {
has_eeprom = 1; has_eeprom = 1;
if( !mi2c_devprobe(i2cif, i2c_addr) ) if (!mi2c_devprobe(i2cif, i2c_addr))
if( !mi2c_devprobe(i2cif, i2c_addr) ) if (!mi2c_devprobe(i2cif, i2c_addr))
has_eeprom = 0; has_eeprom = 0;
return 0; return 0;
} }
int eeprom_read(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t *buf, size_t size) int eeprom_read(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t * buf,
size_t size)
{ {
int i; int i;
unsigned char c; unsigned char c;
if(!has_eeprom) if (!has_eeprom)
return -1; return -1;
mi2c_start(i2cif); mi2c_start(i2cif);
if(mi2c_put_byte(i2cif, i2c_addr << 1) < 0) if (mi2c_put_byte(i2cif, i2c_addr << 1) < 0) {
{ mi2c_stop(i2cif);
mi2c_stop(i2cif); return -1;
return -1; }
} mi2c_put_byte(i2cif, (offset >> 8) & 0xff);
mi2c_put_byte(i2cif, (offset>>8) & 0xff); mi2c_put_byte(i2cif, offset & 0xff);
mi2c_put_byte(i2cif, offset & 0xff); mi2c_repeat_start(i2cif);
mi2c_repeat_start(i2cif); mi2c_put_byte(i2cif, (i2c_addr << 1) | 1);
mi2c_put_byte(i2cif, (i2c_addr << 1) | 1); for (i = 0; i < size - 1; ++i) {
for(i=0; i<size-1; ++i) mi2c_get_byte(i2cif, &c, 0);
{ *buf++ = c;
mi2c_get_byte(i2cif, &c, 0); }
*buf++ = c; mi2c_get_byte(i2cif, &c, 1);
} *buf++ = c;
mi2c_get_byte(i2cif, &c, 1); mi2c_stop(i2cif);
*buf++ = c;
mi2c_stop(i2cif); return size;
return size;
} }
int eeprom_write(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t *buf, size_t size) int eeprom_write(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset,
uint8_t * buf, size_t size)
{ {
int i, busy; int i, busy;
if(!has_eeprom) if (!has_eeprom)
return -1; return -1;
for(i=0;i<size;i++) for (i = 0; i < size; i++) {
{ mi2c_start(i2cif);
mi2c_start(i2cif);
if(mi2c_put_byte(i2cif, i2c_addr << 1) < 0) if (mi2c_put_byte(i2cif, i2c_addr << 1) < 0) {
{ mi2c_stop(i2cif);
mi2c_stop(i2cif); return -1;
return -1; }
}
mi2c_put_byte(i2cif, (offset >> 8) & 0xff); mi2c_put_byte(i2cif, (offset >> 8) & 0xff);
mi2c_put_byte(i2cif, offset & 0xff); mi2c_put_byte(i2cif, offset & 0xff);
mi2c_put_byte(i2cif, *buf++); mi2c_put_byte(i2cif, *buf++);
offset++; offset++;
mi2c_stop(i2cif); mi2c_stop(i2cif);
do /* wait until the chip becomes ready */ do { /* wait until the chip becomes ready */
{ mi2c_start(i2cif);
mi2c_start(i2cif);
busy = mi2c_put_byte(i2cif, i2c_addr << 1); busy = mi2c_put_byte(i2cif, i2c_addr << 1);
mi2c_stop(i2cif); mi2c_stop(i2cif);
} while(busy); } while (busy);
} }
return size; return size;
} }
int32_t eeprom_sfpdb_erase(uint8_t i2cif, uint8_t i2c_addr) int32_t eeprom_sfpdb_erase(uint8_t i2cif, uint8_t i2c_addr)
{ {
uint8_t sfpcount = 0; uint8_t sfpcount = 0;
//just a dummy function that writes '0' to sfp count field of the SFP DB //just a dummy function that writes '0' to sfp count field of the SFP DB
if( eeprom_write(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount, sizeof(sfpcount)) != sizeof(sfpcount)) if (eeprom_write(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount,
return EE_RET_I2CERR; sizeof(sfpcount)) != sizeof(sfpcount))
else return EE_RET_I2CERR;
return sfpcount; else
return sfpcount;
} }
int32_t eeprom_get_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo* sfp, uint8_t add, uint8_t pos) int32_t eeprom_get_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo * sfp,
uint8_t add, uint8_t pos)
{ {
static uint8_t sfpcount = 0; static uint8_t sfpcount = 0;
uint8_t i, chksum=0; uint8_t i, chksum = 0;
uint8_t* ptr; uint8_t *ptr;
if( pos>=SFPS_MAX ) if (pos >= SFPS_MAX)
return EE_RET_POSERR; //position in database outside the range return EE_RET_POSERR; //position in database outside the range
//read how many SFPs are in the database, but only in the first call (pos==0) //read how many SFPs are in the database, but only in the first call (pos==0)
if( !pos && eeprom_read(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount, sizeof(sfpcount)) != sizeof(sfpcount) ) if (!pos
return EE_RET_I2CERR; && eeprom_read(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount,
sizeof(sfpcount)) != sizeof(sfpcount))
if( add && sfpcount==SFPS_MAX ) //no more space in the database to add new SFPs return EE_RET_I2CERR;
return EE_RET_DBFULL;
else if( !pos && !add && sfpcount==0 ) //there are no SFPs in the database to read if (add && sfpcount == SFPS_MAX) //no more space in the database to add new SFPs
return sfpcount; return EE_RET_DBFULL;
else if (!pos && !add && sfpcount == 0) //there are no SFPs in the database to read
if(!add) return sfpcount;
{
if( eeprom_read(i2cif, i2c_addr, EE_BASE_SFP + sizeof(sfpcount) + pos*sizeof(struct s_sfpinfo), (uint8_t*)sfp, if (!add) {
sizeof(struct s_sfpinfo)) != sizeof(struct s_sfpinfo) ) if (eeprom_read(i2cif, i2c_addr,
return EE_RET_I2CERR; EE_BASE_SFP + sizeof(sfpcount)
+ pos * sizeof(struct s_sfpinfo),
ptr = (uint8_t*)sfp; (uint8_t*)sfp, sizeof(struct s_sfpinfo))
for(i=0; i<sizeof(struct s_sfpinfo)-1; ++i) //'-1' because we do not include chksum in computation != sizeof(struct s_sfpinfo) )
chksum = (uint8_t) ((uint16_t)chksum + *(ptr++)) & 0xff; return EE_RET_I2CERR;
if(chksum != sfp->chksum)
EE_RET_CORRPT; ptr = (uint8_t *) sfp;
} for (i = 0; i < sizeof(struct s_sfpinfo) - 1; ++i) //'-1' because we do not include chksum in computation
else chksum =
{ (uint8_t) ((uint16_t) chksum + *(ptr++)) & 0xff;
/*count checksum*/ if (chksum != sfp->chksum)
ptr = (uint8_t*)sfp; EE_RET_CORRPT;
for(i=0; i<sizeof(struct s_sfpinfo)-1; ++i) //'-1' because we do not include chksum in computation } else {
chksum = (uint8_t) ((uint16_t)chksum + *(ptr++)) & 0xff; /*count checksum */
sfp->chksum = chksum; ptr = (uint8_t *) sfp;
/*add SFP at the end of DB*/ for (i = 0; i < sizeof(struct s_sfpinfo) - 1; ++i) //'-1' because we do not include chksum in computation
eeprom_write(i2cif, i2c_addr, EE_BASE_SFP+sizeof(sfpcount) + sfpcount*sizeof(struct s_sfpinfo), (uint8_t*)sfp, sizeof(struct s_sfpinfo)); chksum =
sfpcount++; (uint8_t) ((uint16_t) chksum + *(ptr++)) & 0xff;
eeprom_write(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount, sizeof(sfpcount)); sfp->chksum = chksum;
} /*add SFP at the end of DB */
eeprom_write(i2cif, i2c_addr,
return sfpcount; EE_BASE_SFP + sizeof(sfpcount)
+ sfpcount * sizeof(struct s_sfpinfo),
(uint8_t *) sfp, sizeof(struct s_sfpinfo));
sfpcount++;
eeprom_write(i2cif, i2c_addr, EE_BASE_SFP, &sfpcount,
sizeof(sfpcount));
}
return sfpcount;
} }
int8_t eeprom_match_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo* sfp) int8_t eeprom_match_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo * sfp)
{ {
uint8_t sfpcount = 1; uint8_t sfpcount = 1;
int8_t i, temp; int8_t i, temp;
struct s_sfpinfo dbsfp; struct s_sfpinfo dbsfp;
for(i=0; i<sfpcount; ++i) for (i = 0; i < sfpcount; ++i) {
{ temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR,
temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &dbsfp, 0, i); &dbsfp, 0, i);
if(!i) if (!i) {
{ sfpcount = temp; //only in first round valid sfpcount is returned from eeprom_get_sfp
sfpcount=temp; //only in first round valid sfpcount is returned from eeprom_get_sfp if (sfpcount == 0 || sfpcount == 0xFF)
if(sfpcount == 0 || sfpcount == 0xFF) return 0;
return 0; else if (sfpcount < 0)
else if(sfpcount<0) return sfpcount;
return sfpcount; }
} if (!strncmp(dbsfp.pn, sfp->pn, 16)) {
if( !strncmp(dbsfp.pn, sfp->pn, 16) ) sfp->dTx = dbsfp.dTx;
{ sfp->dRx = dbsfp.dRx;
sfp->dTx = dbsfp.dTx; sfp->alpha = dbsfp.alpha;
sfp->dRx = dbsfp.dRx; return 1;
sfp->alpha = dbsfp.alpha; }
return 1; }
}
} return 0;
return 0;
} }
int8_t eeprom_phtrans(uint8_t i2cif, uint8_t i2c_addr, uint32_t *val, uint8_t write) int8_t eeprom_phtrans(uint8_t i2cif, uint8_t i2c_addr, uint32_t * val,
uint8_t write)
{ {
if(write) if (write) {
{ *val |= (1 << 31);
*val |= (1<<31); if (eeprom_write(i2cif, i2c_addr, EE_BASE_CAL, (uint8_t *) val,
if( eeprom_write(i2cif, i2c_addr, EE_BASE_CAL, (uint8_t*)val, sizeof(val) ) != sizeof(val) ) sizeof(val)) != sizeof(val))
return EE_RET_I2CERR; return EE_RET_I2CERR;
else else
return 1; return 1;
} } else {
else if (eeprom_read(i2cif, i2c_addr, EE_BASE_CAL, (uint8_t *) val,
{ sizeof(val)) != sizeof(val))
if( eeprom_read(i2cif, i2c_addr, EE_BASE_CAL, (uint8_t*)val, sizeof(val) ) != sizeof(val) ) return EE_RET_I2CERR;
return EE_RET_I2CERR;
if (!(*val & (1 << 31)))
if( !(*val&(1<<31)) ) return 0;
return 0;
*val &= 0x7fffffff; //return ph_trans value without validity bit
*val &= 0x7fffffff; //return ph_trans value without validity bit return 1;
return 1; }
}
} }
int8_t eeprom_init_erase(uint8_t i2cif, uint8_t i2c_addr) int8_t eeprom_init_erase(uint8_t i2cif, uint8_t i2c_addr)
{ {
uint16_t used = 0; uint16_t used = 0;
if( eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used)) if (eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used,
return EE_RET_I2CERR; sizeof(used)) != sizeof(used))
else return EE_RET_I2CERR;
return used; else
return used;
} }
int8_t eeprom_init_purge(uint8_t i2cif, uint8_t i2c_addr) int8_t eeprom_init_purge(uint8_t i2cif, uint8_t i2c_addr)
{ {
uint16_t used = 0xffff, i; uint16_t used = 0xffff, i;
uint16_t pattern = 0xff; uint16_t pattern = 0xff;
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used) ) if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used,
sizeof(used)) != sizeof(used))
return EE_RET_I2CERR; return EE_RET_I2CERR;
if(used==0xffff) used=0; if (used == 0xffff)
for(i=0; i<used; ++i) used = 0;
eeprom_write(i2cif, i2c_addr, EE_BASE_INIT+sizeof(used)+i, (uint8_t*)&pattern, 1); for (i = 0; i < used; ++i)
used = 0xffff; eeprom_write(i2cif, i2c_addr, EE_BASE_INIT + sizeof(used) + i,
eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, 2); (uint8_t *) & pattern, 1);
used = 0xffff;
eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used, 2);
return used; return used;
} }
/* /*
...@@ -261,86 +270,96 @@ int8_t eeprom_init_purge(uint8_t i2cif, uint8_t i2c_addr) ...@@ -261,86 +270,96 @@ int8_t eeprom_init_purge(uint8_t i2cif, uint8_t i2c_addr)
*/ */
int8_t eeprom_init_add(uint8_t i2cif, uint8_t i2c_addr, const char *args[]) int8_t eeprom_init_add(uint8_t i2cif, uint8_t i2c_addr, const char *args[])
{ {
uint8_t i=1; uint8_t i = 1;
char separator = ' '; char separator = ' ';
uint16_t used, readback; uint16_t used, readback;
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used) ) if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used,
return EE_RET_I2CERR; sizeof(used)) != sizeof(used))
return EE_RET_I2CERR;
if( used==0xffff ) used=0; //this means the memory is blank
if (used == 0xffff)
while(args[i]!='\0') used = 0; //this means the memory is blank
{
if( eeprom_write(i2cif, i2c_addr, EE_BASE_INIT+sizeof(used)+used, (uint8_t*)args[i], strlen(args[i])) != strlen(args[i])) while (args[i] != '\0') {
return EE_RET_I2CERR; if (eeprom_write(i2cif, i2c_addr, EE_BASE_INIT + sizeof(used)
used += strlen(args[i]); + used, (uint8_t *) args[i], strlen(args[i]))
if( eeprom_write(i2cif, i2c_addr, EE_BASE_INIT+sizeof(used)+used, &separator, sizeof(separator)) != sizeof(separator) ) != strlen(args[i]))
return EE_RET_I2CERR; return EE_RET_I2CERR;
++used; used += strlen(args[i]);
++i; if (eeprom_write(i2cif, i2c_addr, EE_BASE_INIT + sizeof(used)
} + used, &separator, sizeof(separator))
//the end of the command, replace last separator with '\n' != sizeof(separator))
separator = '\n'; return EE_RET_I2CERR;
if( eeprom_write(i2cif, i2c_addr, EE_BASE_INIT+sizeof(used)+used-1, &separator, sizeof(separator)) != sizeof(separator) ) ++used;
return EE_RET_I2CERR; ++i;
//and finally update the size of the script }
if( eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used) ) //the end of the command, replace last separator with '\n'
return EE_RET_I2CERR; separator = '\n';
if (eeprom_write(i2cif, i2c_addr, EE_BASE_INIT + sizeof(used) + used-1,
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&readback, sizeof(readback)) != sizeof(readback) ) &separator, sizeof(separator)) != sizeof(separator))
return EE_RET_I2CERR; return EE_RET_I2CERR;
//and finally update the size of the script
return 0; if (eeprom_write(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used,
sizeof(used)) != sizeof(used))
return EE_RET_I2CERR;
if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & readback,
sizeof(readback)) != sizeof(readback))
return EE_RET_I2CERR;
return 0;
} }
int32_t eeprom_init_show(uint8_t i2cif, uint8_t i2c_addr) int32_t eeprom_init_show(uint8_t i2cif, uint8_t i2c_addr)
{ {
uint16_t used, i; uint16_t used, i;
char byte; char byte;
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used) ) if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t *) & used,
return EE_RET_I2CERR; sizeof(used)) != sizeof(used))
return EE_RET_I2CERR;
if(used==0 || used==0xffff)
{ if (used == 0 || used == 0xffff) {
used = 0; //this means the memory is blank used = 0; //this means the memory is blank
mprintf("Empty init script...\n"); mprintf("Empty init script...\n");
} }
//just read and print to the screen char after char
//just read and print to the screen char after char for (i = 0; i < used; ++i) {
for(i=0; i<used; ++i) if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT + sizeof(used)
{ + i, &byte, sizeof(byte)) != sizeof(byte))
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT+sizeof(used)+i, &byte, sizeof(byte)) != sizeof(byte) ) return EE_RET_I2CERR;
return EE_RET_I2CERR; mprintf("%c", byte);
mprintf("%c", byte); }
}
return 0;
return 0;
} }
int8_t eeprom_init_readcmd(uint8_t i2cif, uint8_t i2c_addr, char* buf, uint8_t bufsize, uint8_t next) int8_t eeprom_init_readcmd(uint8_t i2cif, uint8_t i2c_addr, char *buf,
uint8_t bufsize, uint8_t next)
{ {
static uint16_t ptr; static uint16_t ptr;
static uint16_t used = 0; static uint16_t used = 0;
uint8_t i=0; uint8_t i = 0;
if(next == 0) if (next == 0) {
{ if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT,
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT, (uint8_t*)&used, sizeof(used)) != sizeof(used) ) (uint8_t *) & used, sizeof(used))
return EE_RET_I2CERR; != sizeof(used))
ptr = sizeof(used); return EE_RET_I2CERR;
} ptr = sizeof(used);
}
if(ptr-sizeof(used) >= used)
return 0; if (ptr - sizeof(used) >= used)
return 0;
do
{ do {
if(ptr-sizeof(used) > bufsize) return EE_RET_CORRPT; if (ptr - sizeof(used) > bufsize)
if( eeprom_read(i2cif, i2c_addr, EE_BASE_INIT+(ptr++), &buf[i], sizeof(char)) != sizeof(char) ) return EE_RET_CORRPT;
return EE_RET_I2CERR; if (eeprom_read(i2cif, i2c_addr, EE_BASE_INIT + (ptr++),
}while(buf[i++]!='\n'); &buf[i], sizeof(char)) != sizeof(char))
return EE_RET_I2CERR;
return i; } while (buf[i++] != '\n');
return i;
} }
...@@ -18,7 +18,6 @@ LGPL 2.1 ...@@ -18,7 +18,6 @@ LGPL 2.1
#include <hw/endpoint_regs.h> #include <hw/endpoint_regs.h>
#include <hw/endpoint_mdio.h> #include <hw/endpoint_mdio.h>
/* Length of a single bit on the gigabit serial link in picoseconds. Used for calculating deltaRx/deltaTx /* Length of a single bit on the gigabit serial link in picoseconds. Used for calculating deltaRx/deltaTx
from the serdes bitslip value */ from the serdes bitslip value */
#define PICOS_PER_SERIAL_BIT 800 #define PICOS_PER_SERIAL_BIT 800
...@@ -33,150 +32,150 @@ volatile struct EP_WB *EP; ...@@ -33,150 +32,150 @@ volatile struct EP_WB *EP;
/* functions for accessing PCS (MDIO) registers */ /* functions for accessing PCS (MDIO) registers */
uint16_t pcs_read(int location) uint16_t pcs_read(int location)
{ {
EP->MDIO_CR = EP_MDIO_CR_ADDR_W(location >> 2); EP->MDIO_CR = EP_MDIO_CR_ADDR_W(location >> 2);
while ((EP->MDIO_ASR & EP_MDIO_ASR_READY) == 0); while ((EP->MDIO_ASR & EP_MDIO_ASR_READY) == 0) ;
return EP_MDIO_ASR_RDATA_R(EP->MDIO_ASR) & 0xffff; return EP_MDIO_ASR_RDATA_R(EP->MDIO_ASR) & 0xffff;
} }
void pcs_write(int location, int value) void pcs_write(int location, int value)
{ {
EP->MDIO_CR = EP_MDIO_CR_ADDR_W(location >> 2) EP->MDIO_CR = EP_MDIO_CR_ADDR_W(location >> 2)
| EP_MDIO_CR_DATA_W(value) | EP_MDIO_CR_DATA_W(value)
| EP_MDIO_CR_RW; | EP_MDIO_CR_RW;
while ((EP->MDIO_ASR & EP_MDIO_ASR_READY) == 0); while ((EP->MDIO_ASR & EP_MDIO_ASR_READY) == 0) ;
} }
/* MAC address setting */ /* MAC address setting */
void set_mac_addr(uint8_t dev_addr[]) void set_mac_addr(uint8_t dev_addr[])
{ {
EP->MACL = ((uint32_t)dev_addr[2] << 24) EP->MACL = ((uint32_t) dev_addr[2] << 24)
| ((uint32_t)dev_addr[3] << 16) | ((uint32_t) dev_addr[3] << 16)
| ((uint32_t)dev_addr[4] << 8) | ((uint32_t) dev_addr[4] << 8)
| ((uint32_t)dev_addr[5]); | ((uint32_t) dev_addr[5]);
EP->MACH = ((uint32_t)dev_addr[0] << 8) EP->MACH = ((uint32_t) dev_addr[0] << 8)
| ((uint32_t)dev_addr[1]); | ((uint32_t) dev_addr[1]);
} }
void get_mac_addr(uint8_t dev_addr[]) void get_mac_addr(uint8_t dev_addr[])
{ {
dev_addr[5] = (EP->MACL & 0x000000ff); dev_addr[5] = (EP->MACL & 0x000000ff);
dev_addr[4] = (EP->MACL & 0x0000ff00) >> 8; dev_addr[4] = (EP->MACL & 0x0000ff00) >> 8;
dev_addr[3] = (EP->MACL & 0x00ff0000) >> 16; dev_addr[3] = (EP->MACL & 0x00ff0000) >> 16;
dev_addr[2] = (EP->MACL & 0xff000000) >> 24; dev_addr[2] = (EP->MACL & 0xff000000) >> 24;
dev_addr[1] = (EP->MACH & 0x000000ff); dev_addr[1] = (EP->MACH & 0x000000ff);
dev_addr[0] = (EP->MACH & 0x0000ff00) >> 8; dev_addr[0] = (EP->MACH & 0x0000ff00) >> 8;
} }
/* Initializes the endpoint and sets its local MAC address */ /* Initializes the endpoint and sets its local MAC address */
void ep_init(uint8_t mac_addr[]) void ep_init(uint8_t mac_addr[])
{ {
EP = (volatile struct EP_WB *) BASE_EP; EP = (volatile struct EP_WB *)BASE_EP;
set_mac_addr(mac_addr); set_mac_addr(mac_addr);
*(unsigned int *)(0x62000) = 0x2; // reset network stuff (cleanup required!) *(unsigned int *)(0x62000) = 0x2; // reset network stuff (cleanup required!)
*(unsigned int *)(0x62000) = 0; *(unsigned int *)(0x62000) = 0;
EP->ECR = 0; /* disable Endpoint */ EP->ECR = 0; /* disable Endpoint */
EP->VCR0 = EP_VCR0_QMODE_W(3); /* disable VLAN unit - not used by WRPC */ EP->VCR0 = EP_VCR0_QMODE_W(3); /* disable VLAN unit - not used by WRPC */
EP->RFCR = EP_RFCR_MRU_W(1518); /* Set the max RX packet size */ EP->RFCR = EP_RFCR_MRU_W(1518); /* Set the max RX packet size */
EP->TSCR = EP_TSCR_EN_TXTS | EP_TSCR_EN_RXTS; /* Enable timestamping */ EP->TSCR = EP_TSCR_EN_TXTS | EP_TSCR_EN_RXTS; /* Enable timestamping */
/* Configure DMTD phase tracking */ /* Configure DMTD phase tracking */
EP->DMCR = EP_DMCR_EN | EP_DMCR_N_AVG_W(DMTD_AVG_SAMPLES); EP->DMCR = EP_DMCR_EN | EP_DMCR_N_AVG_W(DMTD_AVG_SAMPLES);
} }
/* Enables/disables transmission and reception. When autoneg is set to 1, /* Enables/disables transmission and reception. When autoneg is set to 1,
starts up 802.3 autonegotiation process */ starts up 802.3 autonegotiation process */
int ep_enable(int enabled, int autoneg) int ep_enable(int enabled, int autoneg)
{ {
uint16_t mcr; uint16_t mcr;
if(!enabled) if (!enabled) {
{ EP->ECR = 0;
EP->ECR = 0; return 0;
return 0; }
}
/* Disable the endpoint */ /* Disable the endpoint */
EP->ECR = 0; EP->ECR = 0;
mprintf("ID: %x\n", EP->IDCODE); mprintf("ID: %x\n", EP->IDCODE);
/* Load default packet classifier rules - see ep_pfilter.c for details */ /* Load default packet classifier rules - see ep_pfilter.c for details */
pfilter_init_default(); pfilter_init_default();
/* Enable TX/RX paths, reset RMON counters */ /* Enable TX/RX paths, reset RMON counters */
EP->ECR = EP_ECR_TX_EN | EP_ECR_RX_EN | EP_ECR_RST_CNT; EP->ECR = EP_ECR_TX_EN | EP_ECR_RX_EN | EP_ECR_RST_CNT;
autoneg_enabled = autoneg; autoneg_enabled = autoneg;
/* Reset the GTP Transceiver - it's important to do the GTP phase alignment every time /* Reset the GTP Transceiver - it's important to do the GTP phase alignment every time
we start up the software, otherwise the calibration RX/TX deltas may not be correct */ we start up the software, otherwise the calibration RX/TX deltas may not be correct */
pcs_write(MDIO_REG_MCR, MDIO_MCR_PDOWN); /* reset the PHY */ pcs_write(MDIO_REG_MCR, MDIO_MCR_PDOWN); /* reset the PHY */
timer_delay(200); timer_delay(200);
pcs_write(MDIO_REG_MCR, MDIO_MCR_RESET); /* reset the PHY */ pcs_write(MDIO_REG_MCR, MDIO_MCR_RESET); /* reset the PHY */
pcs_write(MDIO_REG_MCR, 0); /* reset the PHY */ pcs_write(MDIO_REG_MCR, 0); /* reset the PHY */
/* Don't advertise anything - we don't want flow control */ /* Don't advertise anything - we don't want flow control */
pcs_write(MDIO_REG_ADVERTISE, 0); pcs_write(MDIO_REG_ADVERTISE, 0);
mcr = MDIO_MCR_SPEED1000_MASK | MDIO_MCR_FULLDPLX_MASK; mcr = MDIO_MCR_SPEED1000_MASK | MDIO_MCR_FULLDPLX_MASK;
if(autoneg) if (autoneg)
mcr |= MDIO_MCR_ANENABLE | MDIO_MCR_ANRESTART; mcr |= MDIO_MCR_ANENABLE | MDIO_MCR_ANRESTART;
pcs_write(MDIO_REG_MCR, mcr); pcs_write(MDIO_REG_MCR, mcr);
return 0; return 0;
} }
/* Checks the link status. If the link is up, returns non-zero /* Checks the link status. If the link is up, returns non-zero
and stores the Link Partner Ability (LPA) autonegotiation register at *lpa */ and stores the Link Partner Ability (LPA) autonegotiation register at *lpa */
int ep_link_up(uint16_t *lpa) int ep_link_up(uint16_t * lpa)
{ {
uint16_t flags = MDIO_MSR_LSTATUS; uint16_t flags = MDIO_MSR_LSTATUS;
volatile uint16_t msr; volatile uint16_t msr;
if(autoneg_enabled) if (autoneg_enabled)
flags |= MDIO_MSR_ANEGCOMPLETE; flags |= MDIO_MSR_ANEGCOMPLETE;
msr = pcs_read(MDIO_REG_MSR); msr = pcs_read(MDIO_REG_MSR);
msr = pcs_read(MDIO_REG_MSR); /* Read this flag twice to make sure the status is updated */ msr = pcs_read(MDIO_REG_MSR); /* Read this flag twice to make sure the status is updated */
if(lpa) *lpa = pcs_read(MDIO_REG_LPA); if (lpa)
*lpa = pcs_read(MDIO_REG_LPA);
return (msr & flags) == flags ? 1 : 0; return (msr & flags) == flags ? 1 : 0;
} }
/* Returns the TX/RX latencies. They are valid only when the link is up. */ /* Returns the TX/RX latencies. They are valid only when the link is up. */
int ep_get_deltas(uint32_t *delta_tx, uint32_t *delta_rx) int ep_get_deltas(uint32_t * delta_tx, uint32_t * delta_rx)
{ {
/* fixme: these values should be stored in calibration block in the EEPROM on the FMC. Also, the TX/RX delays of a particular SFP /* fixme: these values should be stored in calibration block in the EEPROM on the FMC. Also, the TX/RX delays of a particular SFP
should be added here */ should be added here */
*delta_tx = sfp_deltaTx; *delta_tx = sfp_deltaTx;
*delta_rx = sfp_deltaRx + PICOS_PER_SERIAL_BIT * MDIO_WR_SPEC_BSLIDE_R(pcs_read(MDIO_REG_WR_SPEC)); *delta_rx =
sfp_deltaRx +
PICOS_PER_SERIAL_BIT *
MDIO_WR_SPEC_BSLIDE_R(pcs_read(MDIO_REG_WR_SPEC));
return 0; return 0;
} }
int ep_cal_pattern_enable() int ep_cal_pattern_enable()
{ {
uint32_t val; uint32_t val;
val = pcs_read(MDIO_REG_WR_SPEC); val = pcs_read(MDIO_REG_WR_SPEC);
val |= MDIO_WR_SPEC_TX_CAL; val |= MDIO_WR_SPEC_TX_CAL;
pcs_write(MDIO_REG_WR_SPEC, val); pcs_write(MDIO_REG_WR_SPEC, val);
return 0; return 0;
} }
int ep_cal_pattern_disable() int ep_cal_pattern_disable()
{ {
uint32_t val; uint32_t val;
val = pcs_read(MDIO_REG_WR_SPEC); val = pcs_read(MDIO_REG_WR_SPEC);
val &= (~MDIO_WR_SPEC_TX_CAL); val &= (~MDIO_WR_SPEC_TX_CAL);
pcs_write(MDIO_REG_WR_SPEC, val); pcs_write(MDIO_REG_WR_SPEC, val);
return 0; return 0;
} }
...@@ -60,7 +60,6 @@ ...@@ -60,7 +60,6 @@
FIN instruction terminates the program. FIN instruction terminates the program.
NOP executes a dummy instruction (LOGIC2 0, 0, AND, 0) NOP executes a dummy instruction (LOGIC2 0, 0, AND, 0)
IMPORTANT: IMPORTANT:
- the program counter is advanved each time a 16-bit words of the packet arrives. - the program counter is advanved each time a 16-bit words of the packet arrives.
- the CPU doesn't have any interlocks to simplify the HW, so you can't compare the - the CPU doesn't have any interlocks to simplify the HW, so you can't compare the
...@@ -69,8 +68,6 @@ ...@@ -69,8 +68,6 @@
32 instructions (there's no flow throttling) 32 instructions (there's no flow throttling)
*/ */
#include <stdio.h> #include <stdio.h>
#include "board.h" #include "board.h"
...@@ -83,133 +80,140 @@ ...@@ -83,133 +80,140 @@
extern volatile struct EP_WB *EP; extern volatile struct EP_WB *EP;
static const uint64_t PF_MODE_LOGIC = (1ULL<<34); static const uint64_t PF_MODE_LOGIC = (1ULL << 34);
static const uint64_t PF_MODE_CMP = 0ULL; static const uint64_t PF_MODE_CMP = 0ULL;
static int code_pos; static int code_pos;
static uint64_t code_buf[32]; static uint64_t code_buf[32];
/* begins assembling a new packet filter program */ /* begins assembling a new packet filter program */
void pfilter_new() void pfilter_new()
{ {
code_pos = 0; code_pos = 0;
} }
static void check_size() static void check_size()
{ {
if(code_pos == PFILTER_MAX_CODE_SIZE - 1) if (code_pos == PFILTER_MAX_CODE_SIZE - 1) {
{ pfilter_dbg("microcode: code too big (max size: %d)\n",
pfilter_dbg("microcode: code too big (max size: %d)\n", PFILTER_MAX_CODE_SIZE); PFILTER_MAX_CODE_SIZE);
} }
} }
static void check_reg_range(int val, int minval, int maxval, char *name) static void check_reg_range(int val, int minval, int maxval, char *name)
{ {
if(val < minval || val > maxval) if (val < minval || val > maxval) {
{ pfilter_dbg("microcode: %s register out of range (%d to %d)",
pfilter_dbg("microcode: %s register out of range (%d to %d)", name, minval,maxval); name, minval, maxval);
} }
} }
void pfilter_cmp(int offset, int value, int mask, pfilter_op_t op, int rd) void pfilter_cmp(int offset, int value, int mask, pfilter_op_t op, int rd)
{ {
uint64_t ir; uint64_t ir;
check_size(); check_size();
if(offset > code_pos) if (offset > code_pos)
pfilter_dbg("microcode: comparison offset is bigger than current PC. Insert some nops before comparing"); pfilter_dbg
("microcode: comparison offset is bigger than current PC. Insert some nops before comparing");
check_reg_range(rd, 1, 15, "ra/rd"); check_reg_range(rd, 1, 15, "ra/rd");
ir = (PF_MODE_CMP | ((uint64_t)offset << 7) ir = (PF_MODE_CMP | ((uint64_t) offset << 7)
| ((mask & 0x1) ? (1ULL<<29) : 0) | ((mask & 0x1) ? (1ULL << 29) : 0)
| ((mask & 0x10) ? (1ULL<<30) : 0) | ((mask & 0x10) ? (1ULL << 30) : 0)
| ((mask & 0x100) ? (1ULL<<31) : 0) | ((mask & 0x100) ? (1ULL << 31) : 0)
| ((mask & 0x1000) ? (1ULL<<32) : 0)) | ((mask & 0x1000) ? (1ULL << 32) : 0))
| op | (rd << 3); | op | (rd << 3);
ir = ir | ((uint64_t)value & 0xffffULL) << 13; ir = ir | ((uint64_t) value & 0xffffULL) << 13;
code_buf[code_pos++] = ir; code_buf[code_pos++] = ir;
} }
// rd = (packet[offset] & (1<<bit_index)) op rd // rd = (packet[offset] & (1<<bit_index)) op rd
void pfilter_btst(int offset, int bit_index, pfilter_op_t op, int rd) void pfilter_btst(int offset, int bit_index, pfilter_op_t op, int rd)
{ {
uint64_t ir; uint64_t ir;
check_size(); check_size();
if(offset > code_pos) if (offset > code_pos)
pfilter_dbg("microcode: comparison offset is bigger than current PC. Insert some nops before comparing"); pfilter_dbg
("microcode: comparison offset is bigger than current PC. Insert some nops before comparing");
check_reg_range(rd, 1, 15, "ra/rd"); check_reg_range(rd, 1, 15, "ra/rd");
check_reg_range(bit_index, 0, 15, "bit index"); check_reg_range(bit_index, 0, 15, "bit index");
ir = ((1ULL<<33) | PF_MODE_CMP | ((uint64_t)offset << 7) | ((uint64_t)bit_index << 29) | (uint64_t)op | ((uint64_t)rd << 3)); ir = ((1ULL << 33) | PF_MODE_CMP | ((uint64_t) offset << 7) |
((uint64_t) bit_index << 29) | (uint64_t) op | ((uint64_t) rd <<
3));
code_buf[code_pos++] = ir; code_buf[code_pos++] = ir;
} }
void pfilter_nop() void pfilter_nop()
{ {
uint64_t ir; uint64_t ir;
check_size(); check_size();
ir = PF_MODE_LOGIC; ir = PF_MODE_LOGIC;
code_buf[code_pos++] = ir; code_buf[code_pos++] = ir;
} }
// rd = ra op rb // rd = ra op rb
void pfilter_logic2(int rd, int ra, pfilter_op_t op, int rb) void pfilter_logic2(int rd, int ra, pfilter_op_t op, int rb)
{ {
uint64_t ir; uint64_t ir;
check_size(); check_size();
check_reg_range(ra, 0, 31, "ra"); check_reg_range(ra, 0, 31, "ra");
check_reg_range(rb, 0, 31, "rb"); check_reg_range(rb, 0, 31, "rb");
check_reg_range(rd, 1, 31, "rd"); check_reg_range(rd, 1, 31, "rd");
ir = ((uint64_t)ra << 8) | ((uint64_t)rb << 13) | (((uint64_t)rd & 0xf) << 3) | (((uint64_t)rd & 0x10) ? (1ULL<<7) : 0) | (uint64_t)op; ir = ((uint64_t) ra << 8) | ((uint64_t) rb << 13) |
ir = ir | PF_MODE_LOGIC | (3ULL<<23); (((uint64_t) rd & 0xf) << 3) | (((uint64_t) rd & 0x10) ? (1ULL << 7)
code_buf[code_pos++] = ir; : 0) | (uint64_t) op;
ir = ir | PF_MODE_LOGIC | (3ULL << 23);
code_buf[code_pos++] = ir;
} }
static void pfilter_logic3(int rd, int ra, pfilter_op_t op, int rb,
static void pfilter_logic3(int rd, int ra, pfilter_op_t op, int rb, pfilter_op_t op2, int rc) pfilter_op_t op2, int rc)
{ {
uint64_t ir; uint64_t ir;
check_size(); check_size();
check_reg_range(ra, 0, 31, "ra"); check_reg_range(ra, 0, 31, "ra");
check_reg_range(rb, 0, 31, "rb"); check_reg_range(rb, 0, 31, "rb");
check_reg_range(rc, 0, 31, "rb"); check_reg_range(rc, 0, 31, "rb");
check_reg_range(rd, 1, 31, "rd"); check_reg_range(rd, 1, 31, "rd");
ir = (ra << 8) | (rb << 13) | (rc << 18) | ((rd & 0xf) << 3) | ((rd & 0x10) ? (1<<7) : 0) | op; ir = (ra << 8) | (rb << 13) | (rc << 18) | ((rd & 0xf) << 3) |
ir = ir | PF_MODE_LOGIC | (op2<<23); ((rd & 0x10) ? (1 << 7) : 0) | op;
code_buf[code_pos++] = ir; ir = ir | PF_MODE_LOGIC | (op2 << 23);
code_buf[code_pos++] = ir;
} }
/* Terminates the microcode, loads it to the endpoint and enables the pfilter */ /* Terminates the microcode, loads it to the endpoint and enables the pfilter */
void pfilter_load() void pfilter_load()
{ {
int i; int i;
code_buf[code_pos++] = (1ULL<<35); // insert FIN instruction code_buf[code_pos++] = (1ULL << 35); // insert FIN instruction
EP->PFCR0 = 0; // disable pfilter EP->PFCR0 = 0; // disable pfilter
for(i=0;i<code_pos;i++) for (i = 0; i < code_pos; i++) {
{ uint32_t cr0, cr1;
uint32_t cr0, cr1; cr1 = EP_PFCR1_MM_DATA_LSB_W(code_buf[i] & 0xfff);
cr1 = EP_PFCR1_MM_DATA_LSB_W(code_buf[i] & 0xfff); cr0 =
cr0 = EP_PFCR0_MM_ADDR_W(i) | EP_PFCR0_MM_DATA_MSB_W(code_buf[i]>>12) | EP_PFCR0_MM_WRITE_MASK; EP_PFCR0_MM_ADDR_W(i) | EP_PFCR0_MM_DATA_MSB_W(code_buf[i]
>> 12) |
EP_PFCR0_MM_WRITE_MASK;
EP->PFCR1 = cr1; EP->PFCR1 = cr1;
EP->PFCR0 = cr0; EP->PFCR0 = cr0;
} }
EP->PFCR0 = EP_PFCR0_ENABLE; EP->PFCR0 = EP_PFCR0_ENABLE;
} }
/* sample packet filter initialization: /* sample packet filter initialization:
...@@ -221,62 +225,62 @@ void pfilter_load() ...@@ -221,62 +225,62 @@ void pfilter_load()
void pfilter_init_default() void pfilter_init_default()
{ {
pfilter_new(); pfilter_new();
pfilter_nop(); pfilter_nop();
#if WITH_ETHERBONE != 0 #if WITH_ETHERBONE != 0
pfilter_cmp(0, 0xffff, 0xffff, MOV, 1); pfilter_cmp(0, 0xffff, 0xffff, MOV, 1);
pfilter_cmp(1, 0xffff, 0xffff, AND, 1); pfilter_cmp(1, 0xffff, 0xffff, AND, 1);
pfilter_cmp(2, 0xffff, 0xffff, AND, 1); /* r1 = 1 when dst mac is broadcast */ pfilter_cmp(2, 0xffff, 0xffff, AND, 1); /* r1 = 1 when dst mac is broadcast */
pfilter_cmp(0, 0x011b, 0xffff, MOV, 2); pfilter_cmp(0, 0x011b, 0xffff, MOV, 2);
pfilter_cmp(1, 0x1900, 0xffff, AND, 2); pfilter_cmp(1, 0x1900, 0xffff, AND, 2);
pfilter_cmp(2, 0x0000, 0xffff, AND, 2); /* r2 = 1 when dst mac is PTP multicast (01:1b:19:00:00:00) */ pfilter_cmp(2, 0x0000, 0xffff, AND, 2); /* r2 = 1 when dst mac is PTP multicast (01:1b:19:00:00:00) */
pfilter_cmp(0, EP->MACH & 0xffff, 0xffff, MOV, 3); pfilter_cmp(0, EP->MACH & 0xffff, 0xffff, MOV, 3);
pfilter_cmp(1, EP->MACL >> 16, 0xffff, AND, 3); pfilter_cmp(1, EP->MACL >> 16, 0xffff, AND, 3);
pfilter_cmp(2, EP->MACL & 0xffff, 0xffff, AND, 3); /* r3 = 1 when the packet is unicast to our own MAC */ pfilter_cmp(2, EP->MACL & 0xffff, 0xffff, AND, 3); /* r3 = 1 when the packet is unicast to our own MAC */
pfilter_cmp(6, 0x0800, 0xffff, MOV, 4); /* r4 = 1 when ethertype = IPv4 */ pfilter_cmp(6, 0x0800, 0xffff, MOV, 4); /* r4 = 1 when ethertype = IPv4 */
pfilter_cmp(6, 0x88f7, 0xffff, MOV, 5); /* r5 = 1 when ethertype = PTPv2 */ pfilter_cmp(6, 0x88f7, 0xffff, MOV, 5); /* r5 = 1 when ethertype = PTPv2 */
pfilter_cmp(6, 0x0806, 0xffff, MOV, 6); /* r6 = 1 when ethertype = ARP */ pfilter_cmp(6, 0x0806, 0xffff, MOV, 6); /* r6 = 1 when ethertype = ARP */
/* Ethernet = 14 bytes, Offset to type in IP: 8 bytes = 22/2 = 11 */ /* Ethernet = 14 bytes, Offset to type in IP: 8 bytes = 22/2 = 11 */
pfilter_cmp(11,0x0001, 0x00ff, MOV, 7); /* r7 = 1 when IP type = ICMP */ pfilter_cmp(11, 0x0001, 0x00ff, MOV, 7); /* r7 = 1 when IP type = ICMP */
pfilter_cmp(11,0x0011, 0x00ff, MOV, 8); /* r8 = 1 when IP type = UDP */ pfilter_cmp(11, 0x0011, 0x00ff, MOV, 8); /* r8 = 1 when IP type = UDP */
pfilter_logic3(10, 3, OR, 0, AND, 4); /* r10 = IP(unicast) */ pfilter_logic3(10, 3, OR, 0, AND, 4); /* r10 = IP(unicast) */
pfilter_logic3(11, 1, OR, 3, AND, 4); /* r11 = IP(unicast+broadcast) */ pfilter_logic3(11, 1, OR, 3, AND, 4); /* r11 = IP(unicast+broadcast) */
pfilter_logic3(14, 1, AND, 6, OR, 5); /* r14 = ARP(broadcast) or PTPv2 */ pfilter_logic3(14, 1, AND, 6, OR, 5); /* r14 = ARP(broadcast) or PTPv2 */
pfilter_logic3(15, 10, AND, 7, OR, 14); /* r15 = ICMP/IP(unicast) or ARP(broadcast) or PTPv2 */ pfilter_logic3(15, 10, AND, 7, OR, 14); /* r15 = ICMP/IP(unicast) or ARP(broadcast) or PTPv2 */
/* Ethernet = 14 bytes, IPv4 = 20 bytes, offset to dport: 2 = 36/2 = 18 */ /* Ethernet = 14 bytes, IPv4 = 20 bytes, offset to dport: 2 = 36/2 = 18 */
pfilter_cmp(18, 0x0044, 0xffff, MOV, 14); /* r14 = 1 when dport = BOOTPC */ pfilter_cmp(18, 0x0044, 0xffff, MOV, 14); /* r14 = 1 when dport = BOOTPC */
pfilter_logic3(14, 14, AND, 8, AND, 11); /* r14 = BOOTP/UDP/IP(unicast|broadcast) */ pfilter_logic3(14, 14, AND, 8, AND, 11); /* r14 = BOOTP/UDP/IP(unicast|broadcast) */
pfilter_logic2(15, 14, OR, 15); /* r15 = BOOTP/UDP/IP(unicast|broadcast) or ICMP/IP(unicast) or ARP(broadcast) or PTPv2 */ pfilter_logic2(15, 14, OR, 15); /* r15 = BOOTP/UDP/IP(unicast|broadcast) or ICMP/IP(unicast) or ARP(broadcast) or PTPv2 */
pfilter_logic3(20, 11, AND, 8, OR, 15); /* r16 = Something we accept */ pfilter_logic3(20, 11, AND, 8, OR, 15); /* r16 = Something we accept */
pfilter_logic2(R_DROP, 20, NOT, 0); /* None match? drop */ pfilter_logic2(R_DROP, 20, NOT, 0); /* None match? drop */
pfilter_logic2(R_CLASS(7), 11, AND, 8); /* class 7: UDP/IP(unicast|broadcast) => external fabric */ pfilter_logic2(R_CLASS(7), 11, AND, 8); /* class 7: UDP/IP(unicast|broadcast) => external fabric */
pfilter_logic2(R_CLASS(0), 15, MOV, 0); /* class 0: ICMP/IP(unicast) or ARP(broadcast) or PTPv2 => PTP LM32 core */ pfilter_logic2(R_CLASS(0), 15, MOV, 0); /* class 0: ICMP/IP(unicast) or ARP(broadcast) or PTPv2 => PTP LM32 core */
pfilter_load(); pfilter_load();
#else #else
pfilter_new(); pfilter_new();
pfilter_nop(); pfilter_nop();
pfilter_cmp(0, 0xffff, 0xffff, MOV, 1); pfilter_cmp(0, 0xffff, 0xffff, MOV, 1);
pfilter_cmp(1, 0xffff, 0xffff, AND, 1); pfilter_cmp(1, 0xffff, 0xffff, AND, 1);
pfilter_cmp(2, 0xffff, 0xffff, AND, 1); /* r1 = 1 when dst mac is broadcast */ pfilter_cmp(2, 0xffff, 0xffff, AND, 1); /* r1 = 1 when dst mac is broadcast */
pfilter_cmp(0, 0x011b, 0xffff, MOV, 2); pfilter_cmp(0, 0x011b, 0xffff, MOV, 2);
pfilter_cmp(1, 0x1900, 0xffff, AND, 2); pfilter_cmp(1, 0x1900, 0xffff, AND, 2);
pfilter_cmp(2, 0x0000, 0xffff, AND, 2); /* r2 = 1 when dst mac is PTP multicast (01:1b:19:00:00:00) */ pfilter_cmp(2, 0x0000, 0xffff, AND, 2); /* r2 = 1 when dst mac is PTP multicast (01:1b:19:00:00:00) */
pfilter_cmp(0, EP->MACH & 0xffff, 0xffff, MOV, 3); pfilter_cmp(0, EP->MACH & 0xffff, 0xffff, MOV, 3);
pfilter_cmp(1, EP->MACL >> 16, 0xffff, AND, 3); pfilter_cmp(1, EP->MACL >> 16, 0xffff, AND, 3);
pfilter_cmp(2, EP->MACL & 0xffff, 0xffff, AND, 3); /* r3 = 1 when the packet is unicast to our own MAC */ pfilter_cmp(2, EP->MACL & 0xffff, 0xffff, AND, 3); /* r3 = 1 when the packet is unicast to our own MAC */
pfilter_cmp(6, 0x88f7, 0xffff, MOV, 5); /* r5 = 1 when ethertype = PTPv2 */ pfilter_cmp(6, 0x88f7, 0xffff, MOV, 5); /* r5 = 1 when ethertype = PTPv2 */
pfilter_logic3(6, 3, OR, 2, AND, 5); /* r6 = PTPv2(multicast or unicast) */ pfilter_logic3(6, 3, OR, 2, AND, 5); /* r6 = PTPv2(multicast or unicast) */
pfilter_logic2(R_CLASS(7), 6, NOT, 0); /* class 7: not PTP => external fabric */ pfilter_logic2(R_CLASS(7), 6, NOT, 0); /* class 7: not PTP => external fabric */
pfilter_logic2(R_CLASS(0), 6, MOV, 0); /* class 0: PTPv2 => PTP LM32 core */ pfilter_logic2(R_CLASS(0), 6, MOV, 0); /* class 0: PTPv2 => PTP LM32 core */
pfilter_load(); pfilter_load();
#endif #endif
} }
\ No newline at end of file
...@@ -6,8 +6,9 @@ ...@@ -6,8 +6,9 @@
void mi2c_delay() void mi2c_delay()
{ {
int i; int i;
for(i=0;i<I2C_DELAY;i++) asm volatile ("nop"); for (i = 0; i < I2C_DELAY; i++)
asm volatile ("nop");
} }
#define M_SDA_OUT(i, x) { gpio_out(i2c_if[i].sda, x); mi2c_delay(); } #define M_SDA_OUT(i, x) { gpio_out(i2c_if[i].sda, x); mi2c_delay(); }
...@@ -16,96 +17,92 @@ void mi2c_delay() ...@@ -16,96 +17,92 @@ void mi2c_delay()
void mi2c_start(uint8_t i2cif) void mi2c_start(uint8_t i2cif)
{ {
M_SDA_OUT(i2cif, 0); M_SDA_OUT(i2cif, 0);
M_SCL_OUT(i2cif, 0); M_SCL_OUT(i2cif, 0);
} }
void mi2c_repeat_start(uint8_t i2cif) void mi2c_repeat_start(uint8_t i2cif)
{ {
M_SDA_OUT(i2cif, 1); M_SDA_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 1);
M_SDA_OUT(i2cif, 0); M_SDA_OUT(i2cif, 0);
M_SCL_OUT(i2cif, 0); M_SCL_OUT(i2cif, 0);
} }
void mi2c_stop(uint8_t i2cif) void mi2c_stop(uint8_t i2cif)
{ {
M_SDA_OUT(i2cif, 0); M_SDA_OUT(i2cif, 0);
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 1);
M_SDA_OUT(i2cif, 1); M_SDA_OUT(i2cif, 1);
} }
unsigned char mi2c_put_byte(uint8_t i2cif, unsigned char data) unsigned char mi2c_put_byte(uint8_t i2cif, unsigned char data)
{ {
char i; char i;
unsigned char ack; unsigned char ack;
for (i=0;i<8;i++, data<<=1) for (i = 0; i < 8; i++, data <<= 1) {
{ M_SDA_OUT(i2cif, data & 0x80);
M_SDA_OUT(i2cif, data&0x80); M_SCL_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 0);
M_SCL_OUT(i2cif, 0); }
}
M_SDA_OUT(i2cif, 1); M_SDA_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 1);
ack = M_SDA_IN(i2cif); /* ack: sda is pulled low ->success. */ ack = M_SDA_IN(i2cif); /* ack: sda is pulled low ->success. */
M_SCL_OUT(i2cif, 0); M_SCL_OUT(i2cif, 0);
M_SDA_OUT(i2cif, 0); M_SDA_OUT(i2cif, 0);
return ack!=0; return ack != 0;
} }
void mi2c_get_byte(uint8_t i2cif, unsigned char *data, uint8_t last) void mi2c_get_byte(uint8_t i2cif, unsigned char *data, uint8_t last)
{ {
int i; int i;
unsigned char indata = 0; unsigned char indata = 0;
M_SDA_OUT(i2cif, 1); M_SDA_OUT(i2cif, 1);
/* assert: scl is low */ /* assert: scl is low */
M_SCL_OUT(i2cif, 0); M_SCL_OUT(i2cif, 0);
for (i=0;i<8;i++) for (i = 0; i < 8; i++) {
{ M_SCL_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 1); indata <<= 1;
indata <<= 1; if (M_SDA_IN(i2cif))
if ( M_SDA_IN(i2cif) ) indata |= 0x01; indata |= 0x01;
M_SCL_OUT(i2cif, 0); M_SCL_OUT(i2cif, 0);
} }
if(last) if (last) {
{ M_SDA_OUT(i2cif, 1); //noack
M_SDA_OUT(i2cif, 1); //noack M_SCL_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 0);
M_SCL_OUT(i2cif, 0); } else {
} M_SDA_OUT(i2cif, 0); //ack
else M_SCL_OUT(i2cif, 1);
{ M_SCL_OUT(i2cif, 0);
M_SDA_OUT(i2cif, 0); //ack }
M_SCL_OUT(i2cif, 1);
M_SCL_OUT(i2cif, 0); *data = indata;
}
*data= indata;
} }
void mi2c_init(uint8_t i2cif) void mi2c_init(uint8_t i2cif)
{ {
M_SCL_OUT(i2cif, 1); M_SCL_OUT(i2cif, 1);
M_SDA_OUT(i2cif, 1); M_SDA_OUT(i2cif, 1);
} }
uint8_t mi2c_devprobe(uint8_t i2cif, uint8_t i2c_addr) uint8_t mi2c_devprobe(uint8_t i2cif, uint8_t i2c_addr)
{ {
uint8_t ret; uint8_t ret;
mi2c_start(i2cif); mi2c_start(i2cif);
ret = !mi2c_put_byte(i2cif, i2c_addr<<1); ret = !mi2c_put_byte(i2cif, i2c_addr << 1);
mi2c_stop(i2cif); mi2c_stop(i2cif);
return ret; return ret;
} }
//void mi2c_scan(uint8_t i2cif) //void mi2c_scan(uint8_t i2cif)
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#include "types.h" #include "types.h"
#include "board.h" #include "board.h"
#include "pps_gen.h" /* for pps_gen_get_time() */ #include "pps_gen.h" /* for pps_gen_get_time() */
#include "minic.h" #include "minic.h"
#include <hw/minic_regs.h> #include <hw/minic_regs.h>
...@@ -37,106 +37,112 @@ ...@@ -37,106 +37,112 @@
rc = (raw) & 0xfffffff; \ rc = (raw) & 0xfffffff; \
fc = (raw >> 28) & 0xf; fc = (raw >> 28) & 0xf;
static volatile uint32_t dma_tx_buf[MINIC_DMA_TX_BUF_SIZE / 4]; static volatile uint32_t dma_tx_buf[MINIC_DMA_TX_BUF_SIZE / 4];
static volatile uint32_t dma_rx_buf[MINIC_DMA_RX_BUF_SIZE / 4]; static volatile uint32_t dma_rx_buf[MINIC_DMA_RX_BUF_SIZE / 4];
struct wr_minic { struct wr_minic {
volatile uint32_t *rx_head, *rx_base; volatile uint32_t *rx_head, *rx_base;
uint32_t rx_avail, rx_size; uint32_t rx_avail, rx_size;
volatile uint32_t *tx_head, *tx_base; volatile uint32_t *tx_head, *tx_base;
uint32_t tx_avail, tx_size; uint32_t tx_avail, tx_size;
int tx_count, rx_count; int tx_count, rx_count;
}; };
static struct wr_minic minic; static struct wr_minic minic;
static inline void minic_writel(uint32_t reg,uint32_t data) static inline void minic_writel(uint32_t reg, uint32_t data)
{ {
*(volatile uint32_t *) (BASE_MINIC + reg) = data; *(volatile uint32_t *)(BASE_MINIC + reg) = data;
} }
static inline uint32_t minic_readl(uint32_t reg) static inline uint32_t minic_readl(uint32_t reg)
{ {
return *(volatile uint32_t *)(BASE_MINIC + reg); return *(volatile uint32_t *)(BASE_MINIC + reg);
} }
/* /*
* uint32_t size - in bytes * uint32_t size - in bytes
*/ */
static uint8_t * minic_rx_memcpy( uint8_t *dst, uint8_t *src, uint32_t size) static uint8_t *minic_rx_memcpy(uint8_t * dst, uint8_t * src, uint32_t size)
{ {
uint32_t part; uint32_t part;
//if src is outside the circular buffer, bring it back to the beginning //if src is outside the circular buffer, bring it back to the beginning
src = (uint8_t *) ((uint32_t)minic.rx_base + ((uint32_t)src - (uint32_t)minic.rx_base) % (minic.rx_size<<2)); src = (uint8_t *)((uint32_t)minic.rx_base +
((uint32_t)src - (uint32_t) minic.rx_base)
if((uint32_t)src + size <= (uint32_t)minic.rx_base + (minic.rx_size<<2)) % (minic.rx_size << 2));
return memcpy(dst, src, size);
if ((uint32_t)src + size <= (uint32_t)minic.rx_base
part = (uint32_t)minic.rx_base + (minic.rx_size<<2) - (uint32_t)src; + (minic.rx_size << 2))
memcpy(dst, src, part); return memcpy(dst, src, size);
memcpy((void*) (dst+part), (void*)minic.rx_base, size - part);
return dst; part = (uint32_t)minic.rx_base + (minic.rx_size << 2) - (uint32_t)src;
memcpy(dst, src, part);
memcpy((void *)(dst + part), (void *)minic.rx_base, size - part);
return dst;
} }
/* /*
* uint32_t size - in bytes * uint32_t size - in bytes
*/ */
static uint8_t *minic_rx_memset( uint8_t *mem, uint8_t c, uint32_t size) static uint8_t *minic_rx_memset(uint8_t * mem, uint8_t c, uint32_t size)
{ {
uint32_t part; uint32_t part;
uint32_t *src; uint32_t *src;
//if src is outside the circular buffer, bring it back to the beginning
src = (uint32_t*)((uint32_t)minic.rx_base + ((uint32_t)mem - (uint32_t)minic.rx_base) % (minic.rx_size<<2));
if((uint32_t)src + size <= (uint32_t)minic.rx_base + (minic.rx_size<<2)) //if src is outside the circular buffer, bring it back to the beginning
return memset((void*)src, c, size); src = (uint32_t *)((uint32_t)minic.rx_base +
((uint32_t) mem - (uint32_t) minic.rx_base)
% (minic.rx_size << 2));
part = (uint32_t)minic.rx_base + (minic.rx_size<<2) - (uint32_t)src; if ((uint32_t) src + size <= (uint32_t) minic.rx_base
memset(src, c, part); + (minic.rx_size << 2))
memset((void*)minic.rx_base, c, size - part); return memset((void *)src, c, size);
return (uint8_t*)src; part = (uint32_t) minic.rx_base + (minic.rx_size << 2) - (uint32_t) src;
memset(src, c, part);
memset((void *)minic.rx_base, c, size - part);
return (uint8_t *) src;
} }
static void minic_new_rx_buffer() static void minic_new_rx_buffer()
{ {
minic_writel(MINIC_REG_MCR, 0); minic_writel(MINIC_REG_MCR, 0);
minic.rx_base = dma_rx_buf; minic.rx_base = dma_rx_buf;
minic.rx_size = MINIC_DMA_RX_BUF_SIZE/4; minic.rx_size = MINIC_DMA_RX_BUF_SIZE / 4;
minic.rx_head = minic.rx_base; minic.rx_head = minic.rx_base;
minic_rx_memset((uint8_t*)minic.rx_base, 0x00, minic.rx_size<<2); minic_rx_memset((uint8_t *) minic.rx_base, 0x00, minic.rx_size << 2);
minic_writel(MINIC_REG_RX_ADDR, (uint32_t) minic.rx_base); minic_writel(MINIC_REG_RX_ADDR, (uint32_t) minic.rx_base);
minic_writel(MINIC_REG_RX_SIZE, minic.rx_size); minic_writel(MINIC_REG_RX_SIZE, minic.rx_size);
//new buffer allocated, clear any old RX interrupts //new buffer allocated, clear any old RX interrupts
minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX); minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX);
minic_writel(MINIC_REG_MCR, MINIC_MCR_RX_EN); minic_writel(MINIC_REG_MCR, MINIC_MCR_RX_EN);
} }
static void minic_rxbuf_free(uint32_t words) static void minic_rxbuf_free(uint32_t words)
{ {
minic_rx_memset((uint8_t*)minic.rx_head, 0x00, words<<2); minic_rx_memset((uint8_t *) minic.rx_head, 0x00, words << 2);
minic_writel(MINIC_REG_RX_AVAIL, words); minic_writel(MINIC_REG_RX_AVAIL, words);
} }
static void minic_new_tx_buffer() static void minic_new_tx_buffer()
{ {
minic.tx_base = dma_tx_buf; minic.tx_base = dma_tx_buf;
minic.tx_size = MINIC_DMA_TX_BUF_SIZE>>2; minic.tx_size = MINIC_DMA_TX_BUF_SIZE >> 2;
minic.tx_head = minic.tx_base; minic.tx_head = minic.tx_base;
minic.tx_avail = minic.tx_size; minic.tx_avail = minic.tx_size;
minic_writel(MINIC_REG_TX_ADDR, (uint32_t) minic.tx_base); minic_writel(MINIC_REG_TX_ADDR, (uint32_t) minic.tx_base);
} }
void minic_init() void minic_init()
{ {
uint32_t lo , hi; uint32_t lo, hi;
minic_writel(MINIC_REG_EIC_IDR, MINIC_EIC_IDR_RX); minic_writel(MINIC_REG_EIC_IDR, MINIC_EIC_IDR_RX);
minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX); minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX);
minic.rx_base = dma_rx_buf; minic.rx_base = dma_rx_buf;
minic.rx_size = sizeof(dma_rx_buf); minic.rx_size = sizeof(dma_rx_buf);
...@@ -144,13 +150,14 @@ void minic_init() ...@@ -144,13 +150,14 @@ void minic_init()
very well hidden bug in Minic's RX logic which sometimes causes an overwrite of the memory outside very well hidden bug in Minic's RX logic which sometimes causes an overwrite of the memory outside
the buffer. */ the buffer. */
lo = (uint32_t)minic.rx_base >> 2; lo = (uint32_t) minic.rx_base >> 2;
hi = ((uint32_t)minic.rx_base >> 2) + (sizeof(dma_rx_buf)>>2) - 1; hi = ((uint32_t) minic.rx_base >> 2) + (sizeof(dma_rx_buf) >> 2) - 1;
minic_writel(MINIC_REG_MPROT, MINIC_MPROT_LO_W(lo) | MINIC_MPROT_HI_W(hi)); minic_writel(MINIC_REG_MPROT,
MINIC_MPROT_LO_W(lo) | MINIC_MPROT_HI_W(hi));
minic.tx_base = dma_tx_buf; minic.tx_base = dma_tx_buf;
minic.tx_size = MINIC_DMA_TX_BUF_SIZE>>2; minic.tx_size = MINIC_DMA_TX_BUF_SIZE >> 2;
minic.tx_count = 0; minic.tx_count = 0;
minic.rx_count = 0; minic.rx_count = 0;
...@@ -161,180 +168,186 @@ void minic_init() ...@@ -161,180 +168,186 @@ void minic_init()
void minic_disable() void minic_disable()
{ {
minic_writel(MINIC_REG_MCR, 0); minic_writel(MINIC_REG_MCR, 0);
} }
int minic_poll_rx() int minic_poll_rx()
{ {
uint32_t isr; uint32_t isr;
isr = minic_readl(MINIC_REG_EIC_ISR); isr = minic_readl(MINIC_REG_EIC_ISR);
return (isr & MINIC_EIC_ISR_RX) ? 1 : 0; return (isr & MINIC_EIC_ISR_RX) ? 1 : 0;
} }
int minic_rx_frame(uint8_t *hdr, uint8_t *payload, uint32_t buf_size, struct hw_timestamp *hwts) int minic_rx_frame(uint8_t * hdr, uint8_t * payload, uint32_t buf_size,
struct hw_timestamp *hwts)
{ {
uint32_t payload_size, num_words; uint32_t payload_size, num_words;
uint32_t desc_hdr; uint32_t desc_hdr;
uint32_t raw_ts; uint32_t raw_ts;
uint32_t rx_addr_cur, cur_avail; uint32_t rx_addr_cur, cur_avail;
int n_recvd; int n_recvd;
if(! (minic_readl(MINIC_REG_EIC_ISR) & MINIC_EIC_ISR_RX)) if (!(minic_readl(MINIC_REG_EIC_ISR) & MINIC_EIC_ISR_RX))
return 0; return 0;
desc_hdr = *minic.rx_head; desc_hdr = *minic.rx_head;
if(!RX_DESC_VALID(desc_hdr)) /* invalid descriptor? Weird, the RX_ADDR seems to be saying something different. Ignore the packet and purge the RX buffer. */ if (!RX_DESC_VALID(desc_hdr)) { /* invalid descriptor? Weird, the RX_ADDR seems to be saying something different. Ignore the packet and purge the RX buffer. */
{
//invalid descriptor ? then probably the interrupt was generated by full rx buffer //invalid descriptor ? then probably the interrupt was generated by full rx buffer
if(minic_readl(MINIC_REG_MCR) & MINIC_MCR_RX_FULL) if (minic_readl(MINIC_REG_MCR) & MINIC_MCR_RX_FULL) {
minic_new_rx_buffer(); minic_new_rx_buffer();
else } else {
{
//otherwise, weird !! //otherwise, weird !!
mprintf("invalid descriptor @%x = %x\n", (uint32_t)minic.rx_head, desc_hdr); mprintf("invalid descriptor @%x = %x\n",
(uint32_t) minic.rx_head, desc_hdr);
minic_new_rx_buffer(); minic_new_rx_buffer();
} }
return 0; return 0;
} }
payload_size = RX_DESC_SIZE(desc_hdr); payload_size = RX_DESC_SIZE(desc_hdr);
num_words = ((payload_size + 3) >> 2) + 1; num_words = ((payload_size + 3) >> 2) + 1;
/* valid packet */
/* valid packet */ if (!RX_DESC_ERROR(desc_hdr)) {
if(!RX_DESC_ERROR(desc_hdr))
{ if (RX_DESC_HAS_OOB(desc_hdr) && hwts != NULL) {
uint32_t counter_r, counter_f, counter_ppsg;
if(RX_DESC_HAS_OOB(desc_hdr) && hwts != NULL) uint64_t sec;
{ int cntr_diff;
uint32_t counter_r, counter_f, counter_ppsg; uint16_t dhdr;
uint64_t sec;
int cntr_diff; payload_size -= RX_OOB_SIZE;
uint16_t dhdr;
/* fixme: ugly way of doing unaligned read */
payload_size -= RX_OOB_SIZE; minic_rx_memcpy((uint8_t *) & raw_ts,
(uint8_t *) minic.rx_head
minic_rx_memcpy((uint8_t *)&raw_ts, (uint8_t *)minic.rx_head + payload_size + 6, 4); /* fixme: ugly way of doing unaligned read */ + payload_size + 6, 4);
minic_rx_memcpy((uint8_t *)&dhdr, (uint8_t *)minic.rx_head + payload_size + 4, 2); minic_rx_memcpy((uint8_t *) & dhdr,
EXPLODE_WR_TIMESTAMP(raw_ts, counter_r, counter_f); (uint8_t *) minic.rx_head +
payload_size + 4, 2);
pps_gen_get_time(&sec, &counter_ppsg); EXPLODE_WR_TIMESTAMP(raw_ts, counter_r, counter_f);
if(counter_r > 3*REF_CLOCK_FREQ_HZ/4 && counter_ppsg < 250000000) pps_gen_get_time(&sec, &counter_ppsg);
sec--;
if (counter_r > 3 * REF_CLOCK_FREQ_HZ / 4
&& counter_ppsg < 250000000)
sec--;
hwts->sec = sec & 0x7fffffff ; hwts->sec = sec & 0x7fffffff;
cntr_diff = (counter_r & F_COUNTER_MASK) - counter_f; cntr_diff = (counter_r & F_COUNTER_MASK) - counter_f;
if(cntr_diff == 1 || cntr_diff == (-F_COUNTER_MASK)) if (cntr_diff == 1 || cntr_diff == (-F_COUNTER_MASK))
hwts->ahead = 1; hwts->ahead = 1;
else else
hwts->ahead = 0; hwts->ahead = 0;
hwts->nsec = counter_r * (REF_CLOCK_PERIOD_PS/1000); hwts->nsec = counter_r * (REF_CLOCK_PERIOD_PS / 1000);
hwts->valid = (dhdr & RXOOB_TS_INCORRECT) ? 0 : 1; hwts->valid = (dhdr & RXOOB_TS_INCORRECT) ? 0 : 1;
} }
n_recvd = (buf_size < payload_size ? buf_size : payload_size); n_recvd = (buf_size < payload_size ? buf_size : payload_size);
minic.rx_count++; minic.rx_count++;
minic_rx_memcpy(hdr, (void*)minic.rx_head + 4, ETH_HEADER_SIZE); minic_rx_memcpy(hdr, (void *)minic.rx_head + 4,
minic_rx_memcpy(payload, (void*)minic.rx_head + 4 + ETH_HEADER_SIZE, n_recvd - ETH_HEADER_SIZE); ETH_HEADER_SIZE);
} minic_rx_memcpy(payload, (void *)minic.rx_head + 4
else { + ETH_HEADER_SIZE, n_recvd - ETH_HEADER_SIZE);
n_recvd = -1; } else {
} n_recvd = -1;
}
minic_rxbuf_free(num_words); minic_rxbuf_free(num_words);
minic.rx_head = (uint32_t *)((uint32_t)minic.rx_base + ((uint32_t)minic.rx_head+(num_words<<2) - (uint32_t)minic.rx_base) % (minic.rx_size<<2)); minic.rx_head = (uint32_t *)((uint32_t)minic.rx_base +
((uint32_t) minic.rx_head
+ (num_words << 2) - (uint32_t)minic.rx_base)
% (minic.rx_size << 2));
cur_avail = minic_readl(MINIC_REG_RX_AVAIL) & 0xFFFFFF; /* 24-bit field */ cur_avail = minic_readl(MINIC_REG_RX_AVAIL) & 0xFFFFFF; /* 24-bit field */
/*empty buffer->no more received packets, or packet reception in progress but not done*/ /*empty buffer->no more received packets, or packet reception in progress but not done */
if( !RX_DESC_VALID(*minic.rx_head)) if (!RX_DESC_VALID(*minic.rx_head)) {
{ if (minic_readl(MINIC_REG_MCR) & MINIC_MCR_RX_FULL)
if(minic_readl(MINIC_REG_MCR) & MINIC_MCR_RX_FULL) minic_new_rx_buffer();
minic_new_rx_buffer();
minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX); minic_writel(MINIC_REG_EIC_ISR, MINIC_EIC_ISR_RX);
} }
return n_recvd; return n_recvd;
} }
int minic_tx_frame(uint8_t * hdr, uint8_t * payload, uint32_t size,
struct hw_timestamp *hwts)
int minic_tx_frame(uint8_t *hdr, uint8_t *payload, uint32_t size, struct hw_timestamp *hwts)
{ {
uint32_t d_hdr, mcr, nwords; uint32_t d_hdr, mcr, nwords;
uint8_t ts_valid; uint8_t ts_valid;
minic_new_tx_buffer(); minic_new_tx_buffer();
memset((void*)minic.tx_head, 0x0, size + 16); memset((void *)minic.tx_head, 0x0, size + 16);
memset((void*)minic.tx_head + 4, 0, size < 60 ? 60 : size); memset((void *)minic.tx_head + 4, 0, size < 60 ? 60 : size);
memcpy((void*)minic.tx_head + 4, hdr, ETH_HEADER_SIZE); memcpy((void *)minic.tx_head + 4, hdr, ETH_HEADER_SIZE);
memcpy((void*)minic.tx_head + 4 + ETH_HEADER_SIZE, payload, size - ETH_HEADER_SIZE); memcpy((void *)minic.tx_head + 4 + ETH_HEADER_SIZE, payload,
size - ETH_HEADER_SIZE);
if(size < 60) if (size < 60)
size = 60; size = 60;
nwords = ((size + 1) >> 1); nwords = ((size + 1) >> 1);
d_hdr = 0; d_hdr = 0;
if(hwts) if (hwts)
d_hdr = TX_DESC_WITH_OOB | (WRPC_FID<<12); d_hdr = TX_DESC_WITH_OOB | (WRPC_FID << 12);
d_hdr |= TX_DESC_VALID | nwords; d_hdr |= TX_DESC_VALID | nwords;
*(volatile uint32_t *)(minic.tx_head) = d_hdr; *(volatile uint32_t *)(minic.tx_head) = d_hdr;
*(volatile uint32_t *)(minic.tx_head + nwords) = 0; *(volatile uint32_t *)(minic.tx_head + nwords) = 0;
mcr = minic_readl(MINIC_REG_MCR); mcr = minic_readl(MINIC_REG_MCR);
minic_writel(MINIC_REG_MCR, mcr | MINIC_MCR_TX_START); minic_writel(MINIC_REG_MCR, mcr | MINIC_MCR_TX_START);
while((minic_readl(MINIC_REG_MCR) & MINIC_MCR_TX_IDLE) == 0); while ((minic_readl(MINIC_REG_MCR) & MINIC_MCR_TX_IDLE) == 0) ;
if(hwts) /* wait for the timestamp */ if (hwts) { /* wait for the timestamp */
{ uint32_t raw_ts;
uint32_t raw_ts; uint16_t fid;
uint16_t fid; uint32_t counter_r, counter_f;
uint32_t counter_r, counter_f; uint64_t sec;
uint64_t sec; uint32_t nsec;
uint32_t nsec;
ts_valid = (uint8_t) (minic_readl(MINIC_REG_TSR0) & MINIC_TSR0_VALID); ts_valid = (uint8_t)(minic_readl(MINIC_REG_TSR0)
& MINIC_TSR0_VALID);
raw_ts = minic_readl(MINIC_REG_TSR1); raw_ts = minic_readl(MINIC_REG_TSR1);
fid = MINIC_TSR0_FID_R(minic_readl(MINIC_REG_TSR0)); fid = MINIC_TSR0_FID_R(minic_readl(MINIC_REG_TSR0));
if(fid != WRPC_FID) if (fid != WRPC_FID) {
{ TRACE_DEV("minic_tx_frame: unmatched fid %d vs %d\n",
TRACE_DEV("minic_tx_frame: unmatched fid %d vs %d\n", fid, WRPC_FID); fid, WRPC_FID);
} }
EXPLODE_WR_TIMESTAMP(raw_ts, counter_r, counter_f); EXPLODE_WR_TIMESTAMP(raw_ts, counter_r, counter_f);
pps_gen_get_time(&sec, &nsec); pps_gen_get_time(&sec, &nsec);
if(counter_r > 3*REF_CLOCK_FREQ_HZ/4 && nsec < 250000000) if (counter_r > 3 * REF_CLOCK_FREQ_HZ / 4 && nsec < 250000000)
sec--; sec--;
hwts->valid = ts_valid; hwts->valid = ts_valid;
hwts->sec = sec; hwts->sec = sec;
hwts->ahead = 0; hwts->ahead = 0;
hwts->nsec = counter_r * 8; hwts->nsec = counter_r * 8;
// TRACE_DEV("minic_tx_frame [%d bytes] TS: %d.%d valid %d\n", size, hwts->utc, hwts->nsec, hwts->valid); // TRACE_DEV("minic_tx_frame [%d bytes] TS: %d.%d valid %d\n", size, hwts->utc, hwts->nsec, hwts->valid);
minic.tx_count++; minic.tx_count++;
} }
return size; return size;
} }
void minic_get_stats(int *tx_frames, int *rx_frames) void minic_get_stats(int *tx_frames, int *rx_frames)
{ {
*tx_frames = minic.tx_count; *tx_frames = minic.tx_count;
*rx_frames = minic.rx_count; *rx_frames = minic.rx_count;
} }
...@@ -10,106 +10,115 @@ uint8_t found_msk; ...@@ -10,106 +10,115 @@ uint8_t found_msk;
void own_scanbus(uint8_t portnum) void own_scanbus(uint8_t portnum)
{ {
// Find the device(s) // Find the device(s)
found_msk = 0; found_msk = 0;
devsnum = 0; devsnum = 0;
devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x28, MAX_DEV1WIRE - devsnum); /* Temperature 28 sensor (SPEC) */ devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x28, MAX_DEV1WIRE - devsnum); /* Temperature 28 sensor (SPEC) */
if(devsnum>0) found_msk |= FOUND_DS18B20; if (devsnum > 0)
devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x42, MAX_DEV1WIRE - devsnum); /* Temperature 42 sensor (SCU) */ found_msk |= FOUND_DS18B20;
devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x43, MAX_DEV1WIRE - devsnum); /* EEPROM */ devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x42, MAX_DEV1WIRE - devsnum); /* Temperature 42 sensor (SCU) */
devsnum += FindDevices(portnum, &FamilySN[devsnum], 0x43, MAX_DEV1WIRE - devsnum); /* EEPROM */
#if DEBUG_PMAC #if DEBUG_PMAC
mprintf("Found %d onewire devices\n", devsnum); mprintf("Found %d onewire devices\n", devsnum);
#endif #endif
} }
int16_t own_readtemp(uint8_t portnum, int16_t *temp, int16_t *t_frac) int16_t own_readtemp(uint8_t portnum, int16_t * temp, int16_t * t_frac)
{ {
if(!(found_msk & FOUND_DS18B20)) if (!(found_msk & FOUND_DS18B20))
return -1; return -1;
if(ReadTemperature28(portnum, FamilySN[0], temp)) if (ReadTemperature28(portnum, FamilySN[0], temp)) {
{ *t_frac =
*t_frac = 5000*(!!(*temp & 0x08)) + 2500*(!!(*temp & 0x04)) + 1250*(!!(*temp & 0x02)) + 5000 * (! !(*temp & 0x08)) + 2500 * (! !(*temp & 0x04)) +
625*(!!(*temp & 0x01)); 1250 * (! !(*temp & 0x02)) + 625 * (! !(*temp & 0x01));
*t_frac = *t_frac/100 + (*t_frac%100)/50; *t_frac = *t_frac / 100 + (*t_frac % 100) / 50;
*temp >>= 4; *temp >>= 4;
return 0; return 0;
} }
return -1; return -1;
} }
/* 0 = success, -1 = error */ /* 0 = success, -1 = error */
int8_t get_persistent_mac(uint8_t portnum, uint8_t* mac) int8_t get_persistent_mac(uint8_t portnum, uint8_t * mac)
{ {
uint8_t read_buffer[32]; uint8_t read_buffer[32];
uint8_t i; uint8_t i;
int8_t out; int8_t out;
out = -1; out = -1;
if(devsnum == 0) return out; if (devsnum == 0)
return out;
for (i = 0; i < devsnum; ++i) { for (i = 0; i < devsnum; ++i) {
//#if DEBUG_PMAC //#if DEBUG_PMAC
mprintf("Found device: %x:%x:%x:%x:%x:%x:%x:%x\n", mprintf("Found device: %x:%x:%x:%x:%x:%x:%x:%x\n",
FamilySN[i][7], FamilySN[i][6], FamilySN[i][5], FamilySN[i][4], FamilySN[i][7], FamilySN[i][6], FamilySN[i][5], FamilySN[i][4],
FamilySN[i][3], FamilySN[i][2], FamilySN[i][1], FamilySN[i][0]); FamilySN[i][3], FamilySN[i][2], FamilySN[i][1], FamilySN[i][0]);
//#endif //#endif
/* If there is a temperature sensor, use it for the low three MAC values */ /* If there is a temperature sensor, use it for the low three MAC values */
if (FamilySN[i][0] == 0x28 || FamilySN[i][0] == 0x42) { if (FamilySN[i][0] == 0x28 || FamilySN[i][0] == 0x42) {
mac[3] = FamilySN[i][3]; mac[3] = FamilySN[i][3];
mac[4] = FamilySN[i][2]; mac[4] = FamilySN[i][2];
mac[5] = FamilySN[i][1]; mac[5] = FamilySN[i][1];
out = 0; out = 0;
#if DEBUG_PMAC #if DEBUG_PMAC
mprintf("Using temperature ID for MAC\n"); mprintf("Using temperature ID for MAC\n");
#endif #endif
} }
/* If there is an EEPROM, read page 0 for the MAC */ /* If there is an EEPROM, read page 0 for the MAC */
if (FamilySN[i][0] == 0x43) { if (FamilySN[i][0] == 0x43) {
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
if (ReadMem43(portnum, FamilySN[i], EEPROM_MAC_PAGE, &read_buffer) == TRUE) { if (ReadMem43(portnum, FamilySN[i], EEPROM_MAC_PAGE,
if (read_buffer[0] == 0 && read_buffer[1] == 0 && read_buffer[2] == 0) { &read_buffer) == TRUE) {
/* Skip the EEPROM since it has not been programmed! */ if (read_buffer[0] == 0 && read_buffer[1] == 0
&& read_buffer[2] == 0) {
/* Skip the EEPROM since it has not been programmed! */
#if DEBUG_PMAC #if DEBUG_PMAC
mprintf("EEPROM has not been programmed with a MAC\n"); mprintf("EEPROM has not been "
"programmed with a MAC\n");
#endif #endif
} else { } else {
memcpy(mac, read_buffer, 6); memcpy(mac, read_buffer, 6);
out = 0; out = 0;
#if DEBUG_PMAC #if DEBUG_PMAC
mprintf("Using EEPROM page: %x:%x:%x:%x:%x:%x\n", mprintf("Using EEPROM page: "
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); "%x:%x:%x:%x:%x:%x\n",
mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5]);
#endif #endif
} }
} }
} }
} }
return out; return out;
} }
/* 0 = success, -1 = error */ /* 0 = success, -1 = error */
int8_t set_persistent_mac(uint8_t portnum, uint8_t* mac) int8_t set_persistent_mac(uint8_t portnum, uint8_t * mac)
{ {
uint8_t FamilySN[1][8]; uint8_t FamilySN[1][8];
uint8_t write_buffer[32]; uint8_t write_buffer[32];
// Find the device (only the first one, we won't write MAC to all EEPROMs out there, right?) // Find the device (only the first one, we won't write MAC to all EEPROMs out there, right?)
if( FindDevices(portnum, &FamilySN[0], 0x43, 1) == 0) return -1; if (FindDevices(portnum, &FamilySN[0], 0x43, 1) == 0)
return -1;
memset(write_buffer, 0, sizeof(write_buffer)); memset(write_buffer, 0, sizeof(write_buffer));
memcpy(write_buffer, mac, 6); memcpy(write_buffer, mac, 6);
#if DEBUG_PMAC #if DEBUG_PMAC
mprintf("Writing to EEPROM\n"); mprintf("Writing to EEPROM\n");
#endif #endif
/* Write the last EEPROM with the MAC */ /* Write the last EEPROM with the MAC */
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
if (Write43(portnum, FamilySN[0], EEPROM_MAC_PAGE, &write_buffer) == TRUE) if (Write43(portnum, FamilySN[0], EEPROM_MAC_PAGE, &write_buffer) ==
return 0; TRUE)
return 0;
return -1; return -1;
} }
...@@ -24,50 +24,54 @@ int pps_gen_init() ...@@ -24,50 +24,54 @@ int pps_gen_init()
cr = PPSG_CR_CNT_EN | PPSG_CR_PWIDTH_W(PPS_WIDTH); cr = PPSG_CR_CNT_EN | PPSG_CR_PWIDTH_W(PPS_WIDTH);
ppsg_write(CR, cr); ppsg_write(CR, cr);
ppsg_write(ADJ_UTCLO, 0); ppsg_write(ADJ_UTCLO, 0);
ppsg_write(ADJ_UTCHI, 0); ppsg_write(ADJ_UTCHI, 0);
ppsg_write(ADJ_NSEC, 0); ppsg_write(ADJ_NSEC, 0);
ppsg_write(CR, cr | PPSG_CR_CNT_SET); ppsg_write(CR, cr | PPSG_CR_CNT_SET);
ppsg_write(CR, cr); ppsg_write(CR, cr);
ppsg_write(ESCR, 0x6); /* enable PPS output */ ppsg_write(ESCR, 0x6); /* enable PPS output */
} }
/* Adjusts the nanosecond (refclk cycle) counter by atomically adding (how_much) cycles. */ /* Adjusts the nanosecond (refclk cycle) counter by atomically adding (how_much) cycles. */
int pps_gen_adjust(int counter, int64_t how_much) int pps_gen_adjust(int counter, int64_t how_much)
{ {
uint32_t cr; uint32_t cr;
TRACE_DEV("Adjust: counter = %s [%c%d]\n", TRACE_DEV("Adjust: counter = %s [%c%d]\n",
counter == PPSG_ADJUST_SEC ? "seconds" : "nanoseconds", how_much<0?'-':'+', (int32_t)abs(how_much)); counter == PPSG_ADJUST_SEC ? "seconds" : "nanoseconds",
how_much < 0 ? '-' : '+', (int32_t) abs(how_much));
if(counter == PPSG_ADJUST_NSEC) if (counter == PPSG_ADJUST_NSEC) {
{ ppsg_write(ADJ_UTCLO, 0);
ppsg_write(ADJ_UTCLO, 0); ppsg_write(ADJ_UTCHI, 0);
ppsg_write(ADJ_UTCHI, 0); ppsg_write(ADJ_NSEC,
ppsg_write(ADJ_NSEC, (int32_t) ((int64_t) how_much * 1000LL / (int64_t)REF_CLOCK_PERIOD_PS)); (int32_t) ((int64_t) how_much * 1000LL /
(int64_t) REF_CLOCK_PERIOD_PS));
} else { } else {
ppsg_write(ADJ_UTCLO, (uint32_t ) (how_much & 0xffffffffLL)); ppsg_write(ADJ_UTCLO, (uint32_t) (how_much & 0xffffffffLL));
ppsg_write(ADJ_UTCHI, (uint32_t ) (how_much >> 32) & 0xff); ppsg_write(ADJ_UTCHI, (uint32_t) (how_much >> 32) & 0xff);
ppsg_write(ADJ_NSEC, 0); ppsg_write(ADJ_NSEC, 0);
} }
ppsg_write(CR, ppsg_read(CR) | PPSG_CR_CNT_ADJ); ppsg_write(CR, ppsg_read(CR) | PPSG_CR_CNT_ADJ);
return 0; return 0;
} }
/* Sets the current time */ /* Sets the current time */
int pps_gen_set_time(uint64_t seconds, uint32_t nanoseconds) int pps_gen_set_time(uint64_t seconds, uint32_t nanoseconds)
{ {
uint32_t cr; uint32_t cr;
ppsg_write(ADJ_UTCLO, (uint32_t ) (seconds & 0xffffffffLL)); ppsg_write(ADJ_UTCLO, (uint32_t) (seconds & 0xffffffffLL));
ppsg_write(ADJ_UTCHI, (uint32_t ) (seconds >> 32) & 0xff); ppsg_write(ADJ_UTCHI, (uint32_t) (seconds >> 32) & 0xff);
ppsg_write(ADJ_NSEC, (int32_t) ((int64_t) nanoseconds * 1000LL / (int64_t)REF_CLOCK_PERIOD_PS)); ppsg_write(ADJ_NSEC,
(int32_t) ((int64_t) nanoseconds * 1000LL /
(int64_t) REF_CLOCK_PERIOD_PS));
ppsg_write(CR, (ppsg_read(CR) & 0xfffffffb) | PPSG_CR_CNT_SET); ppsg_write(CR, (ppsg_read(CR) & 0xfffffffb) | PPSG_CR_CNT_SET);
return 0; return 0;
} }
...@@ -76,45 +80,51 @@ uint64_t pps_get_utc(void) ...@@ -76,45 +80,51 @@ uint64_t pps_get_utc(void)
uint64_t out; uint64_t out;
uint32_t low, high; uint32_t low, high;
low = ppsg_read(CNTR_UTCLO); low = ppsg_read(CNTR_UTCLO);
high = ppsg_read(CNTR_UTCHI); high = ppsg_read(CNTR_UTCHI);
high &= 0xFF; /* CNTR_UTCHI has only 8 bits defined -- rest are HDL don't care */ high &= 0xFF; /* CNTR_UTCHI has only 8 bits defined -- rest are HDL don't care */
out = (uint64_t)low | (uint64_t)high << 32; out = (uint64_t) low | (uint64_t) high << 32;
return out; return out;
} }
void pps_gen_get_time(uint64_t *seconds, uint32_t *nanoseconds) void pps_gen_get_time(uint64_t * seconds, uint32_t * nanoseconds)
{ {
uint32_t ns_cnt; uint32_t ns_cnt;
uint64_t sec1, sec2; uint64_t sec1, sec2;
do { do {
sec1 = pps_get_utc(); sec1 = pps_get_utc();
ns_cnt = ppsg_read(CNTR_NSEC) & 0xFFFFFFFUL; /* 28-bit wide register */ ns_cnt = ppsg_read(CNTR_NSEC) & 0xFFFFFFFUL; /* 28-bit wide register */
sec2 = pps_get_utc(); sec2 = pps_get_utc();
} while(sec2 != sec1); } while (sec2 != sec1);
if(seconds) *seconds = sec2; if (seconds)
if(nanoseconds) *nanoseconds = (uint32_t) ((int64_t)ns_cnt * (int64_t) REF_CLOCK_PERIOD_PS / 1000LL); *seconds = sec2;
if (nanoseconds)
*nanoseconds =
(uint32_t) ((int64_t) ns_cnt *
(int64_t) REF_CLOCK_PERIOD_PS / 1000LL);
} }
/* Returns 1 when the adjustment operation is not yet finished */ /* Returns 1 when the adjustment operation is not yet finished */
int pps_gen_busy() int pps_gen_busy()
{ {
uint32_t cr = ppsg_read(CR); uint32_t cr = ppsg_read(CR);
return cr & PPSG_CR_CNT_ADJ ? 0 : 1; return cr & PPSG_CR_CNT_ADJ ? 0 : 1;
} }
/* Enables/disables PPS output */ /* Enables/disables PPS output */
int pps_gen_enable_output(int enable) int pps_gen_enable_output(int enable)
{ {
uint32_t escr = ppsg_read(ESCR); uint32_t escr = ppsg_read(ESCR);
if(enable) if (enable)
ppsg_write(ESCR, escr | PPSG_ESCR_PPS_VALID | PPSG_ESCR_TM_VALID); ppsg_write(ESCR,
else escr | PPSG_ESCR_PPS_VALID | PPSG_ESCR_TM_VALID);
ppsg_write(ESCR, escr & ~(PPSG_ESCR_PPS_VALID | PPSG_ESCR_TM_VALID)); else
ppsg_write(ESCR,
escr & ~(PPSG_ESCR_PPS_VALID | PPSG_ESCR_TM_VALID));
return 0; return 0;
} }
...@@ -6,123 +6,135 @@ ...@@ -6,123 +6,135 @@
#define SDB_EMPTY 0xFF #define SDB_EMPTY 0xFF
typedef struct pair64 { typedef struct pair64 {
uint32_t high; uint32_t high;
uint32_t low; uint32_t low;
} pair64_t; } pair64_t;
struct sdb_empty { struct sdb_empty {
int8_t reserved[63]; int8_t reserved[63];
uint8_t record_type; uint8_t record_type;
}; };
struct sdb_product { struct sdb_product {
pair64_t vendor_id; pair64_t vendor_id;
uint32_t device_id; uint32_t device_id;
uint32_t version; uint32_t version;
uint32_t date; uint32_t date;
int8_t name[19]; int8_t name[19];
uint8_t record_type; uint8_t record_type;
}; };
struct sdb_component { struct sdb_component {
pair64_t addr_first; pair64_t addr_first;
pair64_t addr_last; pair64_t addr_last;
struct sdb_product product; struct sdb_product product;
}; };
struct sdb_device { struct sdb_device {
uint16_t abi_class; uint16_t abi_class;
uint8_t abi_ver_major; uint8_t abi_ver_major;
uint8_t abi_ver_minor; uint8_t abi_ver_minor;
uint32_t bus_specific; uint32_t bus_specific;
struct sdb_component sdb_component; struct sdb_component sdb_component;
}; };
struct sdb_bridge { struct sdb_bridge {
pair64_t sdb_child; pair64_t sdb_child;
struct sdb_component sdb_component; struct sdb_component sdb_component;
}; };
struct sdb_interconnect { struct sdb_interconnect {
uint32_t sdb_magic; uint32_t sdb_magic;
uint16_t sdb_records; uint16_t sdb_records;
uint8_t sdb_version; uint8_t sdb_version;
uint8_t sdb_bus_type; uint8_t sdb_bus_type;
struct sdb_component sdb_component; struct sdb_component sdb_component;
}; };
typedef union sdb_record { typedef union sdb_record {
struct sdb_empty empty; struct sdb_empty empty;
struct sdb_device device; struct sdb_device device;
struct sdb_bridge bridge; struct sdb_bridge bridge;
struct sdb_interconnect interconnect; struct sdb_interconnect interconnect;
} sdb_record_t; } sdb_record_t;
static unsigned char* find_device_deep(unsigned int base, unsigned int sdb, unsigned int devid) { static unsigned char *find_device_deep(unsigned int base, unsigned int sdb,
sdb_record_t* record = (sdb_record_t*)sdb; unsigned int devid)
int records = record->interconnect.sdb_records; {
int i; sdb_record_t *record = (sdb_record_t *) sdb;
int records = record->interconnect.sdb_records;
for (i = 0; i < records; ++i, ++record) { int i;
if (record->empty.record_type == SDB_BRIDGE) {
unsigned char* out = for (i = 0; i < records; ++i, ++record) {
find_device_deep( if (record->empty.record_type == SDB_BRIDGE) {
base + record->bridge.sdb_component.addr_first.low, unsigned char *out =
record->bridge.sdb_child.low, find_device_deep(base +
devid); record->bridge.sdb_component.
if (out) return out; addr_first.low,
} record->bridge.sdb_child.low,
if (record->empty.record_type == SDB_DEVICE && devid);
record->device.sdb_component.product.device_id == devid) { if (out)
break; return out;
} }
} if (record->empty.record_type == SDB_DEVICE &&
record->device.sdb_component.product.device_id == devid) {
if (i == records) return 0; break;
return (unsigned char*)(base + record->device.sdb_component.addr_first.low); }
}
if (i == records)
return 0;
return (unsigned char *)(base +
record->device.sdb_component.addr_first.low);
} }
static void print_devices_deep(unsigned int base, unsigned int sdb) { static void print_devices_deep(unsigned int base, unsigned int sdb)
sdb_record_t* record = (sdb_record_t*)sdb; {
int records = record->interconnect.sdb_records; sdb_record_t *record = (sdb_record_t *) sdb;
int i; int records = record->interconnect.sdb_records;
char buf[20]; int i;
char buf[20];
for (i = 0; i < records; ++i, ++record) {
if (record->empty.record_type == SDB_BRIDGE) for (i = 0; i < records; ++i, ++record) {
print_devices_deep( if (record->empty.record_type == SDB_BRIDGE)
base + record->bridge.sdb_component.addr_first.low, print_devices_deep(base +
record->bridge.sdb_child.low); record->bridge.sdb_component.
addr_first.low,
if (record->empty.record_type != SDB_DEVICE) continue; record->bridge.sdb_child.low);
memcpy(buf, record->device.sdb_component.product.name, 19); if (record->empty.record_type != SDB_DEVICE)
buf[19] = 0; continue;
mprintf("%8x:%8x 0x%8x %s\n",
record->device.sdb_component.product.vendor_id.low, memcpy(buf, record->device.sdb_component.product.name, 19);
record->device.sdb_component.product.device_id, buf[19] = 0;
base + record->device.sdb_component.addr_first.low, mprintf("%8x:%8x 0x%8x %s\n",
buf); record->device.sdb_component.product.vendor_id.low,
} record->device.sdb_component.product.device_id,
base + record->device.sdb_component.addr_first.low,
buf);
}
} }
static unsigned char* find_device(unsigned int devid) { static unsigned char *find_device(unsigned int devid)
find_device_deep(0, SDB_ADDRESS, devid); {
find_device_deep(0, SDB_ADDRESS, devid);
} }
void sdb_print_devices(void) { void sdb_print_devices(void)
mprintf("SDB memory map:\n"); {
print_devices_deep(0, SDB_ADDRESS); mprintf("SDB memory map:\n");
mprintf("---\n"); print_devices_deep(0, SDB_ADDRESS);
mprintf("---\n");
} }
void sdb_find_devices(void) { void sdb_find_devices(void)
BASE_MINIC = find_device(0xab28633a); {
BASE_EP = find_device(0x650c2d4f); BASE_MINIC = find_device(0xab28633a);
BASE_SOFTPLL = find_device(0x65158dc0); BASE_EP = find_device(0x650c2d4f);
BASE_PPS_GEN = find_device(0xde0d8ced); BASE_SOFTPLL = find_device(0x65158dc0);
BASE_SYSCON = find_device(0xff07fc47); BASE_PPS_GEN = find_device(0xde0d8ced);
BASE_UART = find_device(0xe2d13d04); BASE_SYSCON = find_device(0xff07fc47);
BASE_ONEWIRE = find_device(0x779c5443); BASE_UART = find_device(0xe2d13d04);
BASE_ETHERBONE_CFG = find_device(0x68202b22); BASE_ONEWIRE = find_device(0x779c5443);
BASE_ETHERBONE_CFG = find_device(0x68202b22);
} }
...@@ -16,32 +16,31 @@ int sfp_read_part_id(char *part_id) ...@@ -16,32 +16,31 @@ int sfp_read_part_id(char *part_id)
{ {
int i; int i;
uint8_t data, sum; uint8_t data, sum;
mi2c_init(WRPC_SFP_I2C); mi2c_init(WRPC_SFP_I2C);
mi2c_start(WRPC_SFP_I2C); mi2c_start(WRPC_SFP_I2C);
mi2c_put_byte(WRPC_SFP_I2C, 0xA0); mi2c_put_byte(WRPC_SFP_I2C, 0xA0);
mi2c_put_byte(WRPC_SFP_I2C, 0x00); mi2c_put_byte(WRPC_SFP_I2C, 0x00);
mi2c_repeat_start(WRPC_SFP_I2C); mi2c_repeat_start(WRPC_SFP_I2C);
mi2c_put_byte(WRPC_SFP_I2C, 0xA1); mi2c_put_byte(WRPC_SFP_I2C, 0xA1);
mi2c_get_byte(WRPC_SFP_I2C, &data, 1); mi2c_get_byte(WRPC_SFP_I2C, &data, 1);
mi2c_stop(WRPC_SFP_I2C); mi2c_stop(WRPC_SFP_I2C);
sum = data; sum = data;
mi2c_start(WRPC_SFP_I2C); mi2c_start(WRPC_SFP_I2C);
mi2c_put_byte(WRPC_SFP_I2C, 0xA1); mi2c_put_byte(WRPC_SFP_I2C, 0xA1);
for(i=1; i<63; ++i) for (i = 1; i < 63; ++i) {
{ mi2c_get_byte(WRPC_SFP_I2C, &data, 0);
mi2c_get_byte(WRPC_SFP_I2C, &data, 0); sum = (uint8_t) ((uint16_t) sum + data) & 0xff;
sum = (uint8_t) ((uint16_t)sum + data) & 0xff; if (i >= 40 && i <= 55) //Part Number
if(i>=40 && i<=55) //Part Number part_id[i - 40] = data;
part_id[i-40] = data; }
} mi2c_get_byte(WRPC_SFP_I2C, &data, 1); //final word, checksum
mi2c_get_byte(WRPC_SFP_I2C, &data, 1); //final word, checksum mi2c_stop(WRPC_SFP_I2C);
mi2c_stop(WRPC_SFP_I2C);
if (sum == data)
if(sum == data) return 0;
return 0;
return -1;
return -1;
} }
#include "syscon.h" #include "syscon.h"
struct s_i2c_if i2c_if[2] = { {SYSC_GPSR_FMC_SCL, SYSC_GPSR_FMC_SDA}, struct s_i2c_if i2c_if[2] = {
{SYSC_GPSR_SFP_SCL, SYSC_GPSR_SFP_SDA} }; {SYSC_GPSR_FMC_SCL, SYSC_GPSR_FMC_SDA},
{SYSC_GPSR_SFP_SCL, SYSC_GPSR_SFP_SDA}
};
volatile struct SYSCON_WB *syscon; volatile struct SYSCON_WB *syscon;
...@@ -10,28 +12,27 @@ volatile struct SYSCON_WB *syscon; ...@@ -10,28 +12,27 @@ volatile struct SYSCON_WB *syscon;
***************************/ ***************************/
void timer_init(uint32_t enable) void timer_init(uint32_t enable)
{ {
syscon = (volatile struct SYSCON_WB *) BASE_SYSCON; syscon = (volatile struct SYSCON_WB *)BASE_SYSCON;
if(enable) if (enable)
syscon->TCR |= SYSC_TCR_ENABLE; syscon->TCR |= SYSC_TCR_ENABLE;
else else
syscon->TCR &= ~SYSC_TCR_ENABLE; syscon->TCR &= ~SYSC_TCR_ENABLE;
} }
uint32_t timer_get_tics() uint32_t timer_get_tics()
{ {
return syscon->TVR; return syscon->TVR;
} }
void timer_delay(uint32_t how_long) void timer_delay(uint32_t how_long)
{ {
uint32_t t_start; uint32_t t_start;
// timer_init(1); // timer_init(1);
do do {
{ t_start = timer_get_tics();
t_start = timer_get_tics(); } while (t_start > UINT32_MAX - how_long); //in case of overflow
} while(t_start > UINT32_MAX - how_long); //in case of overflow
while(t_start + how_long > timer_get_tics()); while (t_start + how_long > timer_get_tics()) ;
} }
...@@ -4,14 +4,14 @@ ...@@ -4,14 +4,14 @@
uint32_t timer_get_tics() uint32_t timer_get_tics()
{ {
return *(volatile uint32_t *) (BASE_TIMER); return *(volatile uint32_t *)(BASE_TIMER);
} }
void timer_delay(uint32_t how_long) void timer_delay(uint32_t how_long)
{ {
uint32_t t_start; uint32_t t_start;
t_start = timer_get_tics(); t_start = timer_get_tics();
while(t_start + how_long > timer_get_tics()); while (t_start + how_long > timer_get_tics()) ;
} }
...@@ -13,16 +13,15 @@ volatile struct UART_WB *uart; ...@@ -13,16 +13,15 @@ volatile struct UART_WB *uart;
void uart_init() void uart_init()
{ {
uart = (volatile struct UART_WB *) BASE_UART; uart = (volatile struct UART_WB *)BASE_UART;
uart->BCR = CALC_BAUD(UART_BAUDRATE); uart->BCR = CALC_BAUD(UART_BAUDRATE);
} }
void uart_write_byte(int b) void uart_write_byte(int b)
{ {
if(b == '\n') if (b == '\n')
uart_write_byte('\r'); uart_write_byte('\r');
while(uart->SR & UART_SR_TX_BUSY) while (uart->SR & UART_SR_TX_BUSY) ;
;
uart->TDR = b; uart->TDR = b;
} }
...@@ -34,13 +33,13 @@ void uart_write_string(char *s) ...@@ -34,13 +33,13 @@ void uart_write_string(char *s)
int uart_poll() int uart_poll()
{ {
return uart->SR & UART_SR_RX_RDY; return uart->SR & UART_SR_RX_RDY;
} }
int uart_read_byte() int uart_read_byte()
{ {
if(!uart_poll()) if (!uart_poll())
return -1; return -1;
return uart->RDR & 0xff; return uart->RDR & 0xff;
} }
\ No newline at end of file
...@@ -19,28 +19,32 @@ extern int32_t sfp_deltaRx; ...@@ -19,28 +19,32 @@ extern int32_t sfp_deltaRx;
extern uint32_t cal_phase_transition; extern uint32_t cal_phase_transition;
extern uint8_t has_eeprom; extern uint8_t has_eeprom;
struct s_sfpinfo struct s_sfpinfo {
{ char pn[SFP_PN_LEN];
char pn[SFP_PN_LEN]; int32_t alpha;
int32_t alpha; int32_t dTx;
int32_t dTx; int32_t dRx;
int32_t dRx; uint8_t chksum;
uint8_t chksum; } __attribute__ ((__packed__));
} __attribute__((__packed__));
uint8_t eeprom_present(uint8_t i2cif, uint8_t i2c_addr); uint8_t eeprom_present(uint8_t i2cif, uint8_t i2c_addr);
int eeprom_read(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t *buf, size_t size); int eeprom_read(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t * buf,
int eeprom_write(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset, uint8_t *buf, size_t size); size_t size);
int eeprom_write(uint8_t i2cif, uint8_t i2c_addr, uint32_t offset,
uint8_t * buf, size_t size);
int32_t eeprom_sfpdb_erase(uint8_t i2cif, uint8_t i2c_addr); int32_t eeprom_sfpdb_erase(uint8_t i2cif, uint8_t i2c_addr);
int32_t eeprom_sfp_section(uint8_t i2cif, uint8_t i2c_addr, size_t size, uint16_t *section_sz); int32_t eeprom_sfp_section(uint8_t i2cif, uint8_t i2c_addr, size_t size,
int8_t eeprom_match_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo* sfp); uint16_t * section_sz);
int8_t eeprom_match_sfp(uint8_t i2cif, uint8_t i2c_addr, struct s_sfpinfo *sfp);
int8_t eeprom_phtrans(uint8_t i2cif, uint8_t i2c_addr, uint32_t *val, uint8_t write); int8_t eeprom_phtrans(uint8_t i2cif, uint8_t i2c_addr, uint32_t * val,
uint8_t write);
int8_t eeprom_init_erase(uint8_t i2cif, uint8_t i2c_addr); int8_t eeprom_init_erase(uint8_t i2cif, uint8_t i2c_addr);
int8_t eeprom_init_add(uint8_t i2cif, uint8_t i2c_addr, const char *args[]); int8_t eeprom_init_add(uint8_t i2cif, uint8_t i2c_addr, const char *args[]);
int32_t eeprom_init_show(uint8_t i2cif, uint8_t i2c_addr); int32_t eeprom_init_show(uint8_t i2cif, uint8_t i2c_addr);
int8_t eeprom_init_readcmd(uint8_t i2cif, uint8_t i2c_addr, char* buf, uint8_t bufsize, uint8_t next); int8_t eeprom_init_readcmd(uint8_t i2cif, uint8_t i2c_addr, char *buf,
uint8_t bufsize, uint8_t next);
#endif #endif
...@@ -7,23 +7,23 @@ ...@@ -7,23 +7,23 @@
#include <stdint.h> #include <stdint.h>
typedef enum { typedef enum {
AND=0, AND = 0,
NAND=4, NAND = 4,
OR=1, OR = 1,
NOR=5, NOR = 5,
XOR=2, XOR = 2,
XNOR=6, XNOR = 6,
MOV=3, MOV = 3,
NOT=7 NOT = 7
} pfilter_op_t; } pfilter_op_t;
void ep_init(uint8_t mac_addr[]); void ep_init(uint8_t mac_addr[]);
void get_mac_addr(uint8_t dev_addr[]); void get_mac_addr(uint8_t dev_addr[]);
void set_mac_addr(uint8_t dev_addr[]); void set_mac_addr(uint8_t dev_addr[]);
int ep_enable(int enabled, int autoneg); int ep_enable(int enabled, int autoneg);
int ep_link_up(uint16_t *lpa); int ep_link_up(uint16_t * lpa);
int ep_get_deltas(uint32_t *delta_tx, uint32_t *delta_rx); int ep_get_deltas(uint32_t * delta_tx, uint32_t * delta_rx);
int ep_get_psval(int32_t *psval); int ep_get_psval(int32_t * psval);
int ep_cal_pattern_enable(); int ep_cal_pattern_enable();
int ep_cal_pattern_disable(); int ep_cal_pattern_disable();
...@@ -32,7 +32,8 @@ void pfilter_cmp(int offset, int value, int mask, pfilter_op_t op, int rd); ...@@ -32,7 +32,8 @@ void pfilter_cmp(int offset, int value, int mask, pfilter_op_t op, int rd);
void pfilter_btst(int offset, int bit_index, pfilter_op_t op, int rd); void pfilter_btst(int offset, int bit_index, pfilter_op_t op, int rd);
void pfilter_nop(); void pfilter_nop();
void pfilter_logic2(int rd, int ra, pfilter_op_t op, int rb); void pfilter_logic2(int rd, int ra, pfilter_op_t op, int rb);
static void pfilter_logic3(int rd, int ra, pfilter_op_t op, int rb, pfilter_op_t op2, int rc); static void pfilter_logic3(int rd, int ra, pfilter_op_t op, int rb,
pfilter_op_t op2, int rc);
void pfilter_load(); void pfilter_load();
void pfilter_init_default(); void pfilter_init_default();
......
...@@ -30,7 +30,6 @@ ...@@ -30,7 +30,6 @@
#define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value)) #define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value))
#endif #endif
/* definitions for register: MDIO Control Register */ /* definitions for register: MDIO Control Register */
/* definitions for field: Reserved in reg: MDIO Control Register */ /* definitions for field: Reserved in reg: MDIO Control Register */
......
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
#define SDB_ADDRESS 0x30000 #define SDB_ADDRESS 0x30000
unsigned char* BASE_MINIC; unsigned char *BASE_MINIC;
unsigned char* BASE_EP; unsigned char *BASE_EP;
unsigned char* BASE_SOFTPLL; unsigned char *BASE_SOFTPLL;
unsigned char* BASE_PPS_GEN; unsigned char *BASE_PPS_GEN;
unsigned char* BASE_SYSCON; unsigned char *BASE_SYSCON;
unsigned char* BASE_UART; unsigned char *BASE_UART;
unsigned char* BASE_ONEWIRE; unsigned char *BASE_ONEWIRE;
unsigned char* BASE_ETHERBONE_CFG; unsigned char *BASE_ETHERBONE_CFG;
#define FMC_EEPROM_ADR 0x50 #define FMC_EEPROM_ADR 0x50
......
...@@ -30,7 +30,6 @@ ...@@ -30,7 +30,6 @@
#define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value)) #define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value))
#endif #endif
/* definitions for register: Status Register */ /* definitions for register: Status Register */
/* definitions for field: TX busy in reg: Status Register */ /* definitions for field: TX busy in reg: Status Register */
...@@ -66,14 +65,14 @@ ...@@ -66,14 +65,14 @@
#define UART_REG_RDR 0x0000000c #define UART_REG_RDR 0x0000000c
PACKED struct UART_WB { PACKED struct UART_WB {
/* [0x0]: REG Status Register */ /* [0x0]: REG Status Register */
uint32_t SR; uint32_t SR;
/* [0x4]: REG Baudrate control register */ /* [0x4]: REG Baudrate control register */
uint32_t BCR; uint32_t BCR;
/* [0x8]: REG Transmit data regsiter */ /* [0x8]: REG Transmit data regsiter */
uint32_t TDR; uint32_t TDR;
/* [0xc]: REG Receive data regsiter */ /* [0xc]: REG Receive data regsiter */
uint32_t RDR; uint32_t RDR;
}; };
#endif #endif
...@@ -30,7 +30,6 @@ ...@@ -30,7 +30,6 @@
#define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value)) #define WBGEN2_SIGN_EXTEND(value, bits) (((value) & (1<<bits) ? ~((1<<(bits))-1): 0 ) | (value))
#endif #endif
/* definitions for register: Status Register */ /* definitions for register: Status Register */
/* definitions for field: TX busy in reg: Status Register */ /* definitions for field: TX busy in reg: Status Register */
...@@ -80,18 +79,18 @@ ...@@ -80,18 +79,18 @@
#define UART_DEBUG_CSR_USEDW_R(reg) WBGEN2_GEN_READ(reg, 0, 8) #define UART_DEBUG_CSR_USEDW_R(reg) WBGEN2_GEN_READ(reg, 0, 8)
PACKED struct UART_WB { PACKED struct UART_WB {
/* [0x0]: REG Status Register */ /* [0x0]: REG Status Register */
uint32_t SR; uint32_t SR;
/* [0x4]: REG Baudrate control register */ /* [0x4]: REG Baudrate control register */
uint32_t BCR; uint32_t BCR;
/* [0x8]: REG Transmit data regsiter */ /* [0x8]: REG Transmit data regsiter */
uint32_t TDR; uint32_t TDR;
/* [0xc]: REG Receive data regsiter */ /* [0xc]: REG Receive data regsiter */
uint32_t RDR; uint32_t RDR;
/* [0x10]: REG FIFO 'UART TX FIFO' data output register 0 */ /* [0x10]: REG FIFO 'UART TX FIFO' data output register 0 */
uint32_t DEBUG_R0; uint32_t DEBUG_R0;
/* [0x14]: REG FIFO 'UART TX FIFO' control/status register */ /* [0x14]: REG FIFO 'UART TX FIFO' control/status register */
uint32_t DEBUG_CSR; uint32_t DEBUG_CSR;
}; };
#endif #endif
#ifndef __I2C_H #ifndef __I2C_H
#define __I2C_H #define __I2C_H
uint8_t mi2c_devprobe(uint8_t i2cif, uint8_t i2c_addr); uint8_t mi2c_devprobe(uint8_t i2cif, uint8_t i2c_addr);
void mi2c_init(uint8_t i2cif); void mi2c_init(uint8_t i2cif);
void mi2c_start(uint8_t i2cif); void mi2c_start(uint8_t i2cif);
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
static inline void clear_irq() static inline void clear_irq()
{ {
unsigned int val = 1; unsigned int val = 1;
asm volatile ("wcsr ip, %0"::"r"(val)); asm volatile ("wcsr ip, %0"::"r" (val));
} }
void disable_irq(); void disable_irq();
......
...@@ -11,9 +11,9 @@ void minic_disable(); ...@@ -11,9 +11,9 @@ void minic_disable();
int minic_poll_rx(); int minic_poll_rx();
void minic_get_stats(int *tx_frames, int *rx_frames); void minic_get_stats(int *tx_frames, int *rx_frames);
int minic_rx_frame(uint8_t *hdr, uint8_t *payload, uint32_t buf_size, struct hw_timestamp *hwts); int minic_rx_frame(uint8_t * hdr, uint8_t * payload, uint32_t buf_size,
int minic_tx_frame(uint8_t *hdr, uint8_t *payload, uint32_t size, struct hw_timestamp *hwts); struct hw_timestamp *hwts);
int minic_tx_frame(uint8_t * hdr, uint8_t * payload, uint32_t size,
struct hw_timestamp *hwts);
#endif #endif
...@@ -8,9 +8,9 @@ ...@@ -8,9 +8,9 @@
#define FOUND_DS18B20 0x01 #define FOUND_DS18B20 0x01
void own_scanbus(uint8_t portnum); void own_scanbus(uint8_t portnum);
int16_t own_readtemp(uint8_t portnum, int16_t *temp, int16_t *t_frac); int16_t own_readtemp(uint8_t portnum, int16_t * temp, int16_t * t_frac);
/* 0 = success, -1 = error */ /* 0 = success, -1 = error */
int8_t get_persistent_mac(uint8_t portnum, uint8_t* mac); int8_t get_persistent_mac(uint8_t portnum, uint8_t * mac);
int8_t set_persistent_mac(uint8_t portnum, uint8_t* mac); int8_t set_persistent_mac(uint8_t portnum, uint8_t * mac);
#endif #endif
...@@ -19,10 +19,9 @@ int shw_pps_gen_busy(); ...@@ -19,10 +19,9 @@ int shw_pps_gen_busy();
int shw_pps_gen_enable_output(int enable); int shw_pps_gen_enable_output(int enable);
/* Reads the current time and stores at <seconds,nanoseconds>. */ /* Reads the current time and stores at <seconds,nanoseconds>. */
void shw_pps_gen_get_time(uint64_t *seconds, uint32_t *nanoseconds); void shw_pps_gen_get_time(uint64_t * seconds, uint32_t * nanoseconds);
/* Sets the time to <seconds,nanoseconds>. */ /* Sets the time to <seconds,nanoseconds>. */
void shw_pps_gen_set_time(uint64_t seconds, uint32_t nanoseconds); void shw_pps_gen_set_time(uint64_t seconds, uint32_t nanoseconds);
#endif #endif
...@@ -12,4 +12,3 @@ int sfp_present(); ...@@ -12,4 +12,3 @@ int sfp_present();
int sfp_read_part_id(char *part_id); int sfp_read_part_id(char *part_id);
#endif #endif
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
extern int wrc_ui_mode; extern int wrc_ui_mode;
const char* fromhex(const char* hex, int* v); const char *fromhex(const char *hex, int *v);
const char* fromdec(const char* dec, int* v); const char *fromdec(const char *dec, int *v);
int cmd_gui(const char *args[]); int cmd_gui(const char *args[]);
int cmd_pll(const char *args[]); int cmd_pll(const char *args[]);
...@@ -25,7 +25,6 @@ int cmd_sdb(const char *args[]); ...@@ -25,7 +25,6 @@ int cmd_sdb(const char *args[]);
int cmd_mac(const char *args[]); int cmd_mac(const char *args[]);
int cmd_init(const char *args[]); int cmd_init(const char *args[]);
int cmd_env(const char *args[]); int cmd_env(const char *args[]);
int cmd_saveenv(const char *args[]); int cmd_saveenv(const char *args[]);
int cmd_set(const char *args[]); int cmd_set(const char *args[]);
...@@ -40,4 +39,3 @@ void shell_interactive(); ...@@ -40,4 +39,3 @@ void shell_interactive();
int shell_boot_script(void); int shell_boot_script(void);
#endif #endif
...@@ -6,7 +6,6 @@ WARNING: These parameters must be in sync with the generics of the HDL instantia ...@@ -6,7 +6,6 @@ WARNING: These parameters must be in sync with the generics of the HDL instantia
*/ */
#include <stdio.h> #include <stdio.h>
/* Reference clock frequency, in [Hz] */ /* Reference clock frequency, in [Hz] */
......
...@@ -6,14 +6,13 @@ ...@@ -6,14 +6,13 @@
#include "board.h" #include "board.h"
#include <hw/wrc_syscon_regs.h> #include <hw/wrc_syscon_regs.h>
struct SYSCON_WB struct SYSCON_WB {
{ uint32_t RSTR; /*Syscon Reset Register */
uint32_t RSTR; /*Syscon Reset Register*/ uint32_t GPSR; /*GPIO Set/Readback Register */
uint32_t GPSR; /*GPIO Set/Readback Register*/ uint32_t GPCR; /*GPIO Clear Register */
uint32_t GPCR; /*GPIO Clear Register*/ uint32_t HWFR; /*Hardware Feature Register */
uint32_t HWFR; /*Hardware Feature Register*/ uint32_t TCR; /*Timer Control Register */
uint32_t TCR; /*Timer Control Register*/ uint32_t TVR; /*Timer Counter Value Register */
uint32_t TVR; /*Timer Counter Value Register*/
}; };
/*GPIO pins*/ /*GPIO pins*/
...@@ -26,10 +25,9 @@ struct SYSCON_WB ...@@ -26,10 +25,9 @@ struct SYSCON_WB
#define WRPC_FMC_I2C 0 #define WRPC_FMC_I2C 0
#define WRPC_SFP_I2C 1 #define WRPC_SFP_I2C 1
struct s_i2c_if struct s_i2c_if {
{ uint32_t scl;
uint32_t scl; uint32_t sda;
uint32_t sda;
}; };
extern struct s_i2c_if i2c_if[2]; extern struct s_i2c_if i2c_if[2];
...@@ -45,15 +43,15 @@ extern volatile struct SYSCON_WB *syscon; ...@@ -45,15 +43,15 @@ extern volatile struct SYSCON_WB *syscon;
***************************/ ***************************/
static inline void gpio_out(int pin, int val) static inline void gpio_out(int pin, int val)
{ {
if(val) if (val)
syscon->GPSR = pin; syscon->GPSR = pin;
else else
syscon->GPCR = pin; syscon->GPCR = pin;
} }
static inline int gpio_in(int pin) static inline int gpio_in(int pin)
{ {
return syscon->GPSR & pin ? 1: 0; return syscon->GPSR & pin ? 1 : 0;
} }
static inline int sysc_get_memsize() static inline int sysc_get_memsize()
...@@ -62,4 +60,3 @@ static inline int sysc_get_memsize() ...@@ -62,4 +60,3 @@ static inline int sysc_get_memsize()
} }
#endif #endif
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
#include <inttypes.h> #include <inttypes.h>
struct hw_timestamp { struct hw_timestamp {
uint8_t valid; uint8_t valid;
int ahead; int ahead;
uint64_t sec; uint64_t sec;
uint32_t nsec; uint32_t nsec;
uint32_t phase; uint32_t phase;
}; };
#endif #endif
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#include "ipv4.h" #include "ipv4.h"
#include "ptpd_netif.h" #include "ptpd_netif.h"
static wr_socket_t* arp_socket; static wr_socket_t *arp_socket;
#define ARP_HTYPE 0 #define ARP_HTYPE 0
#define ARP_PTYPE (ARP_HTYPE+2) #define ARP_PTYPE (ARP_HTYPE+2)
...@@ -16,67 +16,73 @@ static wr_socket_t* arp_socket; ...@@ -16,67 +16,73 @@ static wr_socket_t* arp_socket;
#define ARP_TPA (ARP_THA+6) #define ARP_TPA (ARP_THA+6)
#define ARP_END (ARP_TPA+4) #define ARP_END (ARP_TPA+4)
void arp_init(const char* if_name) { void arp_init(const char *if_name)
wr_sockaddr_t saddr; {
wr_sockaddr_t saddr;
/* Configure socket filter */ /* Configure socket filter */
memset(&saddr, 0, sizeof(saddr)); memset(&saddr, 0, sizeof(saddr));
strcpy(saddr.if_name, if_name); strcpy(saddr.if_name, if_name);
memset(&saddr.mac, 0xFF, 6); /* Broadcast */ memset(&saddr.mac, 0xFF, 6); /* Broadcast */
saddr.ethertype = htons(0x0806); /* ARP */ saddr.ethertype = htons(0x0806); /* ARP */
saddr.family = PTPD_SOCK_RAW_ETHERNET; saddr.family = PTPD_SOCK_RAW_ETHERNET;
arp_socket = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET, 0, &saddr); arp_socket = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET,
0, &saddr);
} }
static int process_arp(uint8_t* buf, int len) { static int process_arp(uint8_t * buf, int len)
uint8_t hisMAC[6]; {
uint8_t hisIP[4]; uint8_t hisMAC[6];
uint8_t myIP[4]; uint8_t hisIP[4];
uint8_t myIP[4];
if (len < ARP_END) return 0; if (len < ARP_END)
return 0;
/* Is it ARP request targetting our IP? */ /* Is it ARP request targetting our IP? */
getIP(myIP); getIP(myIP);
if (buf[ARP_OPER+0] != 0 || if (buf[ARP_OPER + 0] != 0 ||
buf[ARP_OPER+1] != 1 || buf[ARP_OPER + 1] != 1 || memcmp(buf + ARP_TPA, myIP, 4))
memcmp(buf+ARP_TPA, myIP, 4)) return 0;
return 0;
memcpy(hisMAC, buf+ARP_SHA, 6); memcpy(hisMAC, buf + ARP_SHA, 6);
memcpy(hisIP, buf+ARP_SPA, 4); memcpy(hisIP, buf + ARP_SPA, 4);
// ------------- ARP ------------ // ------------- ARP ------------
// HW ethernet // HW ethernet
buf[ARP_HTYPE+0] = 0; buf[ARP_HTYPE + 0] = 0;
buf[ARP_HTYPE+1] = 1; buf[ARP_HTYPE + 1] = 1;
// proto IP // proto IP
buf[ARP_PTYPE+0] = 8; buf[ARP_PTYPE + 0] = 8;
buf[ARP_PTYPE+1] = 0; buf[ARP_PTYPE + 1] = 0;
// lengths // lengths
buf[ARP_HLEN] = 6; buf[ARP_HLEN] = 6;
buf[ARP_PLEN] = 4; buf[ARP_PLEN] = 4;
// Response // Response
buf[ARP_OPER+0] = 0; buf[ARP_OPER + 0] = 0;
buf[ARP_OPER+1] = 2; buf[ARP_OPER + 1] = 2;
// my MAC+IP // my MAC+IP
get_mac_addr(buf+ARP_SHA); get_mac_addr(buf + ARP_SHA);
memcpy(buf+ARP_SPA, myIP, 4); memcpy(buf + ARP_SPA, myIP, 4);
// his MAC+IP // his MAC+IP
memcpy(buf+ARP_THA, hisMAC, 6); memcpy(buf + ARP_THA, hisMAC, 6);
memcpy(buf+ARP_TPA, hisIP, 4); memcpy(buf + ARP_TPA, hisIP, 4);
return ARP_END; return ARP_END;
} }
void arp_poll(void) { void arp_poll(void)
uint8_t buf[ARP_END+100]; {
wr_sockaddr_t addr; uint8_t buf[ARP_END + 100];
int len; wr_sockaddr_t addr;
int len;
if (needIP) return; /* can't do ARP w/o an address... */ if (needIP)
return; /* can't do ARP w/o an address... */
if ((len = ptpd_netif_recvfrom(arp_socket, &addr, buf, sizeof(buf), 0)) > 0) if ((len = ptpd_netif_recvfrom(arp_socket,
if ((len = process_arp(buf, len)) > 0) &addr, buf, sizeof(buf), 0)) > 0)
ptpd_netif_sendto(arp_socket, &addr, buf, len, 0); if ((len = process_arp(buf, len)) > 0)
ptpd_netif_sendto(arp_socket, &addr, buf, len, 0);
} }
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
#define ARP_H #define ARP_H
void arp_poll(); void arp_poll();
void arp_init(const char* if_name, uint32_t ip); void arp_init(const char *if_name, uint32_t ip);
#endif #endif
...@@ -43,103 +43,113 @@ ...@@ -43,103 +43,113 @@
#define BOOTP_VEND (BOOTP_FILE+128) #define BOOTP_VEND (BOOTP_FILE+128)
#define BOOTP_END (BOOTP_VEND+64) #define BOOTP_END (BOOTP_VEND+64)
int send_bootp(uint8_t* buf, int retry) { int send_bootp(uint8_t * buf, int retry)
unsigned short sum; {
unsigned short sum;
// ----------- BOOTP ------------
buf[BOOTP_OP] = 1; /* bootrequest */ // ----------- BOOTP ------------
buf[BOOTP_HTYPE] = 1; /* ethernet */ buf[BOOTP_OP] = 1; /* bootrequest */
buf[BOOTP_HLEN] = 6; /* MAC length */ buf[BOOTP_HTYPE] = 1; /* ethernet */
buf[BOOTP_HOPS] = 0; buf[BOOTP_HLEN] = 6; /* MAC length */
buf[BOOTP_HOPS] = 0;
/* A unique identifier for the request !!! FIXME */
get_mac_addr(buf+BOOTP_XID); /* A unique identifier for the request !!! FIXME */
buf[BOOTP_XID+0] ^= buf[BOOTP_XID+4]; get_mac_addr(buf + BOOTP_XID);
buf[BOOTP_XID+1] ^= buf[BOOTP_XID+5]; buf[BOOTP_XID + 0] ^= buf[BOOTP_XID + 4];
buf[BOOTP_XID+2] ^= (retry >> 8) & 0xFF; buf[BOOTP_XID + 1] ^= buf[BOOTP_XID + 5];
buf[BOOTP_XID+3] ^= retry & 0xFF; buf[BOOTP_XID + 2] ^= (retry >> 8) & 0xFF;
buf[BOOTP_XID + 3] ^= retry & 0xFF;
buf[BOOTP_SECS] = (retry >> 8) & 0xFF;
buf[BOOTP_SECS+1] = retry & 0xFF; buf[BOOTP_SECS] = (retry >> 8) & 0xFF;
memset(buf+BOOTP_UNUSED, 0, 2); buf[BOOTP_SECS + 1] = retry & 0xFF;
memset(buf + BOOTP_UNUSED, 0, 2);
memset(buf+BOOTP_CIADDR, 0, 4); /* own IP if known */
memset(buf+BOOTP_YIADDR, 0, 4); memset(buf + BOOTP_CIADDR, 0, 4); /* own IP if known */
memset(buf+BOOTP_SIADDR, 0, 4); memset(buf + BOOTP_YIADDR, 0, 4);
memset(buf+BOOTP_GIADDR, 0, 4); memset(buf + BOOTP_SIADDR, 0, 4);
memset(buf + BOOTP_GIADDR, 0, 4);
memset(buf+BOOTP_CHADDR, 0, 16);
get_mac_addr(buf+BOOTP_CHADDR); /* own MAC address */ memset(buf + BOOTP_CHADDR, 0, 16);
get_mac_addr(buf + BOOTP_CHADDR); /* own MAC address */
memset(buf+BOOTP_SNAME, 0, 64); /* desired BOOTP server */
memset(buf+BOOTP_FILE, 0, 128); /* desired BOOTP file */ memset(buf + BOOTP_SNAME, 0, 64); /* desired BOOTP server */
memset(buf+BOOTP_VEND, 0, 64); /* vendor extensions */ memset(buf + BOOTP_FILE, 0, 128); /* desired BOOTP file */
memset(buf + BOOTP_VEND, 0, 64); /* vendor extensions */
// ------------ UDP -------------
memset(buf+UDP_VIRT_SADDR, 0, 4); // ------------ UDP -------------
memset(buf+UDP_VIRT_DADDR, 0xFF, 4); memset(buf + UDP_VIRT_SADDR, 0, 4);
buf[UDP_VIRT_ZEROS] = 0; memset(buf + UDP_VIRT_DADDR, 0xFF, 4);
buf[UDP_VIRT_PROTO] = 0x11; /* UDP */ buf[UDP_VIRT_ZEROS] = 0;
buf[UDP_VIRT_LENGTH] = (BOOTP_END-IP_END) >> 8; buf[UDP_VIRT_PROTO] = 0x11; /* UDP */
buf[UDP_VIRT_LENGTH+1] = (BOOTP_END-IP_END) & 0xff; buf[UDP_VIRT_LENGTH] = (BOOTP_END - IP_END) >> 8;
buf[UDP_VIRT_LENGTH + 1] = (BOOTP_END - IP_END) & 0xff;
buf[UDP_SPORT] = 0;
buf[UDP_SPORT+1] = 68; /* BOOTP client */ buf[UDP_SPORT] = 0;
buf[UDP_DPORT] = 0; buf[UDP_SPORT + 1] = 68; /* BOOTP client */
buf[UDP_DPORT+1] = 67; /* BOOTP server */ buf[UDP_DPORT] = 0;
buf[UDP_LENGTH] = (BOOTP_END-IP_END) >> 8; buf[UDP_DPORT + 1] = 67; /* BOOTP server */
buf[UDP_LENGTH+1] = (BOOTP_END-IP_END) & 0xff; buf[UDP_LENGTH] = (BOOTP_END - IP_END) >> 8;
buf[UDP_CHECKSUM] = 0; buf[UDP_LENGTH + 1] = (BOOTP_END - IP_END) & 0xff;
buf[UDP_CHECKSUM+1] = 0; buf[UDP_CHECKSUM] = 0;
buf[UDP_CHECKSUM + 1] = 0;
sum = ipv4_checksum((unsigned short*)(buf+UDP_VIRT_SADDR), (BOOTP_END-UDP_VIRT_SADDR)/2);
if (sum == 0) sum = 0xFFFF; sum =
ipv4_checksum((unsigned short *)(buf + UDP_VIRT_SADDR),
buf[UDP_CHECKSUM+0] = (sum >> 8); (BOOTP_END - UDP_VIRT_SADDR) / 2);
buf[UDP_CHECKSUM+1] = sum & 0xff; if (sum == 0)
sum = 0xFFFF;
// ------------ IP --------------
buf[IP_VERSION] = 0x45; buf[UDP_CHECKSUM + 0] = (sum >> 8);
buf[IP_TOS] = 0; buf[UDP_CHECKSUM + 1] = sum & 0xff;
buf[IP_LEN+0] = (BOOTP_END) >> 8;
buf[IP_LEN+1] = (BOOTP_END) & 0xff; // ------------ IP --------------
buf[IP_ID+0] = 0; buf[IP_VERSION] = 0x45;
buf[IP_ID+1] = 0; buf[IP_TOS] = 0;
buf[IP_FLAGS+0] = 0; buf[IP_LEN + 0] = (BOOTP_END) >> 8;
buf[IP_FLAGS+1] = 0; buf[IP_LEN + 1] = (BOOTP_END) & 0xff;
buf[IP_TTL] = 63; buf[IP_ID + 0] = 0;
buf[IP_PROTOCOL] = 17; /* UDP */ buf[IP_ID + 1] = 0;
buf[IP_CHECKSUM+0] = 0; buf[IP_FLAGS + 0] = 0;
buf[IP_CHECKSUM+1] = 0; buf[IP_FLAGS + 1] = 0;
memset(buf+IP_SOURCE, 0, 4); buf[IP_TTL] = 63;
memset(buf+IP_DEST, 0xFF, 4); buf[IP_PROTOCOL] = 17; /* UDP */
buf[IP_CHECKSUM + 0] = 0;
sum = ipv4_checksum((unsigned short*)(buf+IP_VERSION), (IP_END-IP_VERSION)/2); buf[IP_CHECKSUM + 1] = 0;
buf[IP_CHECKSUM+0] = sum >> 8; memset(buf + IP_SOURCE, 0, 4);
buf[IP_CHECKSUM+1] = sum & 0xff; memset(buf + IP_DEST, 0xFF, 4);
mprintf("Sending BOOTP request...\n"); sum =
return BOOTP_END; ipv4_checksum((unsigned short *)(buf + IP_VERSION),
(IP_END - IP_VERSION) / 2);
buf[IP_CHECKSUM + 0] = sum >> 8;
buf[IP_CHECKSUM + 1] = sum & 0xff;
mprintf("Sending BOOTP request...\n");
return BOOTP_END;
} }
int process_bootp(uint8_t* buf, int len) int process_bootp(uint8_t * buf, int len)
{ {
uint8_t mac[6]; uint8_t mac[6];
get_mac_addr(mac); get_mac_addr(mac);
if (len != BOOTP_END) return 0; if (len != BOOTP_END)
return 0;
if (buf[IP_VERSION] != 0x45) return 0; if (buf[IP_VERSION] != 0x45)
return 0;
if (buf[IP_PROTOCOL] != 17 || if (buf[IP_PROTOCOL] != 17 ||
buf[UDP_DPORT] != 0 || buf[UDP_DPORT+1] != 68 || buf[UDP_DPORT] != 0 || buf[UDP_DPORT + 1] != 68 ||
buf[UDP_SPORT] != 0 || buf[UDP_SPORT+1] != 67) return 0; buf[UDP_SPORT] != 0 || buf[UDP_SPORT + 1] != 67)
return 0;
if (memcmp(buf+BOOTP_CHADDR, mac, 6)) return 0; if (memcmp(buf + BOOTP_CHADDR, mac, 6))
return 0;
mprintf("Discovered IP address!\n"); mprintf("Discovered IP address!\n");
setIP(buf+BOOTP_YIADDR); setIP(buf + BOOTP_YIADDR);
return 1; return 1;
} }
...@@ -20,59 +20,62 @@ ...@@ -20,59 +20,62 @@
#define ICMP_CHECKSUM (ICMP_CODE+1) #define ICMP_CHECKSUM (ICMP_CODE+1)
#define ICMP_END (ICMP_CHECKSUM+2) #define ICMP_END (ICMP_CHECKSUM+2)
int process_icmp(uint8_t* buf, int len) { int process_icmp(uint8_t * buf, int len)
int iplen, hisBodyLen; {
uint8_t hisIP[4]; int iplen, hisBodyLen;
uint8_t myIP[4]; uint8_t hisIP[4];
uint16_t sum; uint8_t myIP[4];
uint16_t sum;
/* Is it IP targetting us? */ /* Is it IP targetting us? */
getIP(myIP); getIP(myIP);
if (buf[IP_VERSION] != 0x45 || if (buf[IP_VERSION] != 0x45 || memcmp(buf + IP_DEST, myIP, 4))
memcmp(buf+IP_DEST, myIP, 4)) return 0;
return 0;
iplen = (buf[IP_LEN+0] << 8 | buf[IP_LEN+1]); iplen = (buf[IP_LEN + 0] << 8 | buf[IP_LEN + 1]);
/* An ICMP ECHO request? */ /* An ICMP ECHO request? */
if (buf[IP_PROTOCOL] != 0x01 || buf[ICMP_TYPE] != 0x08) if (buf[IP_PROTOCOL] != 0x01 || buf[ICMP_TYPE] != 0x08)
return 0; return 0;
hisBodyLen = iplen - 24; hisBodyLen = iplen - 24;
if (hisBodyLen > 64) hisBodyLen = 64; if (hisBodyLen > 64)
hisBodyLen = 64;
memcpy(hisIP, buf+IP_SOURCE, 4); memcpy(hisIP, buf + IP_SOURCE, 4);
// ------------ IP -------------- // ------------ IP --------------
buf[IP_VERSION] = 0x45; buf[IP_VERSION] = 0x45;
buf[IP_TOS] = 0; buf[IP_TOS] = 0;
buf[IP_LEN+0] = (hisBodyLen+24) >> 8; buf[IP_LEN + 0] = (hisBodyLen + 24) >> 8;
buf[IP_LEN+1] = (hisBodyLen+24) & 0xff; buf[IP_LEN + 1] = (hisBodyLen + 24) & 0xff;
buf[IP_ID+0] = 0; buf[IP_ID + 0] = 0;
buf[IP_ID+1] = 0; buf[IP_ID + 1] = 0;
buf[IP_FLAGS+0] = 0; buf[IP_FLAGS + 0] = 0;
buf[IP_FLAGS+1] = 0; buf[IP_FLAGS + 1] = 0;
buf[IP_TTL] = 63; buf[IP_TTL] = 63;
buf[IP_PROTOCOL] = 1; /* ICMP */ buf[IP_PROTOCOL] = 1; /* ICMP */
buf[IP_CHECKSUM+0] = 0; buf[IP_CHECKSUM + 0] = 0;
buf[IP_CHECKSUM+1] = 0; buf[IP_CHECKSUM + 1] = 0;
memcpy(buf+IP_SOURCE, myIP, 4); memcpy(buf + IP_SOURCE, myIP, 4);
memcpy(buf+IP_DEST, hisIP, 4); memcpy(buf + IP_DEST, hisIP, 4);
// ------------ ICMP --------- // ------------ ICMP ---------
buf[ICMP_TYPE] = 0x0; // echo reply buf[ICMP_TYPE] = 0x0; // echo reply
buf[ICMP_CODE] = 0; buf[ICMP_CODE] = 0;
buf[ICMP_CHECKSUM+0] = 0; buf[ICMP_CHECKSUM + 0] = 0;
buf[ICMP_CHECKSUM+1] = 0; buf[ICMP_CHECKSUM + 1] = 0;
// No need to copy payload; we modified things in-place // No need to copy payload; we modified things in-place
sum = ipv4_checksum((unsigned short*)(buf+ICMP_TYPE), (hisBodyLen+4+1)/2); sum =
buf[ICMP_CHECKSUM+0] = sum >> 8; ipv4_checksum((unsigned short *)(buf + ICMP_TYPE),
buf[ICMP_CHECKSUM+1] = sum & 0xff; (hisBodyLen + 4 + 1) / 2);
buf[ICMP_CHECKSUM + 0] = sum >> 8;
buf[ICMP_CHECKSUM + 1] = sum & 0xff;
sum = ipv4_checksum((unsigned short*)(buf+IP_VERSION), 10); sum = ipv4_checksum((unsigned short *)(buf + IP_VERSION), 10);
buf[IP_CHECKSUM+0] = sum >> 8; buf[IP_CHECKSUM + 0] = sum >> 8;
buf[IP_CHECKSUM+1] = sum & 0xff; buf[IP_CHECKSUM + 1] = sum & 0xff;
return 24+hisBodyLen; return 24 + hisBodyLen;
} }
...@@ -8,81 +8,88 @@ ...@@ -8,81 +8,88 @@
int needIP = 1; int needIP = 1;
static uint8_t myIP[4]; static uint8_t myIP[4];
static wr_socket_t* ipv4_socket; static wr_socket_t *ipv4_socket;
unsigned int ipv4_checksum(unsigned short* buf, int shorts) { unsigned int ipv4_checksum(unsigned short *buf, int shorts)
int i; {
unsigned int sum; int i;
unsigned int sum;
sum = 0; sum = 0;
for (i = 0; i < shorts; ++i) for (i = 0; i < shorts; ++i)
sum += buf[i]; sum += buf[i];
sum = (sum >> 16) + (sum & 0xffff); sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16); sum += (sum >> 16);
return (~sum & 0xffff); return (~sum & 0xffff);
} }
void ipv4_init(const char* if_name) { void ipv4_init(const char *if_name)
wr_sockaddr_t saddr; {
wr_sockaddr_t saddr;
/* Configure socket filter */ /* Configure socket filter */
memset(&saddr, 0, sizeof(saddr)); memset(&saddr, 0, sizeof(saddr));
strcpy(saddr.if_name, if_name); strcpy(saddr.if_name, if_name);
get_mac_addr(&saddr.mac[0]); /* Unicast */ get_mac_addr(&saddr.mac[0]); /* Unicast */
saddr.ethertype = htons(0x0800); /* IPv4 */ saddr.ethertype = htons(0x0800); /* IPv4 */
saddr.family = PTPD_SOCK_RAW_ETHERNET; saddr.family = PTPD_SOCK_RAW_ETHERNET;
ipv4_socket = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET, 0, &saddr); ipv4_socket = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET,
0, &saddr);
} }
static int bootp_retry = 0; static int bootp_retry = 0;
static int bootp_timer = 0; static int bootp_timer = 0;
void ipv4_poll(void) { void ipv4_poll(void)
uint8_t buf[400]; {
wr_sockaddr_t addr; uint8_t buf[400];
int len; wr_sockaddr_t addr;
int len;
if ((len = ptpd_netif_recvfrom(ipv4_socket, &addr, buf, sizeof(buf), 0)) > 0) { if ((len = ptpd_netif_recvfrom(ipv4_socket, &addr,
if (needIP) buf, sizeof(buf), 0)) > 0) {
process_bootp(buf, len-14); if (needIP)
process_bootp(buf, len - 14);
if (!needIP && (len = process_icmp(buf, len-14)) > 0) if (!needIP && (len = process_icmp(buf, len - 14)) > 0)
ptpd_netif_sendto(ipv4_socket, &addr, buf, len, 0); ptpd_netif_sendto(ipv4_socket, &addr, buf, len, 0);
} }
if (needIP && bootp_timer == 0) { if (needIP && bootp_timer == 0) {
len = send_bootp(buf, ++bootp_retry); len = send_bootp(buf, ++bootp_retry);
memset(addr.mac, 0xFF, 6); memset(addr.mac, 0xFF, 6);
addr.ethertype = htons(0x0800); /* IPv4 */ addr.ethertype = htons(0x0800); /* IPv4 */
ptpd_netif_sendto(ipv4_socket, &addr, buf, len, 0); ptpd_netif_sendto(ipv4_socket, &addr, buf, len, 0);
} }
if (needIP && ++bootp_timer == 100000) bootp_timer = 0; if (needIP && ++bootp_timer == 100000)
bootp_timer = 0;
} }
void getIP(unsigned char* IP) { void getIP(unsigned char *IP)
memcpy(IP, myIP, 4); {
memcpy(IP, myIP, 4);
} }
void setIP(unsigned char* IP) { void setIP(unsigned char *IP)
volatile unsigned int *eb_ip = {
(unsigned int*)(BASE_ETHERBONE_CFG + EB_IPV4); volatile unsigned int *eb_ip =
unsigned int ip; (unsigned int *)(BASE_ETHERBONE_CFG + EB_IPV4);
unsigned int ip;
memcpy(myIP, IP, 4); memcpy(myIP, IP, 4);
ip = ip = (myIP[0] << 24) | (myIP[1] << 16) | (myIP[2] << 8) | (myIP[3]);
(myIP[0] << 24) | (myIP[1] << 16) | while (*eb_ip != ip)
(myIP[2] << 8) | (myIP[3]); *eb_ip = ip;
while (*eb_ip != ip) *eb_ip = ip;
needIP = (ip == 0); needIP = (ip == 0);
if (!needIP) { if (!needIP) {
bootp_retry = 0; bootp_retry = 0;
bootp_timer = 0; bootp_timer = 0;
} }
} }
#ifndef IPV4_H #ifndef IPV4_H
#define IPV4_H #define IPV4_H
void ipv4_init(const char* if_name); void ipv4_init(const char *if_name);
void ipv4_poll(void); void ipv4_poll(void);
/* Internal to IP stack: */ /* Internal to IP stack: */
unsigned int ipv4_checksum(unsigned short* buf, int shorts); unsigned int ipv4_checksum(unsigned short *buf, int shorts);
void arp_init(const char* if_name); void arp_init(const char *if_name);
void arp_poll(void); void arp_poll(void);
extern int needIP; extern int needIP;
void setIP(unsigned char* IP); void setIP(unsigned char *IP);
void getIP(unsigned char* IP); void getIP(unsigned char *IP);
int process_icmp(uint8_t* buf, int len); int process_icmp(uint8_t * buf, int len);
int process_bootp(uint8_t* buf, int len); /* non-zero if IP was set */ int process_bootp(uint8_t * buf, int len); /* non-zero if IP was set */
int send_bootp(uint8_t* buf, int retry); int send_bootp(uint8_t * buf, int retry);
#endif #endif
...@@ -5,247 +5,226 @@ ...@@ -5,247 +5,226 @@
#include "uart.h" #include "uart.h"
#include "util.h" #include "util.h"
int vprintf(char const *format,va_list ap) int vprintf(char const *format, va_list ap)
{ {
unsigned char scratch[16]; unsigned char scratch[16];
unsigned char format_flag; unsigned char format_flag;
unsigned int u_val=0; unsigned int u_val = 0;
unsigned char base; unsigned char base;
unsigned char *ptr; unsigned char *ptr;
unsigned char width = 0; unsigned char width = 0;
unsigned char fill; unsigned char fill;
while(1) while (1) {
{
width = 0;
width = 0; fill = ' ';
fill = ' '; while ((format_flag = *format++) != '%') {
while ((format_flag = *format++) != '%') if (!format_flag) {
{ va_end(ap);
if (!format_flag) return (0);
{ }
va_end (ap);
return (0); uart_write_byte(format_flag);
} }
uart_write_byte(format_flag);
}
// check for zero pad
format_flag = *format - '0';
if (format_flag == 0) // zero pad
{
fill = '0';
format++;
}
// check for width spec // check for zero pad
format_flag = *format - '0'; format_flag = *format - '0';
if (format_flag > 0 && format_flag <= 9) // width set if (format_flag == 0) // zero pad
{ {
width = format_flag; fill = '0';
format++; format++;
} }
// check for width spec
format_flag = *format - '0';
if (format_flag > 0 && format_flag <= 9) // width set
{
width = format_flag;
format++;
}
switch (format_flag = *format++) switch (format_flag = *format++) {
{
case 'c': case 'c':
format_flag = va_arg(ap,int); format_flag = va_arg(ap, int);
//fall through //fall through
default: default:
uart_write_byte(format_flag); uart_write_byte(format_flag);
continue; continue;
case 'S': case 'S':
case 's': case 's':
ptr = (unsigned char *)va_arg(ap, char *); ptr = (unsigned char *)va_arg(ap, char *);
while (*ptr) while (*ptr)
uart_write_byte(*ptr++); uart_write_byte(*ptr++);
continue; continue;
case 'd': case 'd':
base = 10; base = 10;
goto CONVERSION_LOOP; goto CONVERSION_LOOP;
case 'u': case 'u':
base = 10; base = 10;
goto CONVERSION_LOOP; goto CONVERSION_LOOP;
case 'x': case 'x':
base = 16; base = 16;
CONVERSION_LOOP: CONVERSION_LOOP:
u_val = va_arg(ap,unsigned int); u_val = va_arg(ap, unsigned int);
if((format_flag=='d') && (u_val&0x80000000)) if ((format_flag == 'd') && (u_val & 0x80000000)) {
{ uart_write_byte('-');
uart_write_byte('-'); u_val = -u_val;
u_val=-u_val; }
}
ptr = scratch + 16; ptr = scratch + 16;
*--ptr = 0; *--ptr = 0;
do do {
{ char ch = (u_val % base) + '0';
char ch = (u_val % base) + '0'; if (ch > '9')
if (ch > '9') ch += 'a' - '9' - 1;
ch += 'a' - '9' - 1;
*--ptr = ch; *--ptr = ch;
u_val /= base; u_val /= base;
if (width) if (width)
width--; width--;
} while (u_val>0); } while (u_val > 0);
while (width--) while (width--)
*--ptr = fill; *--ptr = fill;
while (*ptr) while (*ptr)
uart_write_byte(*ptr++); uart_write_byte(*ptr++);
} }
} }
return 0; return 0;
} }
static int _p_vsprintf(char const *format, va_list ap, char *dst)
static int _p_vsprintf(char const *format,va_list ap, char*dst)
{ {
unsigned char scratch[16]; unsigned char scratch[16];
unsigned char format_flag; unsigned char format_flag;
unsigned int u_val=0; unsigned int u_val = 0;
unsigned char base; unsigned char base;
unsigned char *ptr; unsigned char *ptr;
unsigned char width = 0; unsigned char width = 0;
unsigned char fill; unsigned char fill;
while(1) while (1) {
{
width = 0;
width = 0; fill = ' ';
fill = ' '; while ((format_flag = *format++) != '%') {
while ((format_flag = *format++) != '%') if (!format_flag) {
{ va_end(ap);
if (!format_flag) *dst++ = 0;
{ return (0);
va_end (ap); }
*dst++=0;
return (0); *dst++ = format_flag;
} }
*dst++=format_flag;
}
// check for zero pad
format_flag = *format - '0';
if (format_flag == 0) // zero pad
{
fill = '0';
format++;
}
// check for width spec // check for zero pad
format_flag = *format - '0'; format_flag = *format - '0';
if (format_flag > 0 && format_flag <= 9) // width set if (format_flag == 0) // zero pad
{ {
width = format_flag; fill = '0';
format++; format++;
} }
// check for width spec
format_flag = *format - '0';
if (format_flag > 0 && format_flag <= 9) // width set
{
width = format_flag;
format++;
}
switch (format_flag = *format++) switch (format_flag = *format++) {
{
case 'c': case 'c':
format_flag = va_arg(ap,int); format_flag = va_arg(ap, int);
//fall through //fall through
default: default:
*dst++=format_flag; *dst++ = format_flag;
continue; continue;
case 'S': case 'S':
case 's': case 's':
ptr = (unsigned char *)va_arg(ap, char *); ptr = (unsigned char *)va_arg(ap, char *);
while (*ptr) while (*ptr)
*dst++=*ptr++; *dst++ = *ptr++;
continue; continue;
case 'd': case 'd':
case 'u': case 'u':
base = 10; base = 10;
goto CONVERSION_LOOP; goto CONVERSION_LOOP;
case 'x': case 'x':
base = 16; base = 16;
CONVERSION_LOOP: CONVERSION_LOOP:
u_val = va_arg(ap,unsigned int); u_val = va_arg(ap, unsigned int);
ptr = scratch + 16; ptr = scratch + 16;
*--ptr = 0; *--ptr = 0;
do do {
{ char ch = (u_val % base) + '0';
char ch = (u_val % base) + '0'; if (ch > '9')
if (ch > '9') ch += 'a' - '9' - 1;
ch += 'a' - '9' - 1;
*--ptr = ch; *--ptr = ch;
u_val /= base; u_val /= base;
if (width) if (width)
width--; width--;
} while (u_val>0); } while (u_val > 0);
// while (width--) // while (width--)
// *--ptr = fill; // *--ptr = fill;
while (*ptr) while (*ptr)
*dst++=*ptr++; *dst++ = *ptr++;
} }
} }
*dst++=0; *dst++ = 0;
return 0; return 0;
} }
int mprintf(char const *format, ...) int mprintf(char const *format, ...)
{ {
int rval; int rval;
va_list ap; va_list ap;
va_start (ap, format); va_start(ap, format);
rval = vprintf(format,ap); rval = vprintf(format, ap);
va_end(ap); va_end(ap);
return rval; return rval;
} }
int sprintf(char *dst, char const *format, ...) int sprintf(char *dst, char const *format, ...)
{ {
va_list ap; va_list ap;
va_start (ap, format); va_start(ap, format);
int r= _p_vsprintf(format,ap,dst); int r = _p_vsprintf(format, ap, dst);
return r; return r;
} }
...@@ -18,77 +18,77 @@ ...@@ -18,77 +18,77 @@
#define ABB_LEN 3 #define ABB_LEN 3
static const char *_days[] = { static const char *_days[] = {
"Sun", "Mon", "Tue", "Wed", "Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat" "Thu", "Fri", "Sat"
}; };
static const char *_months[] = { static const char *_months[] = {
"Jan", "Feb", "Mar", "Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec" "Oct", "Nov", "Dec"
}; };
static const int _ytab[2][12] = { static const int _ytab[2][12] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
}; };
char *format_time(uint64_t sec) char *format_time(uint64_t sec)
{ {
struct tm t; struct tm t;
static char buf[64]; static char buf[64];
unsigned long dayclock, dayno; unsigned long dayclock, dayno;
int year = EPOCH_YR; int year = EPOCH_YR;
dayclock = (unsigned long)sec % SECS_DAY; dayclock = (unsigned long)sec % SECS_DAY;
dayno = (unsigned long)sec / SECS_DAY; dayno = (unsigned long)sec / SECS_DAY;
t.tm_sec = dayclock % 60; t.tm_sec = dayclock % 60;
t.tm_min = (dayclock % 3600) / 60; t.tm_min = (dayclock % 3600) / 60;
t.tm_hour = dayclock / 3600; t.tm_hour = dayclock / 3600;
t.tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */ t.tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */
while (dayno >= YEARSIZE(year)) { while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year); dayno -= YEARSIZE(year);
year++; year++;
} }
t.tm_year = year - YEAR0; t.tm_year = year - YEAR0;
t.tm_yday = dayno; t.tm_yday = dayno;
t.tm_mon = 0; t.tm_mon = 0;
while (dayno >= _ytab[LEAPYEAR(year)][t.tm_mon]) { while (dayno >= _ytab[LEAPYEAR(year)][t.tm_mon]) {
dayno -= _ytab[LEAPYEAR(year)][t.tm_mon]; dayno -= _ytab[LEAPYEAR(year)][t.tm_mon];
t.tm_mon++; t.tm_mon++;
} }
t.tm_mday = dayno + 1; t.tm_mday = dayno + 1;
t.tm_isdst = 0; t.tm_isdst = 0;
sprintf(buf, "%s, %s %d, %d, %2d:%2d:%2d", _days[t.tm_wday], _months[t.tm_mon], sprintf(buf, "%s, %s %d, %d, %2d:%2d:%2d", _days[t.tm_wday],
t.tm_mday, t.tm_year + YEAR0, t.tm_hour, t.tm_min, t.tm_sec); _months[t.tm_mon], t.tm_mday, t.tm_year + YEAR0, t.tm_hour,
t.tm_min, t.tm_sec);
return buf; return buf;
} }
void cprintf(int color, const char *fmt, ...) void cprintf(int color, const char *fmt, ...)
{ {
va_list ap; va_list ap;
mprintf("\033[0%d;3%dm",color & C_DIM ? 2:1, color&0x7f); mprintf("\033[0%d;3%dm", color & C_DIM ? 2 : 1, color & 0x7f);
va_start(ap, fmt); va_start(ap, fmt);
vprintf(fmt, ap); vprintf(fmt, ap);
va_end(ap); va_end(ap);
} }
void pcprintf(int row, int col, int color, const char *fmt, ...) void pcprintf(int row, int col, int color, const char *fmt, ...)
{ {
va_list ap; va_list ap;
mprintf("\033[%d;%df", row, col); mprintf("\033[%d;%df", row, col);
mprintf("\033[0%d;3%dm",color & C_DIM ? 2:1, color&0x7f); mprintf("\033[0%d;3%dm", color & C_DIM ? 2 : 1, color & 0x7f);
va_start(ap, fmt); va_start(ap, fmt);
vprintf(fmt, ap); vprintf(fmt, ap);
va_end(ap); va_end(ap);
} }
void term_clear() void term_clear()
{ {
mprintf("\033[2J\033[1;1H"); mprintf("\033[2J\033[1;1H");
} }
...@@ -10,157 +10,201 @@ ...@@ -10,157 +10,201 @@
#include "timer.h" #include "timer.h"
#include "onewire.h" #include "onewire.h"
#define UI_REFRESH_PERIOD TICS_PER_SECOND /* 1 sec */ #define UI_REFRESH_PERIOD TICS_PER_SECOND /* 1 sec */
extern ptpdexp_sync_state_t cur_servo_state; extern ptpdexp_sync_state_t cur_servo_state;
extern int wrc_man_phase; extern int wrc_man_phase;
int wrc_mon_gui(void) int wrc_mon_gui(void)
{ {
static char* slave_states[] = {"Uninitialized", "SYNC_SEC", "SYNC_NSEC", "SYNC_PHASE", "TRACK_PHASE"}; static char *slave_states[] = {
static uint32_t last = 0; "Uninitialized", "SYNC_SEC", "SYNC_NSEC", "SYNC_PHASE",
hexp_port_state_t ps; "TRACK_PHASE"
int tx, rx; };
int aux_stat; static uint32_t last = 0;
uint64_t sec; hexp_port_state_t ps;
uint32_t nsec; int tx, rx;
int aux_stat;
uint64_t sec;
uint32_t nsec;
if(timer_get_tics() - last < UI_REFRESH_PERIOD) if (timer_get_tics() - last < UI_REFRESH_PERIOD)
return 0; return 0;
last = timer_get_tics(); last = timer_get_tics();
term_clear(); term_clear();
pcprintf(1, 1, C_BLUE, "WR PTP Core Sync Monitor v 1.0"); pcprintf(1, 1, C_BLUE, "WR PTP Core Sync Monitor v 1.0");
pcprintf(2, 1, C_GREY, "Esc = exit"); pcprintf(2, 1, C_GREY, "Esc = exit");
pps_gen_get_time(&sec, &nsec); pps_gen_get_time(&sec, &nsec);
cprintf(C_BLUE, "\n\nTAI Time: ");
cprintf(C_WHITE, "%s", format_time(sec));
/*show_ports*/
halexp_get_port_state(&ps, NULL);
pcprintf(4, 1, C_BLUE, "\n\nLink status:");
pcprintf(6, 1, C_WHITE, "%s: ", "wru1");
if(ps.up) cprintf(C_GREEN, "Link up "); else cprintf(C_RED, "Link down ");
if(ps.up)
{
minic_get_stats(&tx, &rx);
cprintf(C_GREY, "(RX: %d, TX: %d), mode: ", rx, tx);
switch(ps.mode)
{
case HEXP_PORT_MODE_WR_MASTER:cprintf(C_WHITE, "WR Master ");break;
case HEXP_PORT_MODE_WR_SLAVE:cprintf(C_WHITE, "WR Slave ");break;
}
if(ps.is_locked) cprintf(C_GREEN, "Locked "); else cprintf(C_RED, "NoLock ");
if(ps.rx_calibrated && ps.tx_calibrated) cprintf(C_GREEN, "Calibrated "); else cprintf(C_RED, "Uncalibrated ");
/* show_servo */
cprintf(C_BLUE, "\n\nSynchronization status:\n\n");
if(!cur_servo_state.valid)
{
cprintf(C_RED, "Master mode or sync info not valid\n\n");
return;
}
cprintf(C_GREY, "Servo state: "); cprintf(C_WHITE, "%s\n", cur_servo_state.slave_servo_state);
cprintf(C_GREY, "Phase tracking: "); if(cur_servo_state.tracking_enabled) cprintf(C_GREEN, "ON\n"); else cprintf(C_RED,"OFF\n");
cprintf(C_GREY, "Synchronization source: "); cprintf(C_WHITE, "%s\n", cur_servo_state.sync_source);
cprintf(C_GREY, "Aux clock status: ");
aux_stat = spll_get_aux_status(0);
if(aux_stat & SPLL_AUX_ENABLED)
cprintf(C_GREEN,"enabled");
if(aux_stat & SPLL_AUX_LOCKED)
cprintf(C_GREEN,", locked");
mprintf("\n");
cprintf(C_BLUE, "\nTiming parameters:\n\n");
cprintf(C_GREY, "Round-trip time (mu): "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.mu));
cprintf(C_GREY, "Master-slave delay: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.delay_ms));
cprintf(C_GREY, "Master PHY delays: "); cprintf(C_WHITE, "TX: %d ps, RX: %d ps\n", (int32_t)cur_servo_state.delta_tx_m, (int32_t)cur_servo_state.delta_rx_m);
cprintf(C_GREY, "Slave PHY delays: "); cprintf(C_WHITE, "TX: %d ps, RX: %d ps\n", (int32_t)cur_servo_state.delta_tx_s, (int32_t)cur_servo_state.delta_rx_s);
cprintf(C_GREY, "Total link asymmetry: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.total_asymmetry));
cprintf(C_GREY, "Cable rtt delay: "); cprintf(C_WHITE, "%d ps\n",
(int32_t)(cur_servo_state.mu) - (int32_t)cur_servo_state.delta_tx_m - (int32_t)cur_servo_state.delta_rx_m -
(int32_t)cur_servo_state.delta_tx_s - (int32_t)cur_servo_state.delta_rx_s);
cprintf(C_GREY, "Clock offset: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.cur_offset));
cprintf(C_GREY, "Phase setpoint: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.cur_setpoint));
cprintf(C_GREY, "Skew: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(cur_servo_state.cur_skew));
cprintf(C_GREY, "Manual phase adjustment: "); cprintf(C_WHITE, "%d ps\n", (int32_t)(wrc_man_phase));
cprintf(C_GREY, "Update counter: "); cprintf(C_WHITE, "%d \n", (int32_t)(cur_servo_state.update_count));
}
cprintf(C_GREY, "--");
return 0; cprintf(C_BLUE, "\n\nTAI Time: ");
cprintf(C_WHITE, "%s", format_time(sec));
/*show_ports */
halexp_get_port_state(&ps, NULL);
pcprintf(4, 1, C_BLUE, "\n\nLink status:");
pcprintf(6, 1, C_WHITE, "%s: ", "wru1");
if (ps.up)
cprintf(C_GREEN, "Link up ");
else
cprintf(C_RED, "Link down ");
if (ps.up) {
minic_get_stats(&tx, &rx);
cprintf(C_GREY, "(RX: %d, TX: %d), mode: ", rx, tx);
switch (ps.mode) {
case HEXP_PORT_MODE_WR_MASTER:
cprintf(C_WHITE, "WR Master ");
break;
case HEXP_PORT_MODE_WR_SLAVE:
cprintf(C_WHITE, "WR Slave ");
break;
}
if (ps.is_locked)
cprintf(C_GREEN, "Locked ");
else
cprintf(C_RED, "NoLock ");
if (ps.rx_calibrated && ps.tx_calibrated)
cprintf(C_GREEN, "Calibrated ");
else
cprintf(C_RED, "Uncalibrated ");
/* show_servo */
cprintf(C_BLUE, "\n\nSynchronization status:\n\n");
if (!cur_servo_state.valid) {
cprintf(C_RED,
"Master mode or sync info not valid\n\n");
return;
}
cprintf(C_GREY, "Servo state: ");
cprintf(C_WHITE, "%s\n", cur_servo_state.slave_servo_state);
cprintf(C_GREY, "Phase tracking: ");
if (cur_servo_state.tracking_enabled)
cprintf(C_GREEN, "ON\n");
else
cprintf(C_RED, "OFF\n");
cprintf(C_GREY, "Synchronization source: ");
cprintf(C_WHITE, "%s\n", cur_servo_state.sync_source);
cprintf(C_GREY, "Aux clock status: ");
aux_stat = spll_get_aux_status(0);
if (aux_stat & SPLL_AUX_ENABLED)
cprintf(C_GREEN, "enabled");
if (aux_stat & SPLL_AUX_LOCKED)
cprintf(C_GREEN, ", locked");
mprintf("\n");
cprintf(C_BLUE, "\nTiming parameters:\n\n");
cprintf(C_GREY, "Round-trip time (mu): ");
cprintf(C_WHITE, "%d ps\n", (int32_t) (cur_servo_state.mu));
cprintf(C_GREY, "Master-slave delay: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.delay_ms));
cprintf(C_GREY, "Master PHY delays: ");
cprintf(C_WHITE, "TX: %d ps, RX: %d ps\n",
(int32_t) cur_servo_state.delta_tx_m,
(int32_t) cur_servo_state.delta_rx_m);
cprintf(C_GREY, "Slave PHY delays: ");
cprintf(C_WHITE, "TX: %d ps, RX: %d ps\n",
(int32_t) cur_servo_state.delta_tx_s,
(int32_t) cur_servo_state.delta_rx_s);
cprintf(C_GREY, "Total link asymmetry: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.total_asymmetry));
cprintf(C_GREY, "Cable rtt delay: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.mu) -
(int32_t) cur_servo_state.delta_tx_m -
(int32_t) cur_servo_state.delta_rx_m -
(int32_t) cur_servo_state.delta_tx_s -
(int32_t) cur_servo_state.delta_rx_s);
cprintf(C_GREY, "Clock offset: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.cur_offset));
cprintf(C_GREY, "Phase setpoint: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.cur_setpoint));
cprintf(C_GREY, "Skew: ");
cprintf(C_WHITE, "%d ps\n",
(int32_t) (cur_servo_state.cur_skew));
cprintf(C_GREY, "Manual phase adjustment: ");
cprintf(C_WHITE, "%d ps\n", (int32_t) (wrc_man_phase));
cprintf(C_GREY, "Update counter: ");
cprintf(C_WHITE, "%d \n",
(int32_t) (cur_servo_state.update_count));
}
cprintf(C_GREY, "--");
return 0;
} }
int wrc_log_stats(uint8_t onetime) int wrc_log_stats(uint8_t onetime)
{ {
static char* slave_states[] = {"Uninitialized", "SYNC_SEC", "SYNC_NSEC", "SYNC_PHASE", "TRACK_PHASE"}; static char *slave_states[] = {
static uint32_t last = 0; "Uninitialized", "SYNC_SEC", "SYNC_NSEC", "SYNC_PHASE",
hexp_port_state_t ps; "TRACK_PHASE"
int tx, rx; };
int aux_stat; static uint32_t last = 0;
uint64_t sec; hexp_port_state_t ps;
uint32_t nsec; int tx, rx;
int16_t brd_temp = 0; int aux_stat;
int16_t brd_temp_frac = 0; uint64_t sec;
uint32_t nsec;
if(!onetime && timer_get_tics() - last < UI_REFRESH_PERIOD) int16_t brd_temp = 0;
return 0; int16_t brd_temp_frac = 0;
last = timer_get_tics(); if (!onetime && timer_get_tics() - last < UI_REFRESH_PERIOD)
return 0;
last = timer_get_tics();
pps_gen_get_time(&sec, &nsec); pps_gen_get_time(&sec, &nsec);
halexp_get_port_state(&ps, NULL); halexp_get_port_state(&ps, NULL);
minic_get_stats(&tx, &rx); minic_get_stats(&tx, &rx);
mprintf("lnk:%d rx:%d tx:%d ", ps.up, rx, tx); mprintf("lnk:%d rx:%d tx:%d ", ps.up, rx, tx);
mprintf("lock:%d ", ps.is_locked?1:0); mprintf("lock:%d ", ps.is_locked ? 1 : 0);
mprintf("sv:%d ", cur_servo_state.valid?1:0); mprintf("sv:%d ", cur_servo_state.valid ? 1 : 0);
mprintf("ss:'%s' ", cur_servo_state.slave_servo_state); mprintf("ss:'%s' ", cur_servo_state.slave_servo_state);
aux_stat = spll_get_aux_status(0); aux_stat = spll_get_aux_status(0);
mprintf("aux:%x ", aux_stat); mprintf("aux:%x ", aux_stat);
mprintf("sec:%d nsec:%d ", (uint32_t) sec, nsec); /* fixme: clock is not always 125 MHz */ mprintf("sec:%d nsec:%d ", (uint32_t) sec, nsec); /* fixme: clock is not always 125 MHz */
mprintf("mu:%d ", (int32_t)cur_servo_state.mu); mprintf("mu:%d ", (int32_t) cur_servo_state.mu);
mprintf("dms:%d ", (int32_t)cur_servo_state.delay_ms); mprintf("dms:%d ", (int32_t) cur_servo_state.delay_ms);
mprintf("dtxm:%d drxm:%d ", (int32_t)cur_servo_state.delta_tx_m, (int32_t)cur_servo_state.delta_rx_m); mprintf("dtxm:%d drxm:%d ", (int32_t) cur_servo_state.delta_tx_m,
mprintf("dtxs:%d drxs:%d ", (int32_t)cur_servo_state.delta_tx_s, (int32_t)cur_servo_state.delta_rx_s); (int32_t) cur_servo_state.delta_rx_m);
mprintf("asym:%d ", (int32_t)(cur_servo_state.total_asymmetry)); mprintf("dtxs:%d drxs:%d ", (int32_t) cur_servo_state.delta_tx_s,
mprintf("crtt:%d ", (int32_t) cur_servo_state.delta_rx_s);
(int32_t)(cur_servo_state.mu) - (int32_t)cur_servo_state.delta_tx_m - (int32_t)cur_servo_state.delta_rx_m - mprintf("asym:%d ", (int32_t) (cur_servo_state.total_asymmetry));
(int32_t)cur_servo_state.delta_tx_s - (int32_t)cur_servo_state.delta_rx_s); mprintf("crtt:%d ",
mprintf("cko:%d ", (int32_t)(cur_servo_state.cur_offset)); (int32_t) (cur_servo_state.mu) -
mprintf("setp:%d ", (int32_t)(cur_servo_state.cur_setpoint)); (int32_t) cur_servo_state.delta_tx_m -
mprintf("hd:%d md:%d ad:%d ", (int32_t) cur_servo_state.delta_rx_m -
spll_get_dac(-1), (int32_t) cur_servo_state.delta_tx_s -
spll_get_dac(0), (int32_t) cur_servo_state.delta_rx_s);
spll_get_dac(1) mprintf("cko:%d ", (int32_t) (cur_servo_state.cur_offset));
); mprintf("setp:%d ", (int32_t) (cur_servo_state.cur_setpoint));
mprintf("ucnt:%d ", (int32_t)cur_servo_state.update_count); mprintf("hd:%d md:%d ad:%d ", spll_get_dac(-1), spll_get_dac(0),
spll_get_dac(1));
own_readtemp(ONEWIRE_PORT, &brd_temp, &brd_temp_frac); mprintf("ucnt:%d ", (int32_t) cur_servo_state.update_count);
mprintf("temp:%d.%02d C", brd_temp, brd_temp_frac);
own_readtemp(ONEWIRE_PORT, &brd_temp, &brd_temp_frac);
mprintf("\n"); mprintf("temp:%d.%02d C", brd_temp, brd_temp_frac);
return 0;
mprintf("\n");
return 0;
} }
...@@ -7,34 +7,29 @@ ...@@ -7,34 +7,29 @@
#include "eeprom.h" #include "eeprom.h"
#include "syscon.h" #include "syscon.h"
extern int measure_t24p(int *value); extern int measure_t24p(int *value);
int cmd_calib(const char *args[]) int cmd_calib(const char *args[])
{ {
uint32_t trans; uint32_t trans;
if(args[0] && !strcasecmp(args[0], "force")) if (args[0] && !strcasecmp(args[0], "force")) {
{ if (measure_t24p(&trans) < 0)
if( measure_t24p(&trans)<0 )
return -1; return -1;
return eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR, &trans, 1); return eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR, &trans, 1);
} } else if (!args[0]) {
else if( !args[0] ) if (eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR, &trans, 0) > 0) {
{ mprintf("Found phase transition in EEPROM: %dps\n",
if( eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR, &trans, 0) >0 ) trans);
{
mprintf("Found phase transition in EEPROM: %dps\n", trans);
cal_phase_transition = trans; cal_phase_transition = trans;
return 0; return 0;
} } else {
else
{
mprintf("Measuring t2/t4 phase transition...\n"); mprintf("Measuring t2/t4 phase transition...\n");
if( measure_t24p(&trans)<0 ) if (measure_t24p(&trans) < 0)
return -1; return -1;
cal_phase_transition = trans; cal_phase_transition = trans;
return eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR, &trans, 1); return eeprom_phtrans(WRPC_FMC_I2C, FMC_EEPROM_ADR,
&trans, 1);
} }
} }
......
...@@ -3,40 +3,28 @@ ...@@ -3,40 +3,28 @@
#include "eeprom.h" #include "eeprom.h"
#include "syscon.h" #include "syscon.h"
int cmd_init(const char *args[]) int cmd_init(const char *args[])
{ {
if( !mi2c_devprobe(WRPC_FMC_I2C, FMC_EEPROM_ADR) ) if (!mi2c_devprobe(WRPC_FMC_I2C, FMC_EEPROM_ADR)) {
{ mprintf("EEPROM not found..\n");
mprintf("EEPROM not found..\n"); return -1;
return -1; }
}
if(args[0] && !strcasecmp(args[0], "erase")) if (args[0] && !strcasecmp(args[0], "erase")) {
{ if (eeprom_init_erase(WRPC_FMC_I2C, FMC_EEPROM_ADR) < 0)
if( eeprom_init_erase(WRPC_FMC_I2C, FMC_EEPROM_ADR) < 0 ) mprintf("Could not erase init script\n");
mprintf("Could not erase init script\n"); } else if (args[0] && !strcasecmp(args[0], "purge")) {
} eeprom_init_purge(WRPC_FMC_I2C, FMC_EEPROM_ADR);
else if(args[0] && !strcasecmp(args[0], "purge")) } else if (args[1] && !strcasecmp(args[0], "add")) {
{ if (eeprom_init_add(WRPC_FMC_I2C, FMC_EEPROM_ADR, args) < 0)
eeprom_init_purge(WRPC_FMC_I2C, FMC_EEPROM_ADR); mprintf("Could not add the command\n");
} else
else if(args[1] && !strcasecmp(args[0], "add")) mprintf("OK.\n");
{ } else if (args[0] && !strcasecmp(args[0], "show")) {
if( eeprom_init_add(WRPC_FMC_I2C, FMC_EEPROM_ADR, args) < 0 ) eeprom_init_show(WRPC_FMC_I2C, FMC_EEPROM_ADR);
mprintf("Could not add the command\n"); } else if (args[0] && !strcasecmp(args[0], "boot")) {
else shell_boot_script();
mprintf("OK.\n"); }
}
else if(args[0] && !strcasecmp(args[0], "show"))
{
eeprom_init_show(WRPC_FMC_I2C, FMC_EEPROM_ADR);
}
else if(args[0] && !strcasecmp(args[0], "boot"))
{
shell_boot_script();
}
return 0; return 0;
} }
...@@ -6,34 +6,36 @@ ...@@ -6,34 +6,36 @@
#include "shell.h" #include "shell.h"
#include "../lib/ipv4.h" #include "../lib/ipv4.h"
static decode_ip(const char *str, unsigned char* ip) { static decode_ip(const char *str, unsigned char *ip)
int i, x; {
int i, x;
/* Don't try to detect bad input; need small code */ /* Don't try to detect bad input; need small code */
for (i = 0; i < 4; ++i) { for (i = 0; i < 4; ++i) {
str = fromdec(str, &x); str = fromdec(str, &x);
ip[i] = x; ip[i] = x;
if (*str == '.') ++str; if (*str == '.')
} ++str;
}
} }
int cmd_ip(const char *args[]) int cmd_ip(const char *args[])
{ {
unsigned char ip[4]; unsigned char ip[4];
if (!args[0] || !strcasecmp(args[0], "get")) { if (!args[0] || !strcasecmp(args[0], "get")) {
getIP(ip); getIP(ip);
} else if (!strcasecmp(args[0], "set") && args[1]) { } else if (!strcasecmp(args[0], "set") && args[1]) {
decode_ip(args[1], ip); decode_ip(args[1], ip);
setIP(ip); setIP(ip);
} else { } else {
return -EINVAL; return -EINVAL;
} }
if (needIP) { if (needIP) {
mprintf("IP-address: in training\n"); mprintf("IP-address: in training\n");
} else { } else {
mprintf("IP-address: %d.%d.%d.%d\n", mprintf("IP-address: %d.%d.%d.%d\n",
ip[0], ip[1], ip[2], ip[3]); ip[0], ip[1], ip[2], ip[3]);
} }
} }
...@@ -7,39 +7,41 @@ ...@@ -7,39 +7,41 @@
#include "onewire.h" #include "onewire.h"
#include "../lib/ipv4.h" #include "../lib/ipv4.h"
static decode_mac(const char *str, unsigned char* mac) { static decode_mac(const char *str, unsigned char *mac)
int i, x; {
int i, x;
/* Don't try to detect bad input; need small code */ /* Don't try to detect bad input; need small code */
for (i = 0; i < 6; ++i) { for (i = 0; i < 6; ++i) {
str = fromhex(str, &x); str = fromhex(str, &x);
mac[i] = x; mac[i] = x;
if (*str == ':') ++str; if (*str == ':')
} ++str;
}
} }
int cmd_mac(const char *args[]) int cmd_mac(const char *args[])
{ {
unsigned char mac[6]; unsigned char mac[6];
if (!args[0] || !strcasecmp(args[0], "get")) { if (!args[0] || !strcasecmp(args[0], "get")) {
/* get current MAC */ /* get current MAC */
get_mac_addr(mac); get_mac_addr(mac);
} else if (!strcasecmp(args[0], "getp")) { } else if (!strcasecmp(args[0], "getp")) {
/* get persistent MAC */ /* get persistent MAC */
get_mac_addr(mac); get_mac_addr(mac);
get_persistent_mac(ONEWIRE_PORT, mac); get_persistent_mac(ONEWIRE_PORT, mac);
} else if (!strcasecmp(args[0], "set") && args[1]) { } else if (!strcasecmp(args[0], "set") && args[1]) {
decode_mac(args[1], mac); decode_mac(args[1], mac);
set_mac_addr(mac); set_mac_addr(mac);
pfilter_init_default(); pfilter_init_default();
} else if (!strcasecmp(args[0], "setp") && args[1]) { } else if (!strcasecmp(args[0], "setp") && args[1]) {
decode_mac(args[1], mac); decode_mac(args[1], mac);
set_persistent_mac(ONEWIRE_PORT, mac); set_persistent_mac(ONEWIRE_PORT, mac);
} else { } else {
return -EINVAL; return -EINVAL;
} }
mprintf("MAC-address: %x:%x:%x:%x:%x:%x\n", mprintf("MAC-address: %x:%x:%x:%x:%x:%x\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
} }
...@@ -12,17 +12,18 @@ ...@@ -12,17 +12,18 @@
int cmd_mode(const char *args[]) int cmd_mode(const char *args[])
{ {
int mode; int mode;
static const char *modes[]={"unknown","grandmaster","master","slave"}; static const char *modes[] =
{ "unknown", "grandmaster", "master", "slave" };
if(!strcasecmp(args[0], "gm")) if (!strcasecmp(args[0], "gm"))
mode = WRC_MODE_GM; mode = WRC_MODE_GM;
else if(!strcasecmp(args[0], "master")) else if (!strcasecmp(args[0], "master"))
mode = WRC_MODE_MASTER; mode = WRC_MODE_MASTER;
else if(!strcasecmp(args[0], "slave")) else if (!strcasecmp(args[0], "slave"))
mode = WRC_MODE_SLAVE; mode = WRC_MODE_SLAVE;
else { else {
mprintf("%s\n", modes[wrc_ptp_get_mode()]); mprintf("%s\n", modes[wrc_ptp_get_mode()]);
return 0; return 0;
} }
return wrc_ptp_set_mode(mode); return wrc_ptp_set_mode(mode);
} }
\ No newline at end of file
...@@ -9,49 +9,41 @@ int cmd_pll(const char *args[]) ...@@ -9,49 +9,41 @@ int cmd_pll(const char *args[])
{ {
int cur, tgt; int cur, tgt;
if(!strcasecmp(args[0], "init")) if (!strcasecmp(args[0], "init")) {
{ if (!args[3])
if(!args[3])
return -EINVAL; return -EINVAL;
spll_init(atoi(args[1]), atoi(args[2]), atoi(args[3])); spll_init(atoi(args[1]), atoi(args[2]), atoi(args[3]));
} else if (!strcasecmp(args[0], "cl")) } else if (!strcasecmp(args[0], "cl")) {
{ if (!args[1])
if(!args[1])
return -EINVAL; return -EINVAL;
mprintf("%d\n", spll_check_lock(atoi(args[1]))); mprintf("%d\n", spll_check_lock(atoi(args[1])));
} else if (!strcasecmp(args[0], "sps")) } else if (!strcasecmp(args[0], "sps")) {
{ if (!args[2])
if(!args[2])
return -EINVAL; return -EINVAL;
spll_set_phase_shift(atoi(args[1]), atoi(args[2])); spll_set_phase_shift(atoi(args[1]), atoi(args[2]));
} else if (!strcasecmp(args[0], "gps")) } else if (!strcasecmp(args[0], "gps")) {
{ if (!args[1])
if(!args[1])
return -EINVAL; return -EINVAL;
spll_get_phase_shift(atoi(args[1]), &cur, &tgt); spll_get_phase_shift(atoi(args[1]), &cur, &tgt);
printf("%d %d\n", cur, tgt); printf("%d %d\n", cur, tgt);
} else if (!strcasecmp(args[0], "start")) } else if (!strcasecmp(args[0], "start")) {
{ if (!args[1])
if(!args[1])
return -EINVAL; return -EINVAL;
spll_start_channel(atoi(args[1])); spll_start_channel(atoi(args[1]));
} else if (!strcasecmp(args[0], "stop")) } else if (!strcasecmp(args[0], "stop")) {
{ if (!args[1])
if(!args[1])
return -EINVAL; return -EINVAL;
spll_stop_channel(atoi(args[1])); spll_stop_channel(atoi(args[1]));
} else if (!strcasecmp(args[0], "sdac")) } else if (!strcasecmp(args[0], "sdac")) {
{ if (!args[2])
if(!args[2])
return -EINVAL; return -EINVAL;
spll_set_dac(atoi(args[1]), atoi(args[2])); spll_set_dac(atoi(args[1]), atoi(args[2]));
} else if (!strcasecmp(args[0], "gdac")) } else if (!strcasecmp(args[0], "gdac")) {
{ if (!args[1])
if(!args[1])
return -EINVAL; return -EINVAL;
mprintf("%d\n", spll_get_dac(atoi(args[1]))); mprintf("%d\n", spll_get_dac(atoi(args[1])));
} else return -EINVAL; } else
return -EINVAL;
return 0; return 0;
} }
...@@ -8,15 +8,14 @@ ...@@ -8,15 +8,14 @@
#include "shell.h" #include "shell.h"
int cmd_ptp(const char *args[]) int cmd_ptp(const char *args[])
{ {
if(!strcasecmp(args[0], "start")) if (!strcasecmp(args[0], "start"))
return wrc_ptp_start(); return wrc_ptp_start();
else if(!strcasecmp(args[0], "stop")) else if (!strcasecmp(args[0], "stop"))
return wrc_ptp_stop(); return wrc_ptp_stop();
else else
return -EINVAL; return -EINVAL;
return 0; return 0;
} }
\ No newline at end of file
...@@ -8,4 +8,4 @@ int cmd_sdb(const char *args[]) ...@@ -8,4 +8,4 @@ int cmd_sdb(const char *args[])
{ {
sdb_print_devices(); sdb_print_devices();
return 0; return 0;
} }
\ No newline at end of file
...@@ -19,18 +19,17 @@ ...@@ -19,18 +19,17 @@
int cmd_sfp(const char *args[]) int cmd_sfp(const char *args[])
{ {
int8_t sfpcount=1, i, temp; int8_t sfpcount = 1, i, temp;
struct s_sfpinfo sfp; struct s_sfpinfo sfp;
static char pn[SFP_PN_LEN+1] = "\0"; static char pn[SFP_PN_LEN + 1] = "\0";
if(args[0] && !strcasecmp(args[0], "detect")) if (args[0] && !strcasecmp(args[0], "detect")) {
{ if (!sfp_present())
if(!sfp_present())
mprintf("No SFP.\n"); mprintf("No SFP.\n");
else else
sfp_read_part_id(pn); sfp_read_part_id(pn);
pn[16]=0; pn[16] = 0;
mprintf("%s\n",pn); mprintf("%s\n", pn);
return 0; return 0;
} }
// else if (!strcasecmp(args[0], "i2cscan")) // else if (!strcasecmp(args[0], "i2cscan"))
...@@ -38,73 +37,65 @@ int cmd_sfp(const char *args[]) ...@@ -38,73 +37,65 @@ int cmd_sfp(const char *args[])
// mi2c_scan(WRPC_FMC_I2C); // mi2c_scan(WRPC_FMC_I2C);
// return 0; // return 0;
// } // }
else if (!strcasecmp(args[0], "erase")) else if (!strcasecmp(args[0], "erase")) {
{ if (eeprom_sfpdb_erase(WRPC_FMC_I2C, FMC_EEPROM_ADR) ==
if( eeprom_sfpdb_erase(WRPC_FMC_I2C, FMC_EEPROM_ADR) == EE_RET_I2CERR) EE_RET_I2CERR)
mprintf("Could not erase DB\n"); mprintf("Could not erase DB\n");
} } else if (args[4] && !strcasecmp(args[0], "add")) {
else if (args[4] && !strcasecmp(args[0], "add")) if (strlen(args[1]) > 16)
{ temp = 16;
if(strlen( args[1] )>16) temp=16; else
else temp=strlen( args[1] ); temp = strlen(args[1]);
for(i=0; i<temp; ++i) for (i = 0; i < temp; ++i)
sfp.pn[i]=args[1][i]; sfp.pn[i] = args[1][i];
while(i<16) sfp.pn[i++]=' '; //padding while (i < 16)
sfp.dTx = atoi(args[2]); sfp.pn[i++] = ' '; //padding
sfp.dRx = atoi(args[3]); sfp.dTx = atoi(args[2]);
sfp.alpha = atoi(args[4]); sfp.dRx = atoi(args[3]);
temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &sfp, 1, 0); sfp.alpha = atoi(args[4]);
if(temp == EE_RET_DBFULL) temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &sfp, 1, 0);
mprintf("SFP DB is full\n"); if (temp == EE_RET_DBFULL)
else if(temp == EE_RET_I2CERR) mprintf("SFP DB is full\n");
mprintf("I2C error\n"); else if (temp == EE_RET_I2CERR)
else mprintf("I2C error\n");
mprintf("%d SFPs in DB\n", temp); else
mprintf("%d SFPs in DB\n", temp);
} else if (args[0] && !strcasecmp(args[0], "show")) {
for (i = 0; i < sfpcount; ++i) {
temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR,
&sfp, 0, i);
if (!i) {
sfpcount = temp; //only in first round valid sfpcount is returned from eeprom_get_sfp
if (sfpcount == 0 || sfpcount == 0xFF) {
mprintf("SFP database empty...\n");
return 0;
} else if (sfpcount == -1) {
mprintf("SFP database corrupted...\n");
return 0;
}
}
mprintf("%d: PN:", i + 1);
for (temp = 0; temp < 16; ++temp)
mprintf("%c", sfp.pn[temp]);
mprintf(" dTx: %d, dRx: %d, alpha: %d\n", sfp.dTx,
sfp.dRx, sfp.alpha);
}
} else if (args[0] && !strcasecmp(args[0], "match")) {
if (pn[0] == '\0') {
mprintf("Run sfp detect first\n");
return 0;
}
strncpy(sfp.pn, pn, SFP_PN_LEN);
if (eeprom_match_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &sfp) > 0) {
mprintf("SFP matched, dTx=%d, dRx=%d, alpha=%d\n",
sfp.dTx, sfp.dRx, sfp.alpha);
sfp_deltaTx = sfp.dTx;
sfp_deltaRx = sfp.dRx;
sfp_alpha = sfp.alpha;
} else
mprintf("Could not match to DB\n");
return 0;
} }
else if (args[0] && !strcasecmp(args[0], "show"))
{
for(i=0; i<sfpcount; ++i)
{
temp = eeprom_get_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &sfp, 0, i);
if(!i)
{
sfpcount=temp; //only in first round valid sfpcount is returned from eeprom_get_sfp
if(sfpcount == 0 || sfpcount == 0xFF)
{
mprintf("SFP database empty...\n");
return 0;
}
else if(sfpcount == -1)
{
mprintf("SFP database corrupted...\n");
return 0;
}
}
mprintf("%d: PN:", i+1);
for(temp=0; temp<16; ++temp)
mprintf("%c", sfp.pn[temp]);
mprintf(" dTx: %d, dRx: %d, alpha: %d\n", sfp.dTx, sfp.dRx, sfp.alpha);
}
}
else if (args[0] && !strcasecmp(args[0], "match"))
{
if(pn[0]=='\0')
{
mprintf("Run sfp detect first\n");
return 0;
}
strncpy(sfp.pn, pn, SFP_PN_LEN);
if(eeprom_match_sfp(WRPC_FMC_I2C, FMC_EEPROM_ADR, &sfp) > 0)
{
mprintf("SFP matched, dTx=%d, dRx=%d, alpha=%d\n", sfp.dTx, sfp.dRx, sfp.alpha);
sfp_deltaTx = sfp.dTx;
sfp_deltaRx = sfp.dRx;
sfp_alpha = sfp.alpha;
}
else
mprintf("Could not match to DB\n");
return 0;
}
return 0; return 0;
} }
...@@ -2,12 +2,10 @@ ...@@ -2,12 +2,10 @@
int cmd_stat(const char *args[]) int cmd_stat(const char *args[])
{ {
if(!strcasecmp(args[0], "cont") ) if (!strcasecmp(args[0], "cont")) {
{ wrc_ui_mode = UI_STAT_MODE;
wrc_ui_mode = UI_STAT_MODE; } else
} wrc_log_stats(1);
else
wrc_log_stats(1);
return 0; return 0;
} }
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
#include "wrc_ptp.h" #include "wrc_ptp.h"
#include "pps_gen.h" #include "pps_gen.h"
int cmd_time(const char *args[]) int cmd_time(const char *args[])
{ {
uint64_t sec; uint64_t sec;
...@@ -22,20 +21,19 @@ int cmd_time(const char *args[]) ...@@ -22,20 +21,19 @@ int cmd_time(const char *args[])
pps_gen_get_time(&sec, &nsec); pps_gen_get_time(&sec, &nsec);
if(args[2] && !strcasecmp(args[0], "set")) { if (args[2] && !strcasecmp(args[0], "set")) {
if(wrc_ptp_get_mode() != WRC_MODE_SLAVE) if (wrc_ptp_get_mode() != WRC_MODE_SLAVE) {
{ pps_gen_set_time((uint64_t) atoi(args[1]),
pps_gen_set_time((uint64_t)atoi(args[1]), atoi(args[2])); atoi(args[2]));
return 0; return 0;
} else } else
return -EBUSY; return -EBUSY;
} else if(args[0] && !strcasecmp(args[0], "raw")) } else if (args[0] && !strcasecmp(args[0], "raw")) {
{ mprintf("%d %d\n", (uint32_t) sec, nsec);
mprintf("%d %d\n", (uint32_t)sec, nsec); return 0;
return 0;
} }
mprintf("%s +%d nanoseconds.\n", format_time(sec), nsec); /* fixme: clock freq is not always 125 MHz */ mprintf("%s +%d nanoseconds.\n", format_time(sec), nsec); /* fixme: clock freq is not always 125 MHz */
return 0; return 0;
} }
...@@ -5,6 +5,7 @@ extern const char *build_revision, *build_date; ...@@ -5,6 +5,7 @@ extern const char *build_revision, *build_date;
int cmd_version(const char *args[]) int cmd_version(const char *args[])
{ {
mprintf("WR Core build: %s, compiled on: %s (memory size: %d kB)\n", build_revision, build_date, sysc_get_memsize()); mprintf("WR Core build: %s, compiled on: %s (memory size: %d kB)\n",
build_revision, build_date, sysc_get_memsize());
return 0; return 0;
} }
\ No newline at end of file
...@@ -18,10 +18,10 @@ void env_init() ...@@ -18,10 +18,10 @@ void env_init()
static char *_env_get(const char *var) static char *_env_get(const char *var)
{ {
int i = 0; int i = 0;
while(i < SH_ENVIRON_SIZE && env_buf[i] != 0xff) while (i < SH_ENVIRON_SIZE && env_buf[i] != 0xff) {
{ if (env_buf[i] == 0xaa
if(env_buf[i] == 0xaa && !strcasecmp((char*)env_buf + i + 1, var)) && !strcasecmp((char *)env_buf + i + 1, var))
return (char*)env_buf + i; return (char *)env_buf + i;
i++; i++;
} }
...@@ -33,16 +33,17 @@ char *env_get(const char *var) ...@@ -33,16 +33,17 @@ char *env_get(const char *var)
{ {
char *p = _env_get(var); char *p = _env_get(var);
if(!p) return NULL; if (!p)
return NULL;
return p+2+strlen(p+1); return p + 2 + strlen(p + 1);
} }
static int _env_end() static int _env_end()
{ {
int i; int i;
for(i=0;i<SH_ENVIRON_SIZE;i++) for (i = 0; i < SH_ENVIRON_SIZE; i++)
if(env_buf[i] == 0xff) if (env_buf[i] == 0xff)
return i; return i;
} }
...@@ -51,10 +52,10 @@ int env_set(const char *var, const char *value) ...@@ -51,10 +52,10 @@ int env_set(const char *var, const char *value)
unsigned char *vstart = _env_get(var), *p; unsigned char *vstart = _env_get(var), *p;
int end; int end;
if(vstart) /* entry already present? remove current and append at the end of environment */ if (vstart) { /* entry already present? remove current and append at the end of environment */
{ p = vstart + 1;
p=vstart+1; while (*p != 0xaa && *p != 0xff)
while(*p != 0xaa && *p != 0xff) p++; p++;
memmove(vstart, p, SH_ENVIRON_SIZE - (p - env_buf)); memmove(vstart, p, SH_ENVIRON_SIZE - (p - env_buf));
} }
...@@ -67,8 +68,10 @@ int env_set(const char *var, const char *value) ...@@ -67,8 +68,10 @@ int env_set(const char *var, const char *value)
p = &env_buf[end]; p = &env_buf[end];
*p++ = 0xaa; *p++ = 0xaa;
memcpy(p, var, strlen(var) + 1); p += strlen(var) + 1; memcpy(p, var, strlen(var) + 1);
memcpy(p, value, strlen(value) + 1); p += strlen(value) + 1; p += strlen(var) + 1;
memcpy(p, value, strlen(value) + 1);
p += strlen(value) + 1;
*p++ = 0xff; *p++ = 0xff;
p = env_buf; p = env_buf;
...@@ -80,10 +83,9 @@ int cmd_env(const char *args[]) ...@@ -80,10 +83,9 @@ int cmd_env(const char *args[])
{ {
unsigned char *p = env_buf; unsigned char *p = env_buf;
while(*p != 0xff) while (*p != 0xff) {
{ if (*p == 0xaa)
if(*p==0xaa) mprintf("%s=%s\n", p + 1, p + strlen(p + 1) + 2);
mprintf("%s=%s\n", p+1, p+strlen(p+1)+2);
p++; p++;
} }
...@@ -98,9 +100,8 @@ int cmd_saveenv(const char *args[]) ...@@ -98,9 +100,8 @@ int cmd_saveenv(const char *args[])
int cmd_set(const char *args[]) int cmd_set(const char *args[])
{ {
if(!args[1]) if (!args[1])
return -EINVAL; return -EINVAL;
return env_set(args[0], args[1]); return env_set(args[0], args[1]);
} }
...@@ -27,35 +27,33 @@ ...@@ -27,35 +27,33 @@
#define KEY_BACKSPACE (127) #define KEY_BACKSPACE (127)
#define KEY_DELETE (126) #define KEY_DELETE (126)
struct shell_cmd { struct shell_cmd {
char *name; char *name;
int (*exec)(const char *args[]); int (*exec) (const char *args[]);
}; };
static const struct shell_cmd cmds_list[] = { static const struct shell_cmd cmds_list[] = {
{ "pll", cmd_pll }, {"pll", cmd_pll},
{ "gui", cmd_gui }, {"gui", cmd_gui},
{ "ver", cmd_version }, {"ver", cmd_version},
{ "stat", cmd_stat }, {"stat", cmd_stat},
{ "ptp", cmd_ptp }, {"ptp", cmd_ptp},
{ "mode", cmd_mode }, {"mode", cmd_mode},
{ "calibration", cmd_calib }, {"calibration", cmd_calib},
{ "set", cmd_set }, {"set", cmd_set},
{ "env", cmd_env }, {"env", cmd_env},
{ "saveenv", cmd_saveenv }, {"saveenv", cmd_saveenv},
{ "time", cmd_time }, {"time", cmd_time},
{ "sfp", cmd_sfp }, {"sfp", cmd_sfp},
{ "init", cmd_init }, {"init", cmd_init},
#if WITH_ETHERBONE #if WITH_ETHERBONE
{ "ip", cmd_ip }, {"ip", cmd_ip},
#endif #endif
{ "mac", cmd_mac }, {"mac", cmd_mac},
{ "sdb", cmd_sdb }, {"sdb", cmd_sdb},
{ NULL, NULL } {NULL, NULL}
}; };
static char cmd_buf[SH_MAX_LINE_LEN + 1]; static char cmd_buf[SH_MAX_LINE_LEN + 1];
static int cmd_pos = 0, cmd_len = 0; static int cmd_pos = 0, cmd_len = 0;
...@@ -64,11 +62,12 @@ static int current_key = 0; ...@@ -64,11 +62,12 @@ static int current_key = 0;
static int insert(char c) static int insert(char c)
{ {
if(cmd_len >= SH_MAX_LINE_LEN) if (cmd_len >= SH_MAX_LINE_LEN)
return 0; return 0;
if(cmd_pos != cmd_len) if (cmd_pos != cmd_len)
memmove(&cmd_buf[cmd_pos+1], &cmd_buf[cmd_pos], cmd_len - cmd_pos); memmove(&cmd_buf[cmd_pos + 1], &cmd_buf[cmd_pos],
cmd_len - cmd_pos);
cmd_buf[cmd_pos] = c; cmd_buf[cmd_pos] = c;
cmd_pos++; cmd_pos++;
...@@ -79,7 +78,7 @@ static int insert(char c) ...@@ -79,7 +78,7 @@ static int insert(char c)
static void delete(int where) static void delete(int where)
{ {
memmove(&cmd_buf[where], &cmd_buf[where+1], cmd_len - where); memmove(&cmd_buf[where], &cmd_buf[where + 1], cmd_len - where);
cmd_len--; cmd_len--;
} }
...@@ -90,39 +89,39 @@ static void esc(char code) ...@@ -90,39 +89,39 @@ static void esc(char code)
static int _shell_exec() static int _shell_exec()
{ {
char *tokptr[SH_MAX_ARGS+1]; char *tokptr[SH_MAX_ARGS + 1];
int n = 0, i = 0; int n = 0, i = 0;
memset(tokptr, 0, sizeof(tokptr)); memset(tokptr, 0, sizeof(tokptr));
while(1) while (1) {
{ if (n >= SH_MAX_ARGS)
if(n >= SH_MAX_ARGS)
break; break;
while(cmd_buf[i] == ' ' && cmd_buf[i]) cmd_buf[i++] = 0; while (cmd_buf[i] == ' ' && cmd_buf[i])
cmd_buf[i++] = 0;
if(!cmd_buf[i]) if (!cmd_buf[i])
break; break;
tokptr [n++] = &cmd_buf[i]; tokptr[n++] = &cmd_buf[i];
while(cmd_buf[i] != ' ' && cmd_buf[i]) i++; while (cmd_buf[i] != ' ' && cmd_buf[i])
i++;
if(!cmd_buf[i]) if (!cmd_buf[i])
break; break;
} }
if(!n) if (!n)
return 0; return 0;
if(*tokptr[0] == '#') if (*tokptr[0] == '#')
return 0; return 0;
for(i=0; cmds_list[i].name; i++) for (i = 0; cmds_list[i].name; i++)
if(!strcasecmp(cmds_list[i].name, tokptr[0])) if (!strcasecmp(cmds_list[i].name, tokptr[0])) {
{ int rv = cmds_list[i].exec((const char **)tokptr + 1);
int rv = cmds_list[i].exec((const char **)tokptr+1); if (rv < 0)
if(rv<0)
mprintf("Err %d\n", rv); mprintf("Err %d\n", rv);
return rv; return rv;
} }
...@@ -149,149 +148,145 @@ void shell_init() ...@@ -149,149 +148,145 @@ void shell_init()
void shell_interactive() void shell_interactive()
{ {
int c; int c;
switch(state) switch (state) {
{ case SH_PROMPT:
case SH_PROMPT: mprintf("wrc# ");
mprintf("wrc# "); cmd_pos = 0;
cmd_pos = 0; cmd_len = 0;
cmd_len = 0; state = SH_INPUT;
state = SH_INPUT; break;
break;
case SH_INPUT:
c = uart_read_byte();
if (c < 0)
return;
if (c == 27 || ((current_key & ESCAPE_FLAG) && c == 91))
current_key = ESCAPE_FLAG;
else
current_key |= c;
if (current_key & 0xff) {
switch (current_key) {
case KEY_LEFT:
if (cmd_pos > 0) {
cmd_pos--;
esc('D');
}
break;
case KEY_RIGHT:
if (cmd_pos < cmd_len) {
cmd_pos++;
esc('C');
}
break;
case KEY_ENTER:
mprintf("\n");
state = SH_EXEC;
break;
case SH_INPUT: case KEY_DELETE:
c = uart_read_byte(); if (cmd_pos != cmd_len) {
delete(cmd_pos);
if(c < 0) esc('P');
return; }
break;
if(c == 27 || ((current_key & ESCAPE_FLAG) && c == 91))
current_key = ESCAPE_FLAG; case KEY_BACKSPACE:
else if (cmd_pos > 0) {
current_key |= c; esc('D');
esc('P');
if(current_key & 0xff) delete(cmd_pos - 1);
{ cmd_pos--;
}
switch(current_key) break;
{
case KEY_LEFT:
if(cmd_pos > 0)
{
cmd_pos--;
esc('D');
}
break;
case KEY_RIGHT:
if(cmd_pos < cmd_len)
{
cmd_pos++;
esc('C');
}
break;
case KEY_ENTER:
mprintf("\n");
state = SH_EXEC;
break;
case KEY_DELETE:
if(cmd_pos != cmd_len)
{
delete(cmd_pos);
esc('P');
}
break;
case KEY_BACKSPACE:
if(cmd_pos > 0)
{
esc('D');
esc('P');
delete(cmd_pos-1);
cmd_pos--;
}
break;
case '\t':
break;
default:
if(!(current_key & ESCAPE_FLAG) && insert(current_key))
{
esc('@');
mprintf("%c", current_key);
}
break;
case '\t':
break;
default:
if (!(current_key & ESCAPE_FLAG)
&& insert(current_key)) {
esc('@');
mprintf("%c", current_key);
} }
current_key = 0; break;
} }
break; current_key = 0;
}
break;
case SH_EXEC: case SH_EXEC:
cmd_buf[cmd_len] = 0; cmd_buf[cmd_len] = 0;
_shell_exec(); _shell_exec();
state = SH_PROMPT; state = SH_PROMPT;
break; break;
} }
} }
const char* fromhex(const char* hex, int* v) { const char *fromhex(const char *hex, int *v)
int o = 0; {
int o = 0;
for (; *hex; ++hex) {
if (*hex >= '0' && *hex <= '9') { for (; *hex; ++hex) {
o = (o << 4) + (*hex - '0'); if (*hex >= '0' && *hex <= '9') {
} else if (*hex >= 'A' && *hex <= 'F') { o = (o << 4) + (*hex - '0');
o = (o << 4) + (*hex - 'A') + 10; } else if (*hex >= 'A' && *hex <= 'F') {
} else if (*hex >= 'a' && *hex <= 'f') { o = (o << 4) + (*hex - 'A') + 10;
o = (o << 4) + (*hex - 'a') + 10; } else if (*hex >= 'a' && *hex <= 'f') {
} else { o = (o << 4) + (*hex - 'a') + 10;
break; } else {
} break;
} }
}
*v = o;
return hex; *v = o;
return hex;
} }
const char* fromdec(const char* dec, int* v) { const char *fromdec(const char *dec, int *v)
int o = 0; {
int o = 0;
for (; *dec; ++dec) { for (; *dec; ++dec) {
if (*dec >= '0' && *dec <= '9') { if (*dec >= '0' && *dec <= '9') {
o = (o * 10) + (*dec - '0'); o = (o * 10) + (*dec - '0');
} else { } else {
break; break;
} }
} }
*v = o; *v = o;
return dec; return dec;
} }
int shell_boot_script(void) int shell_boot_script(void)
{ {
uint8_t next=0; uint8_t next = 0;
//first check if EEPROM is really there //first check if EEPROM is really there
eeprom_present(WRPC_FMC_I2C, FMC_EEPROM_ADR); eeprom_present(WRPC_FMC_I2C, FMC_EEPROM_ADR);
if(!has_eeprom) return -1; if (!has_eeprom)
return -1;
while(1)
{ while (1) {
cmd_len = eeprom_init_readcmd(WRPC_FMC_I2C, FMC_EEPROM_ADR, cmd_buf, SH_MAX_LINE_LEN, next); cmd_len = eeprom_init_readcmd(WRPC_FMC_I2C, FMC_EEPROM_ADR,
if(cmd_len <= 0) cmd_buf, SH_MAX_LINE_LEN, next);
{ if (cmd_len <= 0) {
if(next==0) mprintf("Empty init script...\n"); if (next == 0)
break; mprintf("Empty init script...\n");
} break;
cmd_buf[cmd_len-1] = 0; }
cmd_buf[cmd_len - 1] = 0;
mprintf("executing: %s\n", cmd_buf);
_shell_exec(); mprintf("executing: %s\n", cmd_buf);
next = 1; _shell_exec();
} next = 1;
}
return 0;
return 0;
} }
...@@ -34,6 +34,7 @@ ...@@ -34,6 +34,7 @@
ushort utilcrc16[MAX_PORTNUM]; ushort utilcrc16[MAX_PORTNUM];
uchar utilcrc8[MAX_PORTNUM]; uchar utilcrc8[MAX_PORTNUM];
static short oddparity[16] = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; static short oddparity[16] = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
static uchar dscrc_table[] = { static uchar dscrc_table[] = {
0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65,
157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220,
...@@ -59,8 +60,8 @@ static uchar dscrc_table[] = { ...@@ -59,8 +60,8 @@ static uchar dscrc_table[] = {
// //
void setcrc16(int portnum, ushort reset) void setcrc16(int portnum, ushort reset)
{ {
utilcrc16[portnum&0x0FF] = reset; utilcrc16[portnum & 0x0FF] = reset;
return; return;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -72,8 +73,8 @@ void setcrc16(int portnum, ushort reset) ...@@ -72,8 +73,8 @@ void setcrc16(int portnum, ushort reset)
// //
void setcrc8(int portnum, uchar reset) void setcrc8(int portnum, uchar reset)
{ {
utilcrc8[portnum&0x0FF] = reset; utilcrc8[portnum & 0x0FF] = reset;
return; return;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -88,18 +89,18 @@ void setcrc8(int portnum, uchar reset) ...@@ -88,18 +89,18 @@ void setcrc8(int portnum, uchar reset)
// //
ushort docrc16(int portnum, ushort cdata) ushort docrc16(int portnum, ushort cdata)
{ {
cdata = (cdata ^ (utilcrc16[portnum&0x0FF] & 0xff)) & 0xff; cdata = (cdata ^ (utilcrc16[portnum & 0x0FF] & 0xff)) & 0xff;
utilcrc16[portnum&0x0FF] >>= 8; utilcrc16[portnum & 0x0FF] >>= 8;
if (oddparity[cdata & 0xf] ^ oddparity[cdata >> 4]) if (oddparity[cdata & 0xf] ^ oddparity[cdata >> 4])
utilcrc16[portnum&0x0FF] ^= 0xc001; utilcrc16[portnum & 0x0FF] ^= 0xc001;
cdata <<= 6; cdata <<= 6;
utilcrc16[portnum&0x0FF] ^= cdata; utilcrc16[portnum & 0x0FF] ^= cdata;
cdata <<= 1; cdata <<= 1;
utilcrc16[portnum&0x0FF] ^= cdata; utilcrc16[portnum & 0x0FF] ^= cdata;
return utilcrc16[portnum&0x0FF]; return utilcrc16[portnum & 0x0FF];
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -114,6 +115,6 @@ ushort docrc16(int portnum, ushort cdata) ...@@ -114,6 +115,6 @@ ushort docrc16(int portnum, ushort cdata)
// //
uchar docrc8(int portnum, uchar x) uchar docrc8(int portnum, uchar x)
{ {
utilcrc8[portnum&0x0FF] = dscrc_table[utilcrc8[portnum&0x0FF] ^ x]; utilcrc8[portnum & 0x0FF] = dscrc_table[utilcrc8[portnum & 0x0FF] ^ x];
return utilcrc8[portnum&0x0FF]; return utilcrc8[portnum & 0x0FF];
} }
...@@ -8,54 +8,52 @@ ...@@ -8,54 +8,52 @@
//#define DEBUG_EEP43 1 //#define DEBUG_EEP43 1
int Write43(int portnum, uchar *SerialNum, int page, uchar *page_buffer) int Write43(int portnum, uchar * SerialNum, int page, uchar * page_buffer)
{ {
uchar rt=FALSE; uchar rt = FALSE;
ushort lastcrc16; ushort lastcrc16;
int i; int i;
owSerialNum(portnum, SerialNum, FALSE); owSerialNum(portnum, SerialNum, FALSE);
if(owAccess(portnum)) if (owAccess(portnum)) {
{
#if DEBUG_EEP43 #if DEBUG_EEP43
mprintf(" Writing Scratchpad...\n"); mprintf(" Writing Scratchpad...\n");
#endif #endif
if (!owWriteBytePower(portnum, WRITE_SCRATCH_CMD)) if (!owWriteBytePower(portnum, WRITE_SCRATCH_CMD))
return FALSE; return FALSE;
setcrc16(portnum, 0); setcrc16(portnum, 0);
docrc16(portnum,(ushort)WRITE_SCRATCH_CMD); docrc16(portnum, (ushort) WRITE_SCRATCH_CMD);
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
owWriteBytePower(portnum, 0x00); //write LSB of target addr owWriteBytePower(portnum, 0x00); //write LSB of target addr
docrc16(portnum,(ushort)0x00); docrc16(portnum, (ushort) 0x00);
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
owWriteBytePower(portnum, 0x00); //write MSB of target addr owWriteBytePower(portnum, 0x00); //write MSB of target addr
docrc16(portnum,(ushort)0x00); docrc16(portnum, (ushort) 0x00);
for(i = 0; i < 32; i++) //write 32 data bytes to scratchpad for (i = 0; i < 32; i++) //write 32 data bytes to scratchpad
{ {
owLevel(portnum,MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
owWriteBytePower(portnum, page_buffer[i]); owWriteBytePower(portnum, page_buffer[i]);
lastcrc16 = docrc16(portnum, page_buffer[i]); lastcrc16 = docrc16(portnum, page_buffer[i]);
// mprintf(" CRC16: %x\n", lastcrc16); // mprintf(" CRC16: %x\n", lastcrc16);
} }
for(i = 0; i < 2; i++) //read two bytes CRC16 for (i = 0; i < 2; i++) //read two bytes CRC16
{ {
owLevel(portnum,MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
lastcrc16 = docrc16(portnum,(ushort)owReadBytePower(portnum)); lastcrc16 =
docrc16(portnum, (ushort) owReadBytePower(portnum));
} }
#if DEBUG_EEP43 #if DEBUG_EEP43
mprintf(" CRC16: %x\n", lastcrc16); mprintf(" CRC16: %x\n", lastcrc16);
#endif #endif
if(lastcrc16 == 0xb001) if (lastcrc16 == 0xb001) {
{
//copy to mem //copy to mem
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
if(Copy2Mem43(portnum, SerialNum)) if (Copy2Mem43(portnum, SerialNum))
rt=TRUE; rt = TRUE;
} }
} }
...@@ -64,17 +62,16 @@ int Write43(int portnum, uchar *SerialNum, int page, uchar *page_buffer) ...@@ -64,17 +62,16 @@ int Write43(int portnum, uchar *SerialNum, int page, uchar *page_buffer)
return rt; return rt;
} }
int Copy2Mem43(int portnum, uchar *SerialNum) int Copy2Mem43(int portnum, uchar * SerialNum)
{ {
uchar rt=FALSE; uchar rt = FALSE;
ushort lastcrc16; ushort lastcrc16;
int i; int i;
uchar read_data; uchar read_data;
owSerialNum(portnum, SerialNum, FALSE); owSerialNum(portnum, SerialNum, FALSE);
if(owAccess(portnum)) if (owAccess(portnum)) {
{
if (!owWriteBytePower(portnum, COPY_SCRATCH_CMD)) if (!owWriteBytePower(portnum, COPY_SCRATCH_CMD))
return FALSE; return FALSE;
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
...@@ -86,26 +83,24 @@ int Copy2Mem43(int portnum, uchar *SerialNum) ...@@ -86,26 +83,24 @@ int Copy2Mem43(int portnum, uchar *SerialNum)
usleep(500000); usleep(500000);
owLevel(portnum, MODE_NORMAL);
owLevel(portnum,MODE_NORMAL);
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
if (read_data == 0xaa) if (read_data == 0xaa)
rt=TRUE; rt = TRUE;
} }
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
return rt; return rt;
} }
// routine for reading the scratchpad of a DS28EC20P EEPROM // routine for reading the scratchpad of a DS28EC20P EEPROM
// 80 pages of 32byte // 80 pages of 32byte
// 32byte scratchpad // 32byte scratchpad
// expects 32 byte deep buffer // expects 32 byte deep buffer
int ReadScratch43(int portnum, uchar *SerialNum, uchar *page_buffer) int ReadScratch43(int portnum, uchar * SerialNum, uchar * page_buffer)
{ {
uchar rt=FALSE; uchar rt = FALSE;
ushort lastcrc16; ushort lastcrc16;
int i; int i;
ushort target_addr = 0; ushort target_addr = 0;
...@@ -113,66 +108,60 @@ int ReadScratch43(int portnum, uchar *SerialNum, uchar *page_buffer) ...@@ -113,66 +108,60 @@ int ReadScratch43(int portnum, uchar *SerialNum, uchar *page_buffer)
owSerialNum(portnum, SerialNum, FALSE); owSerialNum(portnum, SerialNum, FALSE);
if(owAccess(portnum)) if (owAccess(portnum)) {
{
#if DEBUG_EEP43 #if DEBUG_EEP43
mprintf(" Reading Scratchpad...\n"); mprintf(" Reading Scratchpad...\n");
#endif #endif
if (!owWriteBytePower(portnum, READ_SCRATCH_CMD)) if (!owWriteBytePower(portnum, READ_SCRATCH_CMD))
return FALSE; return FALSE;
setcrc16(portnum, 0); //init crc setcrc16(portnum, 0); //init crc
docrc16(portnum,(ushort)READ_SCRATCH_CMD); docrc16(portnum, (ushort) READ_SCRATCH_CMD);
owLevel(portnum, MODE_NORMAL); //read 2 byte address and 1 byte status
owLevel(portnum,MODE_NORMAL); //read 2 byte address and 1 byte status
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, read_data); lastcrc16 = docrc16(portnum, read_data);
target_addr = read_data; target_addr = read_data;
owLevel(portnum,MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, read_data); lastcrc16 = docrc16(portnum, read_data);
target_addr |= read_data << 8; target_addr |= read_data << 8;
owLevel(portnum,MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, read_data); lastcrc16 = docrc16(portnum, read_data);
#if DEBUG_EEP43 #if DEBUG_EEP43
mprintf("E/S: 0x%x\n", read_data); mprintf("E/S: 0x%x\n", read_data);
#endif #endif
for(i = 0; i < 32; i++) for (i = 0; i < 32; i++) {
{ owLevel(portnum, MODE_NORMAL);
owLevel(portnum,MODE_NORMAL);
page_buffer[i] = owReadBytePower(portnum); page_buffer[i] = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, page_buffer[i]); lastcrc16 = docrc16(portnum, page_buffer[i]);
// mprintf("send_block[%d]: %x", i, send_block[i]); // mprintf("send_block[%d]: %x", i, send_block[i]);
// mprintf(" CRC16: %x", lastcrc16); // mprintf(" CRC16: %x", lastcrc16);
// mprintf(" CRC16i: %x\n", ~lastcrc16); // mprintf(" CRC16i: %x\n", ~lastcrc16);
} }
for(i = 0; i < 2; i++) for (i = 0; i < 2; i++) {
{ owLevel(portnum, MODE_NORMAL);
owLevel(portnum,MODE_NORMAL);
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, read_data); lastcrc16 = docrc16(portnum, read_data);
} }
if (lastcrc16 == 0xb001) if (lastcrc16 == 0xb001)
rt=TRUE; rt = TRUE;
} }
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
return rt; return rt;
} }
// routine for reading a memory page of a DS28EC20P EEPROM // routine for reading a memory page of a DS28EC20P EEPROM
// expects 32 byte deep buffer // expects 32 byte deep buffer
int ReadMem43(int portnum, uchar *SerialNum, int page, uchar *page_buffer) int ReadMem43(int portnum, uchar * SerialNum, int page, uchar * page_buffer)
{ {
uchar rt=FALSE; uchar rt = FALSE;
ushort lastcrc16; ushort lastcrc16;
int i; int i;
ushort target_addr = 0; ushort target_addr = 0;
...@@ -180,39 +169,36 @@ int ReadMem43(int portnum, uchar *SerialNum, int page, uchar *page_buffer) ...@@ -180,39 +169,36 @@ int ReadMem43(int portnum, uchar *SerialNum, int page, uchar *page_buffer)
owSerialNum(portnum, SerialNum, FALSE); owSerialNum(portnum, SerialNum, FALSE);
if(owAccess(portnum)) if (owAccess(portnum)) {
{
if (!owWriteBytePower(portnum, E_READ_MEM_CMD)) if (!owWriteBytePower(portnum, E_READ_MEM_CMD))
return FALSE; return FALSE;
setcrc16(portnum, 0); //init crc setcrc16(portnum, 0); //init crc
docrc16(portnum,(ushort)E_READ_MEM_CMD); docrc16(portnum, (ushort) E_READ_MEM_CMD);
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
owWriteBytePower(portnum, 0x00); //write LSB of target addr owWriteBytePower(portnum, 0x00); //write LSB of target addr
docrc16(portnum,(ushort)0x00); docrc16(portnum, (ushort) 0x00);
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
owWriteBytePower(portnum, 0x00); //write MSB of target addr owWriteBytePower(portnum, 0x00); //write MSB of target addr
docrc16(portnum,(ushort)0x00); docrc16(portnum, (ushort) 0x00);
for(i = 0; i < 32; i++) for (i = 0; i < 32; i++) {
{ owLevel(portnum, MODE_NORMAL);
owLevel(portnum,MODE_NORMAL);
page_buffer[i] = owReadBytePower(portnum); page_buffer[i] = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, page_buffer[i]); lastcrc16 = docrc16(portnum, page_buffer[i]);
// mprintf("send_block[%d]: %x", i, send_block[i]); // mprintf("send_block[%d]: %x", i, send_block[i]);
// mprintf(" CRC16: %x", lastcrc16); // mprintf(" CRC16: %x", lastcrc16);
// mprintf(" CRC16i: %x\n", ~lastcrc16); // mprintf(" CRC16i: %x\n", ~lastcrc16);
} }
for(i = 0; i < 2; i++) for (i = 0; i < 2; i++) {
{ owLevel(portnum, MODE_NORMAL);
owLevel(portnum,MODE_NORMAL);
read_data = owReadBytePower(portnum); read_data = owReadBytePower(portnum);
lastcrc16 = docrc16(portnum, read_data); lastcrc16 = docrc16(portnum, read_data);
} }
if (lastcrc16 == 0xb001) if (lastcrc16 == 0xb001)
rt=TRUE; rt = TRUE;
} }
owLevel(portnum, MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
#define EEP43_H #define EEP43_H
/* returns TRUE for success */ /* returns TRUE for success */
int Write43(int portnum, uchar *SerialNum, int page, uchar *page_buffer); int Write43(int portnum, uchar * SerialNum, int page, uchar * page_buffer);
int ReadMem43(int portnum, uchar *SerialNum, int page, uchar *page_buffer); int ReadMem43(int portnum, uchar * SerialNum, int page, uchar * page_buffer);
#endif #endif
...@@ -49,30 +49,29 @@ ...@@ -49,30 +49,29 @@
// Returns: TRUE(1) success, device type found // Returns: TRUE(1) success, device type found
// FALSE(0) device not found // FALSE(0) device not found
// //
SMALLINT FindDevices(int portnum, uchar FamilySN[][8], SMALLINT family_code, int MAXDEVICES) SMALLINT FindDevices(int portnum, uchar FamilySN[][8], SMALLINT family_code,
int MAXDEVICES)
{ {
int NumDevices=0; int NumDevices = 0;
// find the devices // find the devices
// set the search to first find that family code // set the search to first find that family code
owFamilySearchSetup(portnum,family_code); owFamilySearchSetup(portnum, family_code);
// loop to find all of the devices up to MAXDEVICES // loop to find all of the devices up to MAXDEVICES
NumDevices = 0; NumDevices = 0;
do do {
{ // perform the search
// perform the search if (!owNext(portnum, TRUE, FALSE))
if (!owNext(portnum,TRUE, FALSE)) break;
break;
owSerialNum(portnum,FamilySN[NumDevices], TRUE); owSerialNum(portnum, FamilySN[NumDevices], TRUE);
if ((FamilySN[NumDevices][0] & 0x7F) == (family_code & 0x7F)) if ((FamilySN[NumDevices][0] & 0x7F) == (family_code & 0x7F)) {
{ NumDevices++;
NumDevices++; }
} }
} while (NumDevices < (MAXDEVICES - 1));
while (NumDevices < (MAXDEVICES - 1));
// check if not at least 1 device // check if not at least 1 device
return NumDevices; return NumDevices;
} }
...@@ -30,4 +30,4 @@ ...@@ -30,4 +30,4 @@
// //
//---------------------------------------------------------------------- //----------------------------------------------------------------------
SMALLINT FindDevices(int,uchar FamilySN[][8],SMALLINT,int); SMALLINT FindDevices(int, uchar FamilySN[][8], SMALLINT, int);
...@@ -34,14 +34,13 @@ ...@@ -34,14 +34,13 @@
#include "ownet.h" #include "ownet.h"
#include "uart.h" #include "uart.h"
#ifndef SIZE_OWERROR_STACK #ifndef SIZE_OWERROR_STACK
#ifdef SOCKIT_OWM_ERR_SMALL #ifdef SOCKIT_OWM_ERR_SMALL
//for small memory, only hold 1 error //for small memory, only hold 1 error
#define SIZE_OWERROR_STACK 1 #define SIZE_OWERROR_STACK 1
#else #else
#define SIZE_OWERROR_STACK 10 #define SIZE_OWERROR_STACK 10
#endif #endif
#endif #endif
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
...@@ -50,12 +49,11 @@ ...@@ -50,12 +49,11 @@
// Error Struct for holding error information. // Error Struct for holding error information.
// In DEBUG, this will also hold the line number and filename. // In DEBUG, this will also hold the line number and filename.
typedef struct typedef struct {
{ int owErrorNum;
int owErrorNum;
#ifdef DEBUG #ifdef DEBUG
int lineno; int lineno;
char *filename; char *filename;
#endif #endif
} owErrorStruct; } owErrorStruct;
...@@ -66,7 +64,6 @@ static owErrorStruct owErrorStack[SIZE_OWERROR_STACK]; ...@@ -66,7 +64,6 @@ static owErrorStruct owErrorStack[SIZE_OWERROR_STACK];
// Stack pointer to top-most error. // Stack pointer to top-most error.
static int owErrorPointer = 0; static int owErrorPointer = 0;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// Functions Definitions // Functions Definitions
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
...@@ -74,17 +71,16 @@ int owGetErrorNum(void); ...@@ -74,17 +71,16 @@ int owGetErrorNum(void);
void owClearError(void); void owClearError(void);
int owHasErrors(void); int owHasErrors(void);
#ifdef DEBUG #ifdef DEBUG
void owRaiseError(int,int,char*); void owRaiseError(int, int, char *);
#else #else
void owRaiseError(int); void owRaiseError(int);
#endif #endif
#ifndef SOCKIT_OWM_ERR_SMALL #ifndef SOCKIT_OWM_ERR_SMALL
void owPrintErrorMsg(FILE *); void owPrintErrorMsg(FILE *);
void owPrintErrorMsgStd(); void owPrintErrorMsgStd();
char *owGetErrorMsg(int); char *owGetErrorMsg(int);
#endif #endif
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// The 'owGetErroNum' returns the error code of the top-most error on the // The 'owGetErroNum' returns the error code of the top-most error on the
// error stack. NOTE: This function has the side effect of popping the // error stack. NOTE: This function has the side effect of popping the
...@@ -97,13 +93,13 @@ int owHasErrors(void); ...@@ -97,13 +93,13 @@ int owHasErrors(void);
// //
int owGetErrorNum(void) int owGetErrorNum(void)
{ {
int i = owErrorStack[ owErrorPointer ].owErrorNum; int i = owErrorStack[owErrorPointer].owErrorNum;
owErrorStack[ owErrorPointer ].owErrorNum = 0; owErrorStack[owErrorPointer].owErrorNum = 0;
if(!owErrorPointer) if (!owErrorPointer)
owErrorPointer = SIZE_OWERROR_STACK - 1; owErrorPointer = SIZE_OWERROR_STACK - 1;
else else
owErrorPointer = (owErrorPointer - 1); owErrorPointer = (owErrorPointer - 1);
return i; return i;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -111,7 +107,7 @@ int owGetErrorNum(void) ...@@ -111,7 +107,7 @@ int owGetErrorNum(void)
// //
void owClearError(void) void owClearError(void)
{ {
owErrorStack[ owErrorPointer ].owErrorNum = 0; owErrorStack[owErrorPointer].owErrorNum = 0;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -123,10 +119,10 @@ void owClearError(void) ...@@ -123,10 +119,10 @@ void owClearError(void)
// //
int owHasErrors(void) int owHasErrors(void)
{ {
if(owErrorStack[ owErrorPointer ].owErrorNum) if (owErrorStack[owErrorPointer].owErrorNum)
return 1; //TRUE return 1; //TRUE
else else
return 0; //FALSE return 0; //FALSE
} }
#ifdef DEBUG #ifdef DEBUG
...@@ -138,13 +134,13 @@ int owHasErrors(void) ...@@ -138,13 +134,13 @@ int owHasErrors(void)
// int lineno - DEBUG only - the line number where it was raised // int lineno - DEBUG only - the line number where it was raised
// char* filename - DEBUG only - the file name where it occured. // char* filename - DEBUG only - the file name where it occured.
// //
void owRaiseError(int err, int lineno, char* filename) void owRaiseError(int err, int lineno, char *filename)
{ {
owErrorPointer = (owErrorPointer + 1) % SIZE_OWERROR_STACK; owErrorPointer = (owErrorPointer + 1) % SIZE_OWERROR_STACK;
owErrorStack[ owErrorPointer ].owErrorNum = err; owErrorStack[owErrorPointer].owErrorNum = err;
owErrorStack[ owErrorPointer ].lineno = lineno; owErrorStack[owErrorPointer].lineno = lineno;
owErrorStack[ owErrorPointer ].filename = filename; owErrorStack[owErrorPointer].filename = filename;
} }
#else #else
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// The 'owRaiseError' is the method for raising an error onto the error // The 'owRaiseError' is the method for raising an error onto the error
...@@ -152,152 +148,150 @@ int owHasErrors(void) ...@@ -152,152 +148,150 @@ int owHasErrors(void)
// //
// Arguments: int err - the error code you wish to raise. // Arguments: int err - the error code you wish to raise.
// //
void owRaiseError(int err) void owRaiseError(int err)
{ {
owErrorPointer = (owErrorPointer + 1) % SIZE_OWERROR_STACK; owErrorPointer = (owErrorPointer + 1) % SIZE_OWERROR_STACK;
owErrorStack[ owErrorPointer ].owErrorNum = err; owErrorStack[owErrorPointer].owErrorNum = err;
} }
#endif #endif
// SOCKIT_OWM_ERR_SMALL - embedded microcontrollers, where these // SOCKIT_OWM_ERR_SMALL - embedded microcontrollers, where these
// messaging functions might not make any sense. // messaging functions might not make any sense.
#ifndef SOCKIT_OWM_ERR_SMALL #ifndef SOCKIT_OWM_ERR_SMALL
//Array of meaningful error messages to associate with codes. //Array of meaningful error messages to associate with codes.
//Not used on targets with low memory (i.e. PIC). //Not used on targets with low memory (i.e. PIC).
static char *owErrorMsg[125] = static char *owErrorMsg[125] = {
{ /*000 */ "No Error Was Set",
/*000*/ "No Error Was Set", /*001 */ "No Devices found on 1-Wire Network",
/*001*/ "No Devices found on 1-Wire Network", /*002 */ "1-Wire Net Reset Failed",
/*002*/ "1-Wire Net Reset Failed", /*003 */ "Search ROM Error: Couldn't locate next device on 1-Wire",
/*003*/ "Search ROM Error: Couldn't locate next device on 1-Wire", /*004 */ "Access Failed: Could not select device",
/*004*/ "Access Failed: Could not select device", /*005 */ "DS2480B Adapter Not Detected",
/*005*/ "DS2480B Adapter Not Detected", /*006 */ "DS2480B: Wrong Baud",
/*006*/ "DS2480B: Wrong Baud", /*007 */ "DS2480B: Bad Response",
/*007*/ "DS2480B: Bad Response", /*008 */ "Open COM Failed",
/*008*/ "Open COM Failed", /*009 */ "Write COM Failed",
/*009*/ "Write COM Failed", /*010 */ "Read COM Failed",
/*010*/ "Read COM Failed", /*011 */ "Data Block Too Large",
/*011*/ "Data Block Too Large", /*012 */ "Block Transfer failed",
/*012*/ "Block Transfer failed", /*013 */ "Program Pulse Failed",
/*013*/ "Program Pulse Failed", /*014 */ "Program Byte Failed",
/*014*/ "Program Byte Failed", /*015 */ "Write Byte Failed",
/*015*/ "Write Byte Failed", /*016 */ "Read Byte Failed",
/*016*/ "Read Byte Failed", /*017 */ "Write Verify Failed",
/*017*/ "Write Verify Failed", /*018 */ "Read Verify Failed",
/*018*/ "Read Verify Failed", /*019 */ "Write Scratchpad Failed",
/*019*/ "Write Scratchpad Failed", /*020 */ "Copy Scratchpad Failed",
/*020*/ "Copy Scratchpad Failed", /*021 */ "Incorrect CRC Length",
/*021*/ "Incorrect CRC Length", /*022 */ "CRC Failed",
/*022*/ "CRC Failed", /*023 */ "Failed to acquire a necessary system resource",
/*023*/ "Failed to acquire a necessary system resource", /*024 */ "Failed to initialize system resource",
/*024*/ "Failed to initialize system resource", /*025 */ "Data too long to fit on specified device.",
/*025*/ "Data too long to fit on specified device.", /*026 */ "Read exceeds memory bank end.",
/*026*/ "Read exceeds memory bank end.", /*027 */ "Write exceeds memory bank end.",
/*027*/ "Write exceeds memory bank end.", /*028 */ "Device select failed",
/*028*/ "Device select failed", /*029 */ "Read Scratch Pad verify failed.",
/*029*/ "Read Scratch Pad verify failed.", /*030 */ "Copy scratchpad complete not found",
/*030*/ "Copy scratchpad complete not found", /*031 */ "Erase scratchpad complete not found",
/*031*/ "Erase scratchpad complete not found", /*032 */ "Address read back from scrachpad was incorrect",
/*032*/ "Address read back from scrachpad was incorrect", /*033 */ "Read page with extra-info not supported by this memory bank",
/*033*/ "Read page with extra-info not supported by this memory bank", /*034 */ "Read page packet with extra-info not supported by this memory bank",
/*034*/ "Read page packet with extra-info not supported by this memory bank", /*035 */ "Length of packet requested exceeds page size",
/*035*/ "Length of packet requested exceeds page size", /*036 */ "Invalid length in packet",
/*036*/ "Invalid length in packet", /*037 */ "Program pulse required but not available",
/*037*/ "Program pulse required but not available", /*038 */ "Trying to access a read-only memory bank",
/*038*/ "Trying to access a read-only memory bank", /*039 */ "Current bank is not general purpose memory",
/*039*/ "Current bank is not general purpose memory", /*040 */ "Read back from write compare is incorrect, page may be locked",
/*040*/ "Read back from write compare is incorrect, page may be locked", /*041 */ "Invalid page number for this memory bank",
/*041*/ "Invalid page number for this memory bank", /*042 */ "Read page with CRC not supported by this memory bank",
/*042*/ "Read page with CRC not supported by this memory bank", /*043 */ "Read page with CRC and extra-info not supported by this memory bank",
/*043*/ "Read page with CRC and extra-info not supported by this memory bank", /*044 */ "Read back from write incorrect, could not lock page",
/*044*/ "Read back from write incorrect, could not lock page", /*045 */ "Read back from write incorrect, could not lock redirect byte",
/*045*/ "Read back from write incorrect, could not lock redirect byte", /*046 */ "The read of the status was not completed.",
/*046*/ "The read of the status was not completed.", /*047 */ "Page redirection not supported by this memory bank",
/*047*/ "Page redirection not supported by this memory bank", /*048 */ "Lock Page redirection not supported by this memory bank",
/*048*/ "Lock Page redirection not supported by this memory bank", /*049 */ "Read back byte on EPROM programming did not match.",
/*049*/ "Read back byte on EPROM programming did not match.", /*050 */ "Can not write to a page that is locked.",
/*050*/ "Can not write to a page that is locked.", /*051 */ "Can not lock a redirected page that has already been locked.",
/*051*/ "Can not lock a redirected page that has already been locked.", /*052 */ "Trying to redirect a locked redirected page.",
/*052*/ "Trying to redirect a locked redirected page.", /*053 */ "Trying to lock a page that is already locked.",
/*053*/ "Trying to lock a page that is already locked.", /*054 */ "Trying to write to a memory bank that is write protected.",
/*054*/ "Trying to write to a memory bank that is write protected.", /*055 */ "Error due to not matching MAC.",
/*055*/ "Error due to not matching MAC.", /*056 */ "Memory Bank is write protected.",
/*056*/ "Memory Bank is write protected.", /*057 */ "Secret is write protected, can not Load First Secret.",
/*057*/ "Secret is write protected, can not Load First Secret.", /*058 */ "Error in Reading Scratchpad after Computing Next Secret.",
/*058*/ "Error in Reading Scratchpad after Computing Next Secret.", /*059 */ "Load Error from Loading First Secret.",
/*059*/ "Load Error from Loading First Secret.", /*060 */ "Power delivery required but not available",
/*060*/ "Power delivery required but not available", /*061 */ "Not a valid file name.",
/*061*/ "Not a valid file name.", /*062 */ "Unable to Create a Directory in this part.",
/*062*/ "Unable to Create a Directory in this part.", /*063 */ "That file already exists.",
/*063*/ "That file already exists.", /*064 */ "The directory is not empty.",
/*064*/ "The directory is not empty.", /*065 */ "The wrong type of part for this operation.",
/*065*/ "The wrong type of part for this operation.", /*066 */ "The max len for this file is too small.",
/*066*/ "The max len for this file is too small.", /*067 */ "This is not a write once bank.",
/*067*/ "This is not a write once bank.", /*068 */ "The file can not be found.",
/*068*/ "The file can not be found.", /*069 */ "There is not enough space available.",
/*069*/ "There is not enough space available.", /*070 */ "There is not a page to match that bit in the bitmap.",
/*070*/ "There is not a page to match that bit in the bitmap.", /*071 */ "There are no jobs for EPROM parts.",
/*071*/ "There are no jobs for EPROM parts.", /*072 */ "Function not supported to modify attributes.",
/*072*/ "Function not supported to modify attributes.", /*073 */ "Handle is not in use.",
/*073*/ "Handle is not in use.", /*074 */ "Tring to read a write only file.",
/*074*/ "Tring to read a write only file.", /*075 */ "There is no handle available for use.",
/*075*/ "There is no handle available for use.", /*076 */ "The directory provided is an invalid directory.",
/*076*/ "The directory provided is an invalid directory.", /*077 */ "Handle does not exist.",
/*077*/ "Handle does not exist.", /*078 */ "Serial Number did not match with current job.",
/*078*/ "Serial Number did not match with current job.", /*079 */ "Can not program EPROM because a non-EPROM part on the network.",
/*079*/ "Can not program EPROM because a non-EPROM part on the network.", /*080 */ "Write protect redirection byte is set.",
/*080*/ "Write protect redirection byte is set.", /*081 */ "There is an inappropriate directory length.",
/*081*/ "There is an inappropriate directory length.", /*082 */ "The file has already been terminated.",
/*082*/ "The file has already been terminated.", /*083 */ "Failed to read memory page of iButton part.",
/*083*/ "Failed to read memory page of iButton part.", /*084 */ "Failed to match scratchpad of iButton part.",
/*084*/ "Failed to match scratchpad of iButton part.", /*085 */ "Failed to erase scratchpad of iButton part.",
/*085*/ "Failed to erase scratchpad of iButton part.", /*086 */ "Failed to read scratchpad of iButton part.",
/*086*/ "Failed to read scratchpad of iButton part.", /*087 */ "Failed to execute SHA function on SHA iButton.",
/*087*/ "Failed to execute SHA function on SHA iButton.", /*088 */ "SHA iButton did not return a status completion byte.",
/*088*/ "SHA iButton did not return a status completion byte.", /*089 */ "Write data page failed.",
/*089*/ "Write data page failed.", /*090 */ "Copy secret into secret memory pages failed.",
/*090*/ "Copy secret into secret memory pages failed.", /*091 */ "Bind unique secret to iButton failed.",
/*091*/ "Bind unique secret to iButton failed.", /*092 */ "Could not install secret into user token.",
/*092*/ "Could not install secret into user token.", /*093 */ "Transaction Incomplete: signature did not match.",
/*093*/ "Transaction Incomplete: signature did not match.", /*094 */ "Transaction Incomplete: could not sign service data.",
/*094*/ "Transaction Incomplete: could not sign service data.", /*095 */ "User token did not provide a valid authentication response.",
/*095*/ "User token did not provide a valid authentication response.", /*096 */ "Failed to answer a challenge on the user token.",
/*096*/ "Failed to answer a challenge on the user token.", /*097 */ "Failed to create a challenge on the coprocessor.",
/*097*/ "Failed to create a challenge on the coprocessor.", /*098 */ "Transaction Incomplete: service data was not valid.",
/*098*/ "Transaction Incomplete: service data was not valid.", /*099 */ "Transaction Incomplete: service data was not updated.",
/*099*/ "Transaction Incomplete: service data was not updated.", /*100 */ "Unrecoverable, catastrophic service failure occured.",
/*100*/ "Unrecoverable, catastrophic service failure occured.", /*101 */ "Load First Secret from scratchpad data failed.",
/*101*/ "Load First Secret from scratchpad data failed.", /*102 */ "Failed to match signature of user's service data.",
/*102*/ "Failed to match signature of user's service data.", /*103 */ "Subkey out of range for the DS1991.",
/*103*/ "Subkey out of range for the DS1991.", /*104 */ "Block ID out of range for the DS1991",
/*104*/ "Block ID out of range for the DS1991", /*105 */ "Password is enabled",
/*105*/ "Password is enabled", /*106 */ "Password is invalid",
/*106*/ "Password is invalid", /*107 */ "This memory bank has no read only password",
/*107*/ "This memory bank has no read only password", /*108 */ "This memory bank has no read/write password",
/*108*/ "This memory bank has no read/write password", /*109 */ "1-Wire is shorted",
/*109*/ "1-Wire is shorted", /*110 */ "Error communicating with 1-Wire adapter",
/*110*/ "Error communicating with 1-Wire adapter", /*111 */ "CopyScratchpad failed: Ending Offset must go to end of page",
/*111*/ "CopyScratchpad failed: Ending Offset must go to end of page", /*112 */ "WriteScratchpad failed: Ending Offset must go to end of page",
/*112*/ "WriteScratchpad failed: Ending Offset must go to end of page", /*113 */ "Mission can not be stopped while one is not in progress",
/*113*/ "Mission can not be stopped while one is not in progress", /*114 */ "Error stopping the mission",
/*114*/ "Error stopping the mission", /*115 */ "Port number is outside (0,MAX_PORTNUM) interval",
/*115*/ "Port number is outside (0,MAX_PORTNUM) interval", /*116 */ "Level of the 1-Wire was not changed",
/*116*/ "Level of the 1-Wire was not changed", /*117 */ "Both the Read Only and Read Write Passwords must be set",
/*117*/ "Both the Read Only and Read Write Passwords must be set", /*118 */ "Failure to change latch state."
/*118*/ "Failure to change latch state." /*119 */ "Could not open usb port through libusb",
/*119*/ "Could not open usb port through libusb", /*120 */ "Libusb DS2490 port already opened",
/*120*/ "Libusb DS2490 port already opened", /*121 */ "Failed to set libusb configuration",
/*121*/ "Failed to set libusb configuration", /*122 */ "Failed to claim libusb interface",
/*122*/ "Failed to claim libusb interface", /*123 */ "Failed to set libusb altinterface",
/*123*/ "Failed to set libusb altinterface", /*124 */ "No adapter found at this port number"
/*124*/ "No adapter found at this port number" };
};
char *owGetErrorMsg(int err) char *owGetErrorMsg(int err)
{ {
return owErrorMsg[err]; return owErrorMsg[err];
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// The 'owPrintErrorMsg' is the method for printing an error from the stack. // The 'owPrintErrorMsg' is the method for printing an error from the stack.
...@@ -313,30 +307,30 @@ int owHasErrors(void) ...@@ -313,30 +307,30 @@ int owHasErrors(void)
// //
// Arguments: FILE*: the destination for printing. // Arguments: FILE*: the destination for printing.
// //
void owPrintErrorMsg(FILE *filenum) void owPrintErrorMsg(FILE * filenum)
{ {
#ifdef DEBUG #ifdef DEBUG
int l = owErrorStack[ owErrorPointer ].lineno; int l = owErrorStack[owErrorPointer].lineno;
char *f = owErrorStack[ owErrorPointer ].filename; char *f = owErrorStack[owErrorPointer].filename;
int err = owGetErrorNum(); int err = owGetErrorNum();
//fprintf(filenum,"Error %d: %s line %d: %s\r\n",err,f,l,owErrorMsg[err]); //fprintf(filenum,"Error %d: %s line %d: %s\r\n",err,f,l,owErrorMsg[err]);
#else #else
int err = owGetErrorNum(); int err = owGetErrorNum();
//fprintf(filenum,"Error %d: %s\r\n",err,owErrorMsg[err]); //fprintf(filenum,"Error %d: %s\r\n",err,owErrorMsg[err]);
#endif #endif
} }
// Same as above, except uses default printf output // Same as above, except uses default printf output
void owPrintErrorMsgStd() void owPrintErrorMsgStd()
{ {
#ifdef DEBUG #ifdef DEBUG
int l = owErrorStack[ owErrorPointer ].lineno; int l = owErrorStack[owErrorPointer].lineno;
char *f = owErrorStack[ owErrorPointer ].filename; char *f = owErrorStack[owErrorPointer].filename;
int err = owGetErrorNum(); int err = owGetErrorNum();
mprintf("Error %d: %s line %d: %s\r\n",err,f,l,owErrorMsg[err]); mprintf("Error %d: %s line %d: %s\r\n", err, f, l, owErrorMsg[err]);
#else #else
int err = owGetErrorNum(); int err = owGetErrorNum();
mprintf("Error %d: %s\r\n",err,owErrorMsg[err]); mprintf("Error %d: %s\r\n", err, owErrorMsg[err]);
#endif #endif
} }
#endif #endif
...@@ -45,40 +45,41 @@ ...@@ -45,40 +45,41 @@
//#define S_PWR 0 //#define S_PWR 0
#define S_IEN 0 #define S_IEN 0
#define S_OVD_E 1 #define S_OVD_E 1
#define CLK_DIV_NOR (CPU_CLOCK/200000-1) //clock divider for normal mode #define CLK_DIV_NOR (CPU_CLOCK/200000-1) //clock divider for normal mode
#define CLK_DIV_OVD (CPU_CLOCK/1000000-1) //clock divider for overdrive mode #define CLK_DIV_OVD (CPU_CLOCK/1000000-1) //clock divider for overdrive mode
// exportable link-level functions // exportable link-level functions
SMALLINT owTouchReset(int); SMALLINT owTouchReset(int);
SMALLINT owTouchBit(int,SMALLINT); SMALLINT owTouchBit(int, SMALLINT);
SMALLINT owTouchByte(int,SMALLINT); SMALLINT owTouchByte(int, SMALLINT);
SMALLINT owWriteByte(int,SMALLINT); SMALLINT owWriteByte(int, SMALLINT);
SMALLINT owReadByte(int); SMALLINT owReadByte(int);
SMALLINT owSpeed(int,SMALLINT); SMALLINT owSpeed(int, SMALLINT);
SMALLINT owLevel(int,SMALLINT); SMALLINT owLevel(int, SMALLINT);
SMALLINT owProgramPulse(int); SMALLINT owProgramPulse(int);
//void msDelay(int); //void msDelay(int);
long msGettick(void); long msGettick(void);
SMALLINT owWriteBytePower(int,SMALLINT); SMALLINT owWriteBytePower(int, SMALLINT);
SMALLINT owReadBytePower(int); SMALLINT owReadBytePower(int);
SMALLINT owReadBitPower(int,SMALLINT); SMALLINT owReadBitPower(int, SMALLINT);
SMALLINT owHasPowerDelivery(int); SMALLINT owHasPowerDelivery(int);
SMALLINT owHasOverDrive(int); SMALLINT owHasOverDrive(int);
SMALLINT owHasProgramPulse(int); SMALLINT owHasProgramPulse(int);
SMALLINT owInit(void); SMALLINT owInit(void);
int S_OVD = 0; int S_OVD = 0;
int S_PWR = 0; int S_PWR = 0;
// init clock divider for SCU board // init clock divider for SCU board
SMALLINT owInit(void) SMALLINT owInit(void)
{ {
IOWR_SOCKIT_OWM_CDR(BASE_ONEWIRE, ((CLK_DIV_NOR & SOCKIT_OWM_CDR_N_MSK) | ((CLK_DIV_OVD << SOCKIT_OWM_CDR_O_OFST) & SOCKIT_OWM_CDR_O_MSK))); IOWR_SOCKIT_OWM_CDR(BASE_ONEWIRE,
((CLK_DIV_NOR & SOCKIT_OWM_CDR_N_MSK) |
((CLK_DIV_OVD << SOCKIT_OWM_CDR_O_OFST) &
SOCKIT_OWM_CDR_O_MSK)));
return 0; return 0;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// Reset all of the devices on the 1-Wire Net and return the result. // Reset all of the devices on the 1-Wire Net and return the result.
// //
...@@ -90,21 +91,23 @@ SMALLINT owInit(void) ...@@ -90,21 +91,23 @@ SMALLINT owInit(void)
// //
SMALLINT owTouchReset(int portnum) SMALLINT owTouchReset(int portnum)
{ {
int reg; int reg;
int ovd = (S_OVD >> portnum) & 0x1; int ovd = (S_OVD >> portnum) & 0x1;
IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST ) IOWR_SOCKIT_OWM_CTL(BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST)
| (portnum << SOCKIT_OWM_CTL_SEL_OFST ) | (portnum << SOCKIT_OWM_CTL_SEL_OFST)
| (S_IEN ? SOCKIT_OWM_CTL_IEN_MSK : 0x00) | (S_IEN ? SOCKIT_OWM_CTL_IEN_MSK : 0x00)
| ( SOCKIT_OWM_CTL_CYC_MSK ) | (SOCKIT_OWM_CTL_CYC_MSK)
| (ovd ? SOCKIT_OWM_CTL_OVD_MSK : 0x00) | (ovd ? SOCKIT_OWM_CTL_OVD_MSK : 0x00)
| ( SOCKIT_OWM_CTL_RST_MSK )); | (SOCKIT_OWM_CTL_RST_MSK));
// wait for STX (end of transfer cycle) and read the presence status // wait for STX (end of transfer cycle) and read the presence status
while ((reg = IORD_SOCKIT_OWM_CTL (BASE_ONEWIRE)) & SOCKIT_OWM_CTL_CYC_MSK); while ((reg = IORD_SOCKIT_OWM_CTL(BASE_ONEWIRE))
& SOCKIT_OWM_CTL_CYC_MSK)
// return negated DAT (presence detect) ;
return (~reg & SOCKIT_OWM_CTL_DAT_MSK); // NOTE the shortcut
// return negated DAT (presence detect)
return (~reg & SOCKIT_OWM_CTL_DAT_MSK); // NOTE the shortcut
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -122,24 +125,24 @@ SMALLINT owTouchReset(int portnum) ...@@ -122,24 +125,24 @@ SMALLINT owTouchReset(int portnum)
// //
SMALLINT owTouchBit(int portnum, SMALLINT sendbit) SMALLINT owTouchBit(int portnum, SMALLINT sendbit)
{ {
int reg; int reg;
int ovd = (S_OVD >> portnum) & 0x1; int ovd = (S_OVD >> portnum) & 0x1;
// read/write data
// read/write data IOWR_SOCKIT_OWM_CTL(BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST)
IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST ) | (portnum << SOCKIT_OWM_CTL_SEL_OFST)
| (portnum << SOCKIT_OWM_CTL_SEL_OFST ) | (S_IEN ? SOCKIT_OWM_CTL_IEN_MSK : 0x00)
| (S_IEN ? SOCKIT_OWM_CTL_IEN_MSK : 0x00) | (SOCKIT_OWM_CTL_CYC_MSK)
| ( SOCKIT_OWM_CTL_CYC_MSK ) | (ovd ? SOCKIT_OWM_CTL_OVD_MSK : 0x00)
| (ovd ? SOCKIT_OWM_CTL_OVD_MSK : 0x00) | (sendbit & SOCKIT_OWM_CTL_DAT_MSK)); // NOTE the shortcut
| (sendbit & SOCKIT_OWM_CTL_DAT_MSK )); // NOTE the shortcut
// wait for STX (end of transfer cycle) and read the read data bit
// wait for STX (end of transfer cycle) and read the read data bit while ((reg = IORD_SOCKIT_OWM_CTL(BASE_ONEWIRE))
while ((reg = IORD_SOCKIT_OWM_CTL (BASE_ONEWIRE)) & SOCKIT_OWM_CTL_CYC_MSK); & SOCKIT_OWM_CTL_CYC_MSK)
;
// return DAT (read bit) // return DAT (read bit)
return (reg & SOCKIT_OWM_CTL_DAT_MSK); // NOTE the shortcut return (reg & SOCKIT_OWM_CTL_DAT_MSK); // NOTE the shortcut
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -156,14 +159,13 @@ SMALLINT owTouchBit(int portnum, SMALLINT sendbit) ...@@ -156,14 +159,13 @@ SMALLINT owTouchBit(int portnum, SMALLINT sendbit)
// //
SMALLINT owTouchByte(int portnum, SMALLINT sendbyte) SMALLINT owTouchByte(int portnum, SMALLINT sendbyte)
{ {
int i; int i;
SMALLINT dat = 0; SMALLINT dat = 0;
for (i=0; i<8; i++) for (i = 0; i < 8; i++) {
{ dat |= owTouchBit(portnum, sendbyte & 0x1) << i;
dat |= owTouchBit(portnum,sendbyte & 0x1) << i; sendbyte >>= 1;
sendbyte >>= 1; }
} return dat;
return dat;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -180,7 +182,7 @@ SMALLINT owTouchByte(int portnum, SMALLINT sendbyte) ...@@ -180,7 +182,7 @@ SMALLINT owTouchByte(int portnum, SMALLINT sendbyte)
// //
SMALLINT owWriteByte(int portnum, SMALLINT sendbyte) SMALLINT owWriteByte(int portnum, SMALLINT sendbyte)
{ {
return (owTouchByte(portnum,sendbyte) == sendbyte) ? TRUE : FALSE; return (owTouchByte(portnum, sendbyte) == sendbyte) ? TRUE : FALSE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -194,7 +196,7 @@ SMALLINT owWriteByte(int portnum, SMALLINT sendbyte) ...@@ -194,7 +196,7 @@ SMALLINT owWriteByte(int portnum, SMALLINT sendbyte)
// //
SMALLINT owReadByte(int portnum) SMALLINT owReadByte(int portnum)
{ {
return owTouchByte(portnum,0xFF); return owTouchByte(portnum, 0xFF);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -210,15 +212,17 @@ SMALLINT owReadByte(int portnum) ...@@ -210,15 +212,17 @@ SMALLINT owReadByte(int portnum)
// //
SMALLINT owSpeed(int portnum, SMALLINT new_speed) SMALLINT owSpeed(int portnum, SMALLINT new_speed)
{ {
int select; int select;
select = 0x1 << portnum; select = 0x1 << portnum;
//if overdrive is implemented use it //if overdrive is implemented use it
if (S_OVD_E) { if (S_OVD_E) {
if (new_speed == MODE_OVERDRIVE) S_OVD |= select; if (new_speed == MODE_OVERDRIVE)
if (new_speed == MODE_NORMAL ) S_OVD &= ~select; S_OVD |= select;
} if (new_speed == MODE_NORMAL)
// return the current port state S_OVD &= ~select;
return (S_OVD & select) ? MODE_OVERDRIVE : MODE_NORMAL; }
// return the current port state
return (S_OVD & select) ? MODE_OVERDRIVE : MODE_NORMAL;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -237,18 +241,21 @@ SMALLINT owSpeed(int portnum, SMALLINT new_speed) ...@@ -237,18 +241,21 @@ SMALLINT owSpeed(int portnum, SMALLINT new_speed)
// //
SMALLINT owLevel(int portnum, SMALLINT new_level) SMALLINT owLevel(int portnum, SMALLINT new_level)
{ {
if (new_level == MODE_STRONG5) { if (new_level == MODE_STRONG5) {
// set the power bit // set the power bit
S_PWR |= (1 << portnum); S_PWR |= (1 << portnum);
IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST) | SOCKIT_OWM_CTL_PWR_MSK); IOWR_SOCKIT_OWM_CTL(BASE_ONEWIRE,
} (S_PWR << SOCKIT_OWM_CTL_POWER_OFST) |
if (new_level == MODE_NORMAL) { SOCKIT_OWM_CTL_PWR_MSK);
// clear the power bit }
S_PWR &= ~(1 << portnum); if (new_level == MODE_NORMAL) {
IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, (S_PWR << SOCKIT_OWM_CTL_POWER_OFST)); // clear the power bit
} S_PWR &= ~(1 << portnum);
// return the current port state IOWR_SOCKIT_OWM_CTL(BASE_ONEWIRE,
return ((S_PWR >> portnum) & 0x1) ? MODE_STRONG5 : MODE_NORMAL; (S_PWR << SOCKIT_OWM_CTL_POWER_OFST));
}
// return the current port state
return ((S_PWR >> portnum) & 0x1) ? MODE_STRONG5 : MODE_NORMAL;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -263,7 +270,7 @@ SMALLINT owLevel(int portnum, SMALLINT new_level) ...@@ -263,7 +270,7 @@ SMALLINT owLevel(int portnum, SMALLINT new_level)
// //
SMALLINT owProgramPulse(int portnum) SMALLINT owProgramPulse(int portnum)
{ {
return owHasProgramPulse(portnum); return owHasProgramPulse(portnum);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -278,7 +285,6 @@ SMALLINT owProgramPulse(int portnum) ...@@ -278,7 +285,6 @@ SMALLINT owProgramPulse(int portnum)
// compute the number delay cycles depending on delay time // compute the number delay cycles depending on delay time
len = (len * S_F_DLY) >> 16; len = (len * S_F_DLY) >> 16;
for (i=0; i<len; i++) { for (i=0; i<len; i++) {
// create a 960us pause // create a 960us pause
IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, ( S_PWR << SOCKIT_OWM_CTL_POWER_OFST ) IOWR_SOCKIT_OWM_CTL (BASE_ONEWIRE, ( S_PWR << SOCKIT_OWM_CTL_POWER_OFST )
...@@ -288,7 +294,8 @@ SMALLINT owProgramPulse(int portnum) ...@@ -288,7 +294,8 @@ SMALLINT owProgramPulse(int portnum)
| ( SOCKIT_OWM_CTL_DLY_MSK )); | ( SOCKIT_OWM_CTL_DLY_MSK ));
// wait for STX (end of transfer cycle) // wait for STX (end of transfer cycle)
while (IORD_SOCKIT_OWM_CTL (BASE_ONEWIRE) & SOCKIT_OWM_CTL_CYC_MSK); while (IORD_SOCKIT_OWM_CTL (BASE_ONEWIRE) & SOCKIT_OWM_CTL_CYC_MSK)
;
} }
#else #else
...@@ -309,11 +316,11 @@ SMALLINT owProgramPulse(int portnum) ...@@ -309,11 +316,11 @@ SMALLINT owProgramPulse(int portnum)
long msGettick(void) long msGettick(void)
{ {
#ifdef UCOS_II #ifdef UCOS_II
// uCOS-II tick counter // uCOS-II tick counter
OSTimeGet(); OSTimeGet();
#else #else
// TODO add platform specific code here // TODO add platform specific code here
return 0; return 0;
#endif #endif
} }
...@@ -332,16 +339,16 @@ OSTimeGet(); ...@@ -332,16 +339,16 @@ OSTimeGet();
// //
SMALLINT owWriteBytePower(int portnum, SMALLINT sendbyte) SMALLINT owWriteBytePower(int portnum, SMALLINT sendbyte)
{ {
if (!owHasPowerDelivery(portnum)) if (!owHasPowerDelivery(portnum))
return FALSE; return FALSE;
if(owTouchByte(portnum,sendbyte) != sendbyte) if (owTouchByte(portnum, sendbyte) != sendbyte)
return FALSE; return FALSE;
if(owLevel(portnum,MODE_STRONG5) != MODE_STRONG5) if (owLevel(portnum, MODE_STRONG5) != MODE_STRONG5)
return FALSE; return FALSE;
return TRUE; return TRUE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -360,16 +367,16 @@ SMALLINT owWriteBytePower(int portnum, SMALLINT sendbyte) ...@@ -360,16 +367,16 @@ SMALLINT owWriteBytePower(int portnum, SMALLINT sendbyte)
// //
SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse) SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse)
{ {
if (!owHasPowerDelivery(portnum)) if (!owHasPowerDelivery(portnum))
return FALSE; return FALSE;
if(owTouchBit(portnum,0x01) != applyPowerResponse) if (owTouchBit(portnum, 0x01) != applyPowerResponse)
return FALSE; return FALSE;
if(owLevel(portnum,MODE_STRONG5) != MODE_STRONG5) if (owLevel(portnum, MODE_STRONG5) != MODE_STRONG5)
return FALSE; return FALSE;
return TRUE; return TRUE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -384,17 +391,17 @@ SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse) ...@@ -384,17 +391,17 @@ SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse)
// //
SMALLINT owReadBytePower(int portnum) SMALLINT owReadBytePower(int portnum)
{ {
SMALLINT getbyte; SMALLINT getbyte;
if (!owHasPowerDelivery(portnum)) if (!owHasPowerDelivery(portnum))
return FALSE; return FALSE;
getbyte = owTouchByte(portnum,0xFF); getbyte = owTouchByte(portnum, 0xFF);
if (owLevel(portnum,MODE_STRONG5) != MODE_STRONG5) if (owLevel(portnum, MODE_STRONG5) != MODE_STRONG5)
return FALSE; return FALSE;
return getbyte; return getbyte;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -407,7 +414,7 @@ SMALLINT owReadBytePower(int portnum) ...@@ -407,7 +414,7 @@ SMALLINT owReadBytePower(int portnum)
// //
SMALLINT owHasPowerDelivery(int portnum) SMALLINT owHasPowerDelivery(int portnum)
{ {
return TRUE; return TRUE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -420,7 +427,7 @@ SMALLINT owHasPowerDelivery(int portnum) ...@@ -420,7 +427,7 @@ SMALLINT owHasPowerDelivery(int portnum)
// //
SMALLINT owHasOverDrive(int portnum) SMALLINT owHasOverDrive(int portnum)
{ {
return S_OVD_E; return S_OVD_E;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -434,5 +441,5 @@ SMALLINT owHasOverDrive(int portnum) ...@@ -434,5 +441,5 @@ SMALLINT owHasOverDrive(int portnum)
// FALSE program voltage not available // FALSE program voltage not available
SMALLINT owHasProgramPulse(int portnum) SMALLINT owHasProgramPulse(int portnum)
{ {
return FALSE; return FALSE;
} }
...@@ -41,9 +41,8 @@ ...@@ -41,9 +41,8 @@
#include <stdio.h> #include <stdio.h>
#include "ownet.h" #include "ownet.h"
// exportable functions defined in ownet.c // exportable functions defined in ownet.c
SMALLINT bitacc(SMALLINT,SMALLINT,SMALLINT,uchar *); SMALLINT bitacc(SMALLINT, SMALLINT, SMALLINT, uchar *);
// global variables for this module to hold search state information // global variables for this module to hold search state information
static SMALLINT LastDiscrepancy[MAX_PORTNUM]; static SMALLINT LastDiscrepancy[MAX_PORTNUM];
...@@ -72,12 +71,12 @@ uchar SerialNum[MAX_PORTNUM][8]; ...@@ -72,12 +71,12 @@ uchar SerialNum[MAX_PORTNUM][8];
// //
SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only) SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only)
{ {
// reset the search state // reset the search state
LastDiscrepancy[portnum] = 0; LastDiscrepancy[portnum] = 0;
LastDevice[portnum] = FALSE; LastDevice[portnum] = FALSE;
LastFamilyDiscrepancy[portnum] = 0; LastFamilyDiscrepancy[portnum] = 0;
return owNext(portnum,do_reset,alarm_only); return owNext(portnum, do_reset, alarm_only);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -105,135 +104,135 @@ SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only) ...@@ -105,135 +104,135 @@ SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only)
// //
SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only) SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only)
{ {
uchar bit_test, search_direction, bit_number; uchar bit_test, search_direction, bit_number;
uchar last_zero, serial_byte_number, next_result; uchar last_zero, serial_byte_number, next_result;
uchar serial_byte_mask; uchar serial_byte_mask;
uchar lastcrc8 = 0; uchar lastcrc8 = 0;
// initialize for search // initialize for search
bit_number = 1; bit_number = 1;
last_zero = 0; last_zero = 0;
serial_byte_number = 0; serial_byte_number = 0;
serial_byte_mask = 1; serial_byte_mask = 1;
next_result = 0; next_result = 0;
setcrc8(portnum,0); setcrc8(portnum, 0);
// if the last call was not the last one // if the last call was not the last one
if (!LastDevice[portnum]) if (!LastDevice[portnum]) {
{ // check if reset first is requested
// check if reset first is requested if (do_reset) {
if (do_reset) // reset the 1-wire
{ // if there are no parts on 1-wire, return FALSE
// reset the 1-wire if (!owTouchReset(portnum)) {
// if there are no parts on 1-wire, return FALSE // reset the search
if (!owTouchReset(portnum)) LastDiscrepancy[portnum] = 0;
{ LastFamilyDiscrepancy[portnum] = 0;
// reset the search OWERROR(OWERROR_NO_DEVICES_ON_NET);
LastDiscrepancy[portnum] = 0; return FALSE;
LastFamilyDiscrepancy[portnum] = 0; }
OWERROR(OWERROR_NO_DEVICES_ON_NET); }
return FALSE; // If finding alarming devices issue a different command
} if (alarm_only)
} owWriteByte(portnum, 0xEC); // issue the alarming search command
else
// If finding alarming devices issue a different command owWriteByte(portnum, 0xF0); // issue the search command
if (alarm_only)
owWriteByte(portnum,0xEC); // issue the alarming search command //pause before beginning the search
else //usDelay(100);
owWriteByte(portnum,0xF0); // issue the search command
// loop to do the search
//pause before beginning the search do {
//usDelay(100); // read a bit and its compliment
bit_test = owTouchBit(portnum, 1) << 1;
// loop to do the search bit_test |= owTouchBit(portnum, 1);
do
{ // check for no devices on 1-wire
// read a bit and its compliment if (bit_test == 3)
bit_test = owTouchBit(portnum,1) << 1; break;
bit_test |= owTouchBit(portnum,1); else {
// all devices coupled have 0 or 1
// check for no devices on 1-wire if (bit_test > 0)
if (bit_test == 3) search_direction = !(bit_test & 0x01); // bit write value for search
break; else {
else // if this discrepancy if before the Last Discrepancy
{ // on a previous next then pick the same as last time
// all devices coupled have 0 or 1 if (bit_number <
if (bit_test > 0) LastDiscrepancy[portnum])
search_direction = !(bit_test & 0x01); // bit write value for search search_direction =
else ((SerialNum[portnum]
{ [serial_byte_number] &
// if this discrepancy if before the Last Discrepancy serial_byte_mask) > 0);
// on a previous next then pick the same as last time else
if (bit_number < LastDiscrepancy[portnum]) // if equal to last pick 1, if not then pick 0
search_direction = ((SerialNum[portnum][serial_byte_number] & serial_byte_mask) > 0); search_direction =
else (bit_number ==
// if equal to last pick 1, if not then pick 0 LastDiscrepancy[portnum]);
search_direction = (bit_number == LastDiscrepancy[portnum]);
// if 0 was picked then record its position in LastZero
// if 0 was picked then record its position in LastZero if (search_direction == 0) {
if (search_direction == 0) last_zero = bit_number;
{
last_zero = bit_number; // check for Last discrepancy in family
if (last_zero < 9)
// check for Last discrepancy in family LastFamilyDiscrepancy
if (last_zero < 9) [portnum] =
LastFamilyDiscrepancy[portnum] = last_zero; last_zero;
} }
} }
// set or clear the bit in the SerialNum[portnum] byte serial_byte_number // set or clear the bit in the SerialNum[portnum] byte serial_byte_number
// with mask serial_byte_mask // with mask serial_byte_mask
if (search_direction == 1) if (search_direction == 1)
SerialNum[portnum][serial_byte_number] |= serial_byte_mask; SerialNum[portnum][serial_byte_number]
else |= serial_byte_mask;
SerialNum[portnum][serial_byte_number] &= ~serial_byte_mask; else
SerialNum[portnum][serial_byte_number]
// serial number search direction write bit &= ~serial_byte_mask;
owTouchBit(portnum,search_direction);
// serial number search direction write bit
// increment the byte counter bit_number owTouchBit(portnum, search_direction);
// and shift the mask serial_byte_mask
bit_number++; // increment the byte counter bit_number
serial_byte_mask <<= 1; // and shift the mask serial_byte_mask
bit_number++;
// if the mask is 0 then go to new SerialNum[portnum] byte serial_byte_number serial_byte_mask <<= 1;
// and reset mask
if (serial_byte_mask == 0) // if the mask is 0 then go to new SerialNum[portnum] byte serial_byte_number
{ // and reset mask
// The below has been added to accomidate the valid CRC with the if (serial_byte_mask == 0) {
// possible changing serial number values of the DS28E04. // The below has been added to accomidate the valid CRC with the
if (((SerialNum[portnum][0] & 0x7F) == 0x1C) && (serial_byte_number == 1)) // possible changing serial number values of the DS28E04.
lastcrc8 = docrc8(portnum,0x7F); if (((SerialNum[portnum][0] & 0x7F) ==
else 0x1C) && (serial_byte_number == 1))
lastcrc8 = docrc8(portnum,SerialNum[portnum][serial_byte_number]); // accumulate the CRC lastcrc8 =
docrc8(portnum, 0x7F);
serial_byte_number++; else
serial_byte_mask = 1; lastcrc8 = docrc8(portnum, SerialNum[portnum][serial_byte_number]); // accumulate the CRC
}
} serial_byte_number++;
} serial_byte_mask = 1;
while(serial_byte_number < 8); // loop until through all SerialNum[portnum] bytes 0-7 }
}
// if the search was successful then }
if (!((bit_number < 65) || lastcrc8)) while (serial_byte_number < 8); // loop until through all SerialNum[portnum] bytes 0-7
{
// search successful so set LastDiscrepancy[portnum],LastDevice[portnum],next_result // if the search was successful then
LastDiscrepancy[portnum] = last_zero; if (!((bit_number < 65) || lastcrc8)) {
LastDevice[portnum] = (LastDiscrepancy[portnum] == 0); // search successful so set LastDiscrepancy[portnum],LastDevice[portnum],next_result
next_result = TRUE; LastDiscrepancy[portnum] = last_zero;
} LastDevice[portnum] = (LastDiscrepancy[portnum] == 0);
} next_result = TRUE;
}
// if no device found then reset counters so next 'next' will be }
// like a first // if no device found then reset counters so next 'next' will be
if (!next_result || !SerialNum[portnum][0]) // like a first
{ if (!next_result || !SerialNum[portnum][0]) {
LastDiscrepancy[portnum] = 0; LastDiscrepancy[portnum] = 0;
LastDevice[portnum] = FALSE; LastDevice[portnum] = FALSE;
LastFamilyDiscrepancy[portnum] = 0; LastFamilyDiscrepancy[portnum] = 0;
next_result = FALSE; next_result = FALSE;
} }
return next_result; return next_result;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -254,22 +253,20 @@ SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only) ...@@ -254,22 +253,20 @@ SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only)
// 'do_read' - flag to indicate reading (1) or setting (0) the current // 'do_read' - flag to indicate reading (1) or setting (0) the current
// serial number. // serial number.
// //
void owSerialNum(int portnum, uchar *serialnum_buf, SMALLINT do_read) void owSerialNum(int portnum, uchar * serialnum_buf, SMALLINT do_read)
{ {
uchar i; uchar i;
// read the internal buffer and place in 'serialnum_buf' // read the internal buffer and place in 'serialnum_buf'
if (do_read) if (do_read) {
{ for (i = 0; i < 8; i++)
for (i = 0; i < 8; i++) serialnum_buf[i] = SerialNum[portnum][i];
serialnum_buf[i] = SerialNum[portnum][i]; }
} // set the internal buffer from the data in 'serialnum_buf'
// set the internal buffer from the data in 'serialnum_buf' else {
else for (i = 0; i < 8; i++)
{ SerialNum[portnum][i] = serialnum_buf[i];
for (i = 0; i < 8; i++) }
SerialNum[portnum][i] = serialnum_buf[i];
}
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -283,14 +280,14 @@ void owSerialNum(int portnum, uchar *serialnum_buf, SMALLINT do_read) ...@@ -283,14 +280,14 @@ void owSerialNum(int portnum, uchar *serialnum_buf, SMALLINT do_read)
// //
void owFamilySearchSetup(int portnum, SMALLINT search_family) void owFamilySearchSetup(int portnum, SMALLINT search_family)
{ {
uchar i; uchar i;
// set the search state to find SearchFamily type devices // set the search state to find SearchFamily type devices
SerialNum[portnum][0] = search_family; SerialNum[portnum][0] = search_family;
for (i = 1; i < 8; i++) for (i = 1; i < 8; i++)
SerialNum[portnum][i] = 0; SerialNum[portnum][i] = 0;
LastDiscrepancy[portnum] = 64; LastDiscrepancy[portnum] = 64;
LastDevice[portnum] = FALSE; LastDevice[portnum] = FALSE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -301,13 +298,13 @@ void owFamilySearchSetup(int portnum, SMALLINT search_family) ...@@ -301,13 +298,13 @@ void owFamilySearchSetup(int portnum, SMALLINT search_family)
// //
void owSkipFamily(int portnum) void owSkipFamily(int portnum)
{ {
// set the Last discrepancy to last family discrepancy // set the Last discrepancy to last family discrepancy
LastDiscrepancy[portnum] = LastFamilyDiscrepancy[portnum]; LastDiscrepancy[portnum] = LastFamilyDiscrepancy[portnum];
LastFamilyDiscrepancy[portnum] = 0; LastFamilyDiscrepancy[portnum] = 0;
// check for end of list // check for end of list
if (LastDiscrepancy[portnum] == 0) if (LastDiscrepancy[portnum] == 0)
LastDevice[portnum] = TRUE; LastDevice[portnum] = TRUE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -326,42 +323,36 @@ void owSkipFamily(int portnum) ...@@ -326,42 +323,36 @@ void owSkipFamily(int portnum)
// //
SMALLINT owAccess(int portnum) SMALLINT owAccess(int portnum)
{ {
uchar sendpacket[9]; uchar sendpacket[9];
uchar i; uchar i;
// reset the 1-wire // reset the 1-wire
if (owTouchReset(portnum)) if (owTouchReset(portnum)) {
{ // create a buffer to use with block function
// create a buffer to use with block function // match Serial Number command 0x55
// match Serial Number command 0x55 sendpacket[0] = 0x55;
sendpacket[0] = 0x55; // Serial Number
// Serial Number for (i = 1; i < 9; i++)
for (i = 1; i < 9; i++) sendpacket[i] = SerialNum[portnum][i - 1];
sendpacket[i] = SerialNum[portnum][i-1];
// send/recieve the transfer buffer
// send/recieve the transfer buffer if (owBlock(portnum, FALSE, sendpacket, 9)) {
if (owBlock(portnum,FALSE,sendpacket,9)) // verify that the echo of the writes was correct
{ for (i = 1; i < 9; i++)
// verify that the echo of the writes was correct if (sendpacket[i] != SerialNum[portnum][i - 1])
for (i = 1; i < 9; i++) return FALSE;
if (sendpacket[i] != SerialNum[portnum][i-1]) if (sendpacket[0] != 0x55) {
return FALSE; OWERROR(OWERROR_WRITE_VERIFY_FAILED);
if (sendpacket[0] != 0x55) return FALSE;
{ } else
OWERROR(OWERROR_WRITE_VERIFY_FAILED); return TRUE;
return FALSE; } else
} OWERROR(OWERROR_BLOCK_FAILED);
else } else
return TRUE; OWERROR(OWERROR_NO_DEVICES_ON_NET);
}
else // reset or match echo failed
OWERROR(OWERROR_BLOCK_FAILED); return FALSE;
}
else
OWERROR(OWERROR_NO_DEVICES_ON_NET);
// reset or match echo failed
return FALSE;
} }
//---------------------------------------------------------------------- //----------------------------------------------------------------------
...@@ -389,52 +380,53 @@ SMALLINT owAccess(int portnum) ...@@ -389,52 +380,53 @@ SMALLINT owAccess(int portnum)
// //
SMALLINT owVerify(int portnum, SMALLINT alarm_only) SMALLINT owVerify(int portnum, SMALLINT alarm_only)
{ {
uchar i,sendlen=0,goodbits=0,cnt=0,s,tst; uchar i, sendlen = 0, goodbits = 0, cnt = 0, s, tst;
uchar sendpacket[50]; uchar sendpacket[50];
// construct the search // construct the search
if (alarm_only) if (alarm_only)
sendpacket[sendlen++] = 0xEC; // issue the alarming search command sendpacket[sendlen++] = 0xEC; // issue the alarming search command
else else
sendpacket[sendlen++] = 0xF0; // issue the search command sendpacket[sendlen++] = 0xF0; // issue the search command
// set all bits at first // set all bits at first
for (i = 1; i <= 24; i++) for (i = 1; i <= 24; i++)
sendpacket[sendlen++] = 0xFF; sendpacket[sendlen++] = 0xFF;
// now set or clear apropriate bits for search // now set or clear apropriate bits for search
for (i = 0; i < 64; i++) for (i = 0; i < 64; i++)
bitacc(WRITE_FUNCTION,bitacc(READ_FUNCTION,0,i,&SerialNum[portnum][0]),(int)((i+1)*3-1),&sendpacket[1]); bitacc(WRITE_FUNCTION,
bitacc(READ_FUNCTION, 0, i, &SerialNum[portnum][0]),
// send/recieve the transfer buffer (int)((i + 1) * 3 - 1), &sendpacket[1]);
if (owBlock(portnum,TRUE,sendpacket,sendlen))
{ // send/recieve the transfer buffer
// check results to see if it was a success if (owBlock(portnum, TRUE, sendpacket, sendlen)) {
for (i = 0; i < 192; i += 3) // check results to see if it was a success
{ for (i = 0; i < 192; i += 3) {
tst = (bitacc(READ_FUNCTION,0,i,&sendpacket[1]) << 1) | tst =
bitacc(READ_FUNCTION,0,(int)(i+1),&sendpacket[1]); (bitacc(READ_FUNCTION, 0, i, &sendpacket[1]) << 1) |
bitacc(READ_FUNCTION, 0, (int)(i + 1),
s = bitacc(READ_FUNCTION,0,cnt++,&SerialNum[portnum][0]); &sendpacket[1]);
if (tst == 0x03) // no device on line s = bitacc(READ_FUNCTION, 0, cnt++,
{ &SerialNum[portnum][0]);
goodbits = 0; // number of good bits set to zero
break; // quit if (tst == 0x03) // no device on line
} {
goodbits = 0; // number of good bits set to zero
if (((s == 0x01) && (tst == 0x02)) || break; // quit
((s == 0x00) && (tst == 0x01)) ) // correct bit }
goodbits++; // count as a good bit
} if (((s == 0x01) && (tst == 0x02)) || ((s == 0x00) && (tst == 0x01))) // correct bit
goodbits++; // count as a good bit
// check too see if there were enough good bits to be successful }
if (goodbits >= 8)
return TRUE; // check too see if there were enough good bits to be successful
} if (goodbits >= 8)
else return TRUE;
OWERROR(OWERROR_BLOCK_FAILED); } else
OWERROR(OWERROR_BLOCK_FAILED);
// block fail or device not present
return FALSE; // block fail or device not present
return FALSE;
} }
//---------------------------------------------------------------------- //----------------------------------------------------------------------
...@@ -453,55 +445,50 @@ SMALLINT owVerify(int portnum, SMALLINT alarm_only) ...@@ -453,55 +445,50 @@ SMALLINT owVerify(int portnum, SMALLINT alarm_only)
// //
SMALLINT owOverdriveAccess(int portnum) SMALLINT owOverdriveAccess(int portnum)
{ {
uchar sendpacket[8]; uchar sendpacket[8];
uchar i, bad_echo = FALSE; uchar i, bad_echo = FALSE;
// make sure normal level // make sure normal level
owLevel(portnum,MODE_NORMAL); owLevel(portnum, MODE_NORMAL);
// force to normal communication speed // force to normal communication speed
owSpeed(portnum,MODE_NORMAL); owSpeed(portnum, MODE_NORMAL);
// call the 1-Wire Net reset function // call the 1-Wire Net reset function
if (owTouchReset(portnum)) if (owTouchReset(portnum)) {
{ // send the match command 0x69
// send the match command 0x69 if (owWriteByte(portnum, 0x69)) {
if (owWriteByte(portnum,0x69)) // switch to overdrive communication speed
{ owSpeed(portnum, MODE_OVERDRIVE);
// switch to overdrive communication speed
owSpeed(portnum,MODE_OVERDRIVE); // create a buffer to use with block function
// Serial Number
// create a buffer to use with block function for (i = 0; i < 8; i++)
// Serial Number sendpacket[i] = SerialNum[portnum][i];
for (i = 0; i < 8; i++)
sendpacket[i] = SerialNum[portnum][i]; // send/recieve the transfer buffer
if (owBlock(portnum, FALSE, sendpacket, 8)) {
// send/recieve the transfer buffer // verify that the echo of the writes was correct
if (owBlock(portnum,FALSE,sendpacket,8)) for (i = 0; i < 8; i++)
{ if (sendpacket[i] !=
// verify that the echo of the writes was correct SerialNum[portnum][i])
for (i = 0; i < 8; i++) bad_echo = TRUE;
if (sendpacket[i] != SerialNum[portnum][i]) // if echo ok then success
bad_echo = TRUE; if (!bad_echo)
// if echo ok then success return TRUE;
if (!bad_echo) else
return TRUE; OWERROR(OWERROR_WRITE_VERIFY_FAILED);
else } else
OWERROR(OWERROR_WRITE_VERIFY_FAILED); OWERROR(OWERROR_BLOCK_FAILED);
} } else
else OWERROR(OWERROR_WRITE_BYTE_FAILED);
OWERROR(OWERROR_BLOCK_FAILED); } else
} OWERROR(OWERROR_NO_DEVICES_ON_NET);
else
OWERROR(OWERROR_WRITE_BYTE_FAILED); // failure, force back to normal communication speed
} owSpeed(portnum, MODE_NORMAL);
else
OWERROR(OWERROR_NO_DEVICES_ON_NET); return FALSE;
// failure, force back to normal communication speed
owSpeed(portnum,MODE_NORMAL);
return FALSE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -516,22 +503,20 @@ SMALLINT owOverdriveAccess(int portnum) ...@@ -516,22 +503,20 @@ SMALLINT owOverdriveAccess(int portnum)
// Returns: 1 if operation is set (1) // Returns: 1 if operation is set (1)
// 0/1 state of bit number 'loc' if operation is reading // 0/1 state of bit number 'loc' if operation is reading
// //
SMALLINT bitacc(SMALLINT op, SMALLINT state, SMALLINT loc, uchar *buf) SMALLINT bitacc(SMALLINT op, SMALLINT state, SMALLINT loc, uchar * buf)
{ {
SMALLINT nbyt,nbit; SMALLINT nbyt, nbit;
nbyt = (loc / 8); nbyt = (loc / 8);
nbit = loc - (nbyt * 8); nbit = loc - (nbyt * 8);
if (op == WRITE_FUNCTION) if (op == WRITE_FUNCTION) {
{ if (state)
if (state) buf[nbyt] |= (0x01 << nbit);
buf[nbyt] |= (0x01 << nbit); else
else buf[nbyt] &= ~(0x01 << nbit);
buf[nbyt] &= ~(0x01 << nbit);
return 1;
return 1; } else
} return ((buf[nbyt] >> nbit) & 0x01);
else
return ((buf[nbyt] >> nbit) & 0x01);
} }
...@@ -78,31 +78,31 @@ ...@@ -78,31 +78,31 @@
// several kilobytes of data should not be SMALLINT. The most // several kilobytes of data should not be SMALLINT. The most
// common place you'll see smallint is for boolean return types. // common place you'll see smallint is for boolean return types.
// //
#define SMALLINT int #define SMALLINT int
#endif #endif
#ifndef OW_UCHAR #ifndef OW_UCHAR
#define OW_UCHAR #define OW_UCHAR
typedef unsigned char uchar; typedef unsigned char uchar;
#if !defined(__MINGW32__) && (defined(__CYGWIN__) || defined(__GNUC__)) #if !defined(__MINGW32__) && (defined(__CYGWIN__) || defined(__GNUC__))
typedef unsigned long ulong; typedef unsigned long ulong;
//ushort already defined in sys/types.h //ushort already defined in sys/types.h
#include <sys/types.h> #include <sys/types.h>
#else #else
#if defined(_WIN32) || defined(WIN32) || defined(__MC68K__) || defined(_WIN32_WCE) || defined(_DOS) || defined(_WINDOWS) || defined(__MINGW32__) #if defined(_WIN32) || defined(WIN32) || defined(__MC68K__) || defined(_WIN32_WCE) || defined(_DOS) || defined(_WINDOWS) || defined(__MINGW32__)
typedef unsigned short ushort; typedef unsigned short ushort;
typedef unsigned long ulong; typedef unsigned long ulong;
#endif #endif
#endif #endif
#ifdef __sun__ #ifdef __sun__
#include <sys/types.h> #include <sys/types.h>
#endif #endif
#ifdef SDCC #ifdef SDCC
//intent of ushort is 2 bytes unsigned. //intent of ushort is 2 bytes unsigned.
//for ds390 in sdcc, an int, not a short, //for ds390 in sdcc, an int, not a short,
//is 2 bytes. //is 2 bytes.
typedef unsigned int ushort; typedef unsigned int ushort;
#endif #endif
#endif #endif
// general defines // general defines
...@@ -123,7 +123,7 @@ ...@@ -123,7 +123,7 @@
#define TRUE 1 #define TRUE 1
#ifndef MAX_PORTNUM #ifndef MAX_PORTNUM
#define MAX_PORTNUM 1 #define MAX_PORTNUM 1
#endif #endif
// mode bit flags // mode bit flags
...@@ -152,24 +152,24 @@ extern int owHasErrors(void); ...@@ -152,24 +152,24 @@ extern int owHasErrors(void);
#ifdef DEBUG #ifdef DEBUG
//Raises an exception with extra debug info //Raises an exception with extra debug info
#define OWERROR(err) owRaiseError(err,__LINE__,__FILE__) #define OWERROR(err) owRaiseError(err,__LINE__,__FILE__)
extern void owRaiseError(int,int,char*); extern void owRaiseError(int, int, char *);
#define OWASSERT(s,err,ret) if(!(s)){owRaiseError((err),__LINE__,__FILE__);return (ret);} #define OWASSERT(s,err,ret) if(!(s)){owRaiseError((err),__LINE__,__FILE__);return (ret);}
#else #else
//Raises an exception with just the error code //Raises an exception with just the error code
#define OWERROR(err) owRaiseError(err) #define OWERROR(err) owRaiseError(err)
extern void owRaiseError(int); extern void owRaiseError(int);
#define OWASSERT(s,err,ret) if(!(s)){owRaiseError((err));return (ret);} #define OWASSERT(s,err,ret) if(!(s)){owRaiseError((err));return (ret);}
#endif #endif
#ifdef SOCKIT_OWM_ERR_SMALL #ifdef SOCKIT_OWM_ERR_SMALL
#define OWERROR_DUMP(fileno) /*no-op*/; #define OWERROR_DUMP(fileno) /*no-op*/;
#else #else
//Prints the stack out to the given file. //Prints the stack out to the given file.
#define OWERROR_DUMP(fileno) while(owHasErrors()) owPrintErrorMsg(fileno); #define OWERROR_DUMP(fileno) while(owHasErrors()) owPrintErrorMsg(fileno);
extern void owPrintErrorMsg(FILE *); extern void owPrintErrorMsg(FILE *);
extern void owPrintErrorMsgStd(); extern void owPrintErrorMsgStd();
extern char *owGetErrorMsg(int); extern char *owGetErrorMsg(int);
#endif #endif
#else #else
...@@ -309,18 +309,17 @@ extern int owHasErrors(void); ...@@ -309,18 +309,17 @@ extern int owHasErrors(void);
// One Wire functions defined in ownetu.c // One Wire functions defined in ownetu.c
SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only); SMALLINT owFirst(int portnum, SMALLINT do_reset, SMALLINT alarm_only);
SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only); SMALLINT owNext(int portnum, SMALLINT do_reset, SMALLINT alarm_only);
void owSerialNum(int portnum, uchar *serialnum_buf, SMALLINT do_read); void owSerialNum(int portnum, uchar * serialnum_buf, SMALLINT do_read);
void owFamilySearchSetup(int portnum, SMALLINT search_family); void owFamilySearchSetup(int portnum, SMALLINT search_family);
void owSkipFamily(int portnum); void owSkipFamily(int portnum);
SMALLINT owAccess(int portnum); SMALLINT owAccess(int portnum);
SMALLINT owVerify(int portnum, SMALLINT alarm_only); SMALLINT owVerify(int portnum, SMALLINT alarm_only);
SMALLINT owOverdriveAccess(int portnum); SMALLINT owOverdriveAccess(int portnum);
// external One Wire functions defined in owsesu.c // external One Wire functions defined in owsesu.c
SMALLINT owAcquire(int portnum, char *port_zstr); SMALLINT owAcquire(int portnum, char *port_zstr);
int owAcquireEx(char *port_zstr); int owAcquireEx(char *port_zstr);
void owRelease(int portnum); void owRelease(int portnum);
// external One Wire functions defined in findtype.c // external One Wire functions defined in findtype.c
// SMALLINT FindDevices(int,uchar FamilySN[][8],SMALLINT,int); // SMALLINT FindDevices(int,uchar FamilySN[][8],SMALLINT,int);
...@@ -344,12 +343,16 @@ SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse); ...@@ -344,12 +343,16 @@ SMALLINT owReadBitPower(int portnum, SMALLINT applyPowerResponse);
extern SMALLINT FAMILY_CODE_04_ALARM_TOUCHRESET_COMPLIANCE; extern SMALLINT FAMILY_CODE_04_ALARM_TOUCHRESET_COMPLIANCE;
// external One Wire functions from transaction layer in owtrnu.c // external One Wire functions from transaction layer in owtrnu.c
SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar *tran_buf, SMALLINT tran_len); SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar * tran_buf,
SMALLINT owReadPacketStd(int portnum, SMALLINT do_access, int start_page, uchar *read_buf); SMALLINT tran_len);
SMALLINT owWritePacketStd(int portnum, int start_page, uchar *write_buf, SMALLINT owReadPacketStd(int portnum, SMALLINT do_access, int start_page,
SMALLINT write_len, SMALLINT is_eprom, SMALLINT crc_type); uchar * read_buf);
SMALLINT owProgramByte(int portnum, SMALLINT write_byte, int addr, SMALLINT write_cmd, SMALLINT owWritePacketStd(int portnum, int start_page, uchar * write_buf,
SMALLINT crc_type, SMALLINT do_access); SMALLINT write_len, SMALLINT is_eprom,
SMALLINT crc_type);
SMALLINT owProgramByte(int portnum, SMALLINT write_byte, int addr,
SMALLINT write_cmd, SMALLINT crc_type,
SMALLINT do_access);
// link functions // link functions
void msDelay(int len); void msDelay(int len);
...@@ -358,15 +361,15 @@ long msGettick(void); ...@@ -358,15 +361,15 @@ long msGettick(void);
// ioutil.c functions prototypes // ioutil.c functions prototypes
int EnterString(char *msg, char *buf, int min, int max); int EnterString(char *msg, char *buf, int min, int max);
int EnterNum(char *msg, int numchars, long *value, long min, long max); int EnterNum(char *msg, int numchars, long *value, long min, long max);
int EnterHex(char *msg, int numchars, ulong *value); int EnterHex(char *msg, int numchars, ulong * value);
int ToHex(char ch); int ToHex(char ch);
int getkeystroke(void); int getkeystroke(void);
int key_abort(void); int key_abort(void);
void ExitProg(char *msg, int exit_code); void ExitProg(char *msg, int exit_code);
int getData(uchar *write_buff, int max_len, SMALLINT gethex); int getData(uchar * write_buff, int max_len, SMALLINT gethex);
void PrintHex(uchar* buffer, int cnt); void PrintHex(uchar * buffer, int cnt);
void PrintChars(uchar* buffer, int cnt); void PrintChars(uchar * buffer, int cnt);
void PrintSerialNum(uchar* buffer); void PrintSerialNum(uchar * buffer);
// external functions defined in crcutil.c // external functions defined in crcutil.c
void setcrc16(int portnum, ushort reset); void setcrc16(int portnum, ushort reset);
......
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
extern sockit_owm_state sockit_owm; extern sockit_owm_state sockit_owm;
// local function prototypes // local function prototypes
SMALLINT owAcquire(int,char *); SMALLINT owAcquire(int, char *);
void owRelease(int); void owRelease(int);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
...@@ -55,20 +55,20 @@ void owRelease(int); ...@@ -55,20 +55,20 @@ void owRelease(int);
// //
SMALLINT owAcquire(int portnum, char *port_zstr) SMALLINT owAcquire(int portnum, char *port_zstr)
{ {
// check if there are enough ports available // check if there are enough ports available
if (sockit_owm.own <= portnum) { if (sockit_owm.own <= portnum) {
// TODO some error message might be added // TODO some error message might be added
return FALSE; return FALSE;
} }
// check if port is already in use // check if port is already in use
if ((sockit_owm.use >> portnum) & 0x1) { if ((sockit_owm.use >> portnum) & 0x1) {
return FALSE; return FALSE;
} }
// if it is unused take it // if it is unused take it
else { else {
sockit_owm.use |= (0x1 << portnum); sockit_owm.use |= (0x1 << portnum);
return TRUE; return TRUE;
} }
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
...@@ -79,12 +79,12 @@ SMALLINT owAcquire(int portnum, char *port_zstr) ...@@ -79,12 +79,12 @@ SMALLINT owAcquire(int portnum, char *port_zstr)
// //
void owRelease(int portnum) void owRelease(int portnum)
{ {
// check if port is already in use and release it // check if port is already in use and release it
if ((sockit_owm.use >> portnum) & 0x1) { if ((sockit_owm.use >> portnum) & 0x1) {
sockit_owm.use &= ~(0x1 << portnum); sockit_owm.use &= ~(0x1 << portnum);
} }
// releasing an unused port is not supported // releasing an unused port is not supported
else { else {
// TODO some error message might be added // TODO some error message might be added
} }
} }
...@@ -56,32 +56,28 @@ ...@@ -56,32 +56,28 @@
// //
// The maximum tran_len is 160 // The maximum tran_len is 160
// //
SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar *tran_buf, SMALLINT tran_len) SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar * tran_buf,
SMALLINT tran_len)
{ {
uchar i; uchar i;
// check for a block too big // check for a block too big
if (tran_len > 160) if (tran_len > 160) {
{ OWERROR(OWERROR_BLOCK_TOO_BIG);
OWERROR(OWERROR_BLOCK_TOO_BIG); return FALSE;
return FALSE; }
} // check if need to do a owTouchReset first
if (do_reset) {
if (!owTouchReset(portnum)) {
OWERROR(OWERROR_NO_DEVICES_ON_NET);
return FALSE;
}
}
// send and receive the buffer
for (i = 0; i < tran_len; i++)
tran_buf[i] = (uchar) owTouchByte(portnum, tran_buf[i]);
// check if need to do a owTouchReset first return TRUE;
if (do_reset)
{
if (!owTouchReset(portnum))
{
OWERROR(OWERROR_NO_DEVICES_ON_NET);
return FALSE;
}
}
// send and receive the buffer
for (i = 0; i < tran_len; i++)
tran_buf[i] = (uchar)owTouchByte(portnum,tran_buf[i]);
return TRUE;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -108,95 +104,78 @@ SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar *tran_buf, SMALLINT tran_ ...@@ -108,95 +104,78 @@ SMALLINT owBlock(int portnum, SMALLINT do_reset, uchar *tran_buf, SMALLINT tran_
// -1 error, device not connected or program pulse voltage // -1 error, device not connected or program pulse voltage
// not available // not available
// //
SMALLINT owProgramByte(int portnum, SMALLINT write_byte, int addr, SMALLINT write_cmd, SMALLINT owProgramByte(int portnum, SMALLINT write_byte, int addr,
SMALLINT crc_type, SMALLINT do_access) SMALLINT write_cmd, SMALLINT crc_type,
SMALLINT do_access)
{ {
ushort lastcrc16; ushort lastcrc16;
uchar lastcrc8; uchar lastcrc8;
// optionally access the device
if (do_access)
{
if (!owAccess(portnum))
{
OWERROR(OWERROR_ACCESS_FAILED);
return -1;
}
// send the write command
if (!owWriteByte(portnum,write_cmd))
{
OWERROR(OWERROR_WRITE_BYTE_FAILED);
return -1;
}
// send the address
if (!owWriteByte(portnum,addr & 0xFF) || !owWriteByte(portnum,addr >> 8))
{
OWERROR(OWERROR_WRITE_BYTE_FAILED);
return -1;
}
}
// send the data to write
if (!owWriteByte(portnum,write_byte))
{
OWERROR(OWERROR_WRITE_BYTE_FAILED);
return -1;
}
// read the CRC
if (crc_type == 0)
{
// calculate CRC8
if (do_access)
{
setcrc8(portnum,0);
docrc8(portnum,(uchar)write_cmd);
docrc8(portnum,(uchar)(addr & 0xFF));
docrc8(portnum,(uchar)(addr >> 8));
}
else
setcrc8(portnum,(uchar)(addr & 0xFF));
docrc8(portnum,(uchar)write_byte); // optionally access the device
// read and calculate the read crc if (do_access) {
lastcrc8 = docrc8(portnum,(uchar)owReadByte(portnum)); if (!owAccess(portnum)) {
// crc should now be 0x00 OWERROR(OWERROR_ACCESS_FAILED);
if (lastcrc8 != 0) return -1;
{ }
OWERROR(OWERROR_CRC_FAILED); // send the write command
return -1; if (!owWriteByte(portnum, write_cmd)) {
} OWERROR(OWERROR_WRITE_BYTE_FAILED);
} return -1;
else }
{ // send the address
// CRC16 if (!owWriteByte(portnum, addr & 0xFF)
if (do_access) || !owWriteByte(portnum, addr >> 8)) {
{ OWERROR(OWERROR_WRITE_BYTE_FAILED);
setcrc16(portnum,0); return -1;
docrc16(portnum,(ushort)write_cmd); }
docrc16(portnum,(ushort)(addr & 0xFF)); }
docrc16(portnum,(ushort)(addr >> 8)); // send the data to write
} if (!owWriteByte(portnum, write_byte)) {
else OWERROR(OWERROR_WRITE_BYTE_FAILED);
setcrc16(portnum,(ushort)addr); return -1;
docrc16(portnum,(ushort)write_byte); }
// read and calculate the read crc // read the CRC
docrc16(portnum,(ushort)owReadByte(portnum)); if (crc_type == 0) {
lastcrc16 = docrc16(portnum,(ushort)owReadByte(portnum)); // calculate CRC8
// crc should now be 0xB001 if (do_access) {
if (lastcrc16 != 0xB001) setcrc8(portnum, 0);
return -1; docrc8(portnum, (uchar) write_cmd);
} docrc8(portnum, (uchar) (addr & 0xFF));
docrc8(portnum, (uchar) (addr >> 8));
} else
setcrc8(portnum, (uchar) (addr & 0xFF));
// send the program pulse docrc8(portnum, (uchar) write_byte);
if (!owProgramPulse(portnum)) // read and calculate the read crc
{ lastcrc8 = docrc8(portnum, (uchar) owReadByte(portnum));
OWERROR(OWERROR_PROGRAM_PULSE_FAILED); // crc should now be 0x00
return -1; if (lastcrc8 != 0) {
} OWERROR(OWERROR_CRC_FAILED);
return -1;
}
} else {
// CRC16
if (do_access) {
setcrc16(portnum, 0);
docrc16(portnum, (ushort) write_cmd);
docrc16(portnum, (ushort) (addr & 0xFF));
docrc16(portnum, (ushort) (addr >> 8));
} else
setcrc16(portnum, (ushort) addr);
docrc16(portnum, (ushort) write_byte);
// read and calculate the read crc
docrc16(portnum, (ushort) owReadByte(portnum));
lastcrc16 = docrc16(portnum, (ushort) owReadByte(portnum));
// crc should now be 0xB001
if (lastcrc16 != 0xB001)
return -1;
}
// read back and return the resulting byte // send the program pulse
return owReadByte(portnum); if (!owProgramPulse(portnum)) {
OWERROR(OWERROR_PROGRAM_PULSE_FAILED);
return -1;
}
// read back and return the resulting byte
return owReadByte(portnum);
} }
...@@ -45,93 +45,94 @@ ...@@ -45,93 +45,94 @@
// FALSE(0) could not read the temperature, perhaps device is not // FALSE(0) could not read the temperature, perhaps device is not
// in contact // in contact
// //
int ReadTemperature10(int portnum, uchar *SerialNum, float *Temp) int ReadTemperature10(int portnum, uchar * SerialNum, float *Temp)
{ {
uchar rt=FALSE; uchar rt = FALSE;
uchar send_block[30],lastcrc8 = 0; uchar send_block[30], lastcrc8 = 0;
int send_cnt, tsht, i, loop=0; int send_cnt, tsht, i, loop = 0;
float tmp,cr,cpc; float tmp, cr, cpc;
int power = 0; int power = 0;
// set the device serial number to the counter device // set the device serial number to the counter device
owSerialNum(portnum,SerialNum,FALSE); owSerialNum(portnum, SerialNum, FALSE);
for (loop = 0; loop < 2; loop ++) for (loop = 0; loop < 2; loop++) {
{ // check if the chip is connected to VDD
// check if the chip is connected to VDD if (owAccess(portnum)) {
if (owAccess(portnum)) owWriteByte(portnum, 0xB4);
{ power = owReadByte(portnum);
owWriteByte(portnum,0xB4); }
power = owReadByte(portnum); // access the device
} if (owAccess(portnum)) {
// access the device // send the convert command and if nesessary start power delivery
if (owAccess(portnum)) if (power) {
{ if (!owWriteBytePower(portnum, 0x44))
// send the convert command and if nesessary start power delivery return FALSE;
if (power) { } else {
if (!owWriteBytePower(portnum,0x44)) if (!owWriteByte(portnum, 0x44))
return FALSE; return FALSE;
} else { }
if (!owWriteByte(portnum,0x44))
return FALSE;
}
// sleep for 1 second // sleep for 1 second
msDelay(1000); msDelay(1000);
// turn off the 1-Wire Net strong pull-up // turn off the 1-Wire Net strong pull-up
if (power) { if (power) {
if (owLevel(portnum,MODE_NORMAL) != MODE_NORMAL) if (owLevel(portnum, MODE_NORMAL) !=
return FALSE; MODE_NORMAL)
} return FALSE;
}
// access the device
if (owAccess(portnum)) {
// create a block to send that reads the temperature
// read scratchpad command
send_cnt = 0;
send_block[send_cnt++] = 0xBE;
// now add the read bytes for data bytes and crc8
for (i = 0; i < 9; i++)
send_block[send_cnt++] = 0xFF;
// access the device // now send the block
if (owAccess(portnum)) if (owBlock
{ (portnum, FALSE, send_block, send_cnt)) {
// create a block to send that reads the temperature // initialize the CRC8
// read scratchpad command setcrc8(portnum, 0);
send_cnt = 0; // perform the CRC8 on the last 8 bytes of packet
send_block[send_cnt++] = 0xBE; for (i = send_cnt - 9; i < send_cnt;
// now add the read bytes for data bytes and crc8 i++)
for (i = 0; i < 9; i++) lastcrc8 =
send_block[send_cnt++] = 0xFF; docrc8(portnum,
send_block[i]);
// now send the block // verify CRC8 is correct
if (owBlock(portnum,FALSE,send_block,send_cnt)) if (lastcrc8 == 0x00) {
{ // calculate the high-res temperature
// initialize the CRC8 tsht = send_block[1] / 2;
setcrc8(portnum,0); if (send_block[2] & 0x01)
// perform the CRC8 on the last 8 bytes of packet tsht |= -128;
for (i = send_cnt - 9; i < send_cnt; i++) tmp = (float)(tsht);
lastcrc8 = docrc8(portnum,send_block[i]); cr = send_block[7];
cpc = send_block[8];
if (((cpc - cr) == 1)
&& (loop == 0))
continue;
if (cpc == 0)
return FALSE;
else
tmp =
tmp - (float)0.25 +
(cpc - cr) / cpc;
// verify CRC8 is correct *Temp = tmp;
if (lastcrc8 == 0x00) // success
{ rt = TRUE;
// calculate the high-res temperature break;
tsht = send_block[1]/2; }
if (send_block[2] & 0x01) }
tsht |= -128; }
tmp = (float)(tsht); }
cr = send_block[7];
cpc = send_block[8];
if (((cpc - cr) == 1) && (loop == 0))
continue;
if (cpc == 0)
return FALSE;
else
tmp = tmp - (float)0.25 + (cpc - cr)/cpc;
*Temp = tmp; }
// success
rt = TRUE;
break;
}
}
}
}
} // return the result flag rt
return rt;
// return the result flag rt
return rt;
} }
...@@ -28,4 +28,4 @@ ...@@ -28,4 +28,4 @@
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
int ReadTemperature10(int,uchar *,float *); int ReadTemperature10(int, uchar *, float *);
...@@ -45,91 +45,88 @@ ...@@ -45,91 +45,88 @@
// FALSE(0) could not read the temperature, perhaps device is not // FALSE(0) could not read the temperature, perhaps device is not
// in contact // in contact
// //
uint8_t ReadTemperature28(uint8_t portnum, uint8_t *SerialNum, int16_t *Temp) uint8_t ReadTemperature28(uint8_t portnum, uint8_t * SerialNum, int16_t * Temp)
{ {
uint8_t rt=FALSE; uint8_t rt = FALSE;
uint8_t send_block[30],lastcrc8 = 0; uint8_t send_block[30], lastcrc8 = 0;
int send_cnt, tsht, i; int send_cnt, tsht, i;
static int power = -1; static int power = -1;
static uint8_t toggle = 0; static uint8_t toggle = 0;
// set the device serial number to the counter device // set the device serial number to the counter device
owSerialNum(portnum,SerialNum,FALSE); owSerialNum(portnum, SerialNum, FALSE);
//we need to call this only once at the beginning //we need to call this only once at the beginning
if(power==-1) if (power == -1) {
{ // check if the chip is connected to VDD
// check if the chip is connected to VDD if (owAccess(portnum)) {
if (owAccess(portnum)) owWriteByte(portnum, 0xB4);
{ power = owReadByte(portnum);
owWriteByte(portnum,0xB4); }
power = owReadByte(portnum); }
}
}
if(toggle) if (toggle) {
{ if (owAccess(portnum)) {
if( owAccess(portnum)) // turn off the 1-Wire Net strong pull-up
{ if (power) {
// turn off the 1-Wire Net strong pull-up if (owLevel(portnum, MODE_NORMAL) !=
if (power) { MODE_NORMAL)
if (owLevel(portnum,MODE_NORMAL) != MODE_NORMAL) return FALSE;
return FALSE; }
}
while(!owReadByte(portnum)){} //wait until conversion is done while (!owReadByte(portnum)) {
// access the device } //wait until conversion is done
if (owAccess(portnum)) // access the device
{ if (owAccess(portnum)) {
// create a block to send that reads the temperature // create a block to send that reads the temperature
// read scratchpad command // read scratchpad command
send_cnt = 0; send_cnt = 0;
send_block[send_cnt++] = 0xBE; send_block[send_cnt++] = 0xBE;
// now add the read bytes for data bytes and crc8 // now add the read bytes for data bytes and crc8
for (i = 0; i < 9; i++) for (i = 0; i < 9; i++)
send_block[send_cnt++] = 0xFF; send_block[send_cnt++] = 0xFF;
// now send the block // now send the block
if (owBlock(portnum,FALSE,send_block,send_cnt)) if (owBlock
{ (portnum, FALSE, send_block, send_cnt)) {
// initialize the CRC8 // initialize the CRC8
setcrc8(portnum,0); setcrc8(portnum, 0);
// perform the CRC8 on the last 8 bytes of packet // perform the CRC8 on the last 8 bytes of packet
for (i = send_cnt - 9; i < send_cnt; i++) for (i = send_cnt - 9; i < send_cnt;
lastcrc8 = docrc8(portnum,send_block[i]); i++)
lastcrc8 =
docrc8(portnum,
send_block[i]);
// verify CRC8 is correct // verify CRC8 is correct
if (lastcrc8 == 0x00) if (lastcrc8 == 0x00) {
{ // calculate the high-res temperature
// calculate the high-res temperature tsht = send_block[2] << 8;
tsht = send_block[2] << 8; tsht = tsht | send_block[1];
tsht = tsht | send_block[1]; if (tsht & 0x00001000)
if (tsht & 0x00001000) tsht =
tsht = tsht | 0xffff0000; tsht | 0xffff0000;
*Temp = (int16_t) tsht; *Temp = (int16_t) tsht;
// success // success
rt = TRUE; rt = TRUE;
//break; //break;
} }
} }
} }
} }
} }
// access the device
// access the device if (owAccess(portnum)) {
if (owAccess(portnum)) // send the convert command and if nesessary start power delivery
{ if (power) {
// send the convert command and if nesessary start power delivery if (!owWriteBytePower(portnum, 0x44))
if (power) { return FALSE;
if (!owWriteBytePower(portnum,0x44)) } else {
return FALSE; if (!owWriteByte(portnum, 0x44))
} else { return FALSE;
if (!owWriteByte(portnum,0x44)) }
return FALSE; toggle = 1;
} }
toggle=1; // return the result flag rt
} return rt;
// return the result flag rt
return rt;
} }
...@@ -28,4 +28,4 @@ ...@@ -28,4 +28,4 @@
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
uint8_t ReadTemperature28(uint8_t , uint8_t *,int16_t *); uint8_t ReadTemperature28(uint8_t, uint8_t *, int16_t *);
...@@ -45,92 +45,89 @@ ...@@ -45,92 +45,89 @@
// FALSE(0) could not read the temperature, perhaps device is not // FALSE(0) could not read the temperature, perhaps device is not
// in contact // in contact
// //
int ReadTemperature42(int portnum, uchar *SerialNum, int *Temp, int *frac ) int ReadTemperature42(int portnum, uchar * SerialNum, int *Temp, int *frac)
{ {
uchar rt=FALSE; uchar rt = FALSE;
uchar send_block[30],lastcrc8=0; uchar send_block[30], lastcrc8 = 0;
int send_cnt, i, loop=0; int send_cnt, i, loop = 0;
int power=0; int power = 0;
int val_int=0; int val_int = 0;
int is_neg=FALSE; int is_neg = FALSE;
// set the device serial number to the counter device // set the device serial number to the counter device
owSerialNum(portnum,SerialNum,FALSE); owSerialNum(portnum, SerialNum, FALSE);
for (loop = 0; loop < 2; loop ++) for (loop = 0; loop < 2; loop++) {
{ // check if the chip is connected to VDD
// check if the chip is connected to VDD if (owOverdriveAccess(portnum)) {
if (owOverdriveAccess(portnum)) owWriteByte(portnum, 0xB4);
{ power = owReadByte(portnum);
owWriteByte(portnum,0xB4); }
power = owReadByte(portnum); // access the device
} if (owOverdriveAccess(portnum)) {
// send the convert command and if nesessary start power delivery
// access the device // if (power) {
if (owOverdriveAccess(portnum)) // if (!owWriteBytePower(portnum,0x44))
{ // return FALSE;
// send the convert command and if nesessary start power delivery // } else {
// if (power) { if (!owWriteByte(portnum, 0x44))
// if (!owWriteBytePower(portnum,0x44)) return FALSE;
// return FALSE; // }
// } else { // sleep for 1 second
if (!owWriteByte(portnum,0x44)) msDelay(1000);
return FALSE; // turn off the 1-Wire Net strong pull-up
// } if (power) {
// sleep for 1 second if (owLevel(portnum, MODE_NORMAL) !=
msDelay(1000); MODE_NORMAL)
// turn off the 1-Wire Net strong pull-up return FALSE;
if (power) { }
if (owLevel(portnum,MODE_NORMAL) != MODE_NORMAL) // access the device
return FALSE; if (owOverdriveAccess(portnum)) {
} // create a block to send that reads the temperature
// read scratchpad command
send_cnt = 0;
send_block[send_cnt++] = 0xBE;
// now add the read bytes for data bytes and crc8
for (i = 0; i < 9; i++)
send_block[send_cnt++] = 0xFF;
// access the device // now send the block
if (owOverdriveAccess(portnum)) if (owBlock
{ (portnum, FALSE, send_block, send_cnt)) {
// create a block to send that reads the temperature // initialize the CRC8
// read scratchpad command setcrc8(portnum, 0);
send_cnt = 0; // perform the CRC8 on the last 8 bytes of packet
send_block[send_cnt++] = 0xBE; for (i = send_cnt - 9; i < send_cnt;
// now add the read bytes for data bytes and crc8 i++)
for (i = 0; i < 9; i++) lastcrc8 =
send_block[send_cnt++] = 0xFF; docrc8(portnum,
send_block[i]);
// now send the block // verify CRC8 is correct
if (owBlock(portnum,FALSE,send_block,send_cnt)) if (lastcrc8 == 0x00) {
{
// initialize the CRC8
setcrc8(portnum,0);
// perform the CRC8 on the last 8 bytes of packet
for (i = send_cnt - 9; i < send_cnt; i++)
lastcrc8 = docrc8(portnum,send_block[i]);
// verify CRC8 is correct // calculate the high-res temperature
if (lastcrc8 == 0x00) // from twos complement representation
{ val_int = send_block[1]; // low byte
val_int |= send_block[2] << 8; // high byte
if (val_int & 0x00001000) { // check sign for negative
val_int = ~val_int + 1;
is_neg = TRUE;
}
// calculate the high-res temperature *Temp = val_int >> 4; // only integer part
// from twos complement representation *frac = val_int & 0x08; // only 1/2 bit
val_int = send_block[1]; // low byte // success
val_int |= send_block[2] << 8; // high byte rt = TRUE;
if (val_int & 0x00001000) { // check sign for negative break;
val_int = ~val_int + 1; }
is_neg = TRUE; }
}
} }
}
*Temp = val_int >> 4; // only integer part // exit overdrive mode
*frac = val_int & 0x08; // only 1/2 bit owSpeed(portnum, MODE_NORMAL);
// success // return the result flag rt
rt = TRUE; return rt;
break;
}
}
}
}
}
// exit overdrive mode
owSpeed(portnum, MODE_NORMAL);
// return the result flag rt
return rt;
} }
...@@ -28,4 +28,4 @@ ...@@ -28,4 +28,4 @@
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
int ReadTemperature42(int,uchar *,int *,int *); int ReadTemperature42(int, uchar *, int *, int *);
...@@ -23,21 +23,23 @@ static int get_bitslide(int ep) ...@@ -23,21 +23,23 @@ static int get_bitslide(int ep)
} }
struct meas_entry { struct meas_entry {
int delta_ns; int delta_ns;
int phase; int phase;
int phase_sync; int phase_sync;
int ahead; int ahead;
}; };
static void purge_socket(wr_socket_t *sock) static void purge_socket(wr_socket_t * sock)
{ {
wr_sockaddr_t from; wr_sockaddr_t from;
char buf[128]; char buf[128];
update_rx_queues(); update_rx_queues();
while(ptpd_netif_recvfrom(sock, &from, buf, 128, NULL) > 0) update_rx_queues(); while (ptpd_netif_recvfrom(sock, &from, buf, 128, NULL) > 0)
update_rx_queues();
} }
static int meas_phase_range(wr_socket_t *sock, int phase_min, int phase_max, int phase_step, struct meas_entry *results) static int meas_phase_range(wr_socket_t * sock, int phase_min, int phase_max,
int phase_step, struct meas_entry *results)
{ {
char buf[128]; char buf[128];
wr_timestamp_t ts_tx, ts_rx, ts_sync; wr_timestamp_t ts_tx, ts_rx, ts_sync;
...@@ -46,42 +48,43 @@ static int meas_phase_range(wr_socket_t *sock, int phase_min, int phase_max, int ...@@ -46,42 +48,43 @@ static int meas_phase_range(wr_socket_t *sock, int phase_min, int phase_max, int
int setpoint = phase_min, i = 0, phase; int setpoint = phase_min, i = 0, phase;
spll_set_phase_shift(SPLL_ALL_CHANNELS, phase_min); spll_set_phase_shift(SPLL_ALL_CHANNELS, phase_min);
while(spll_shifter_busy(0)); while (spll_shifter_busy(0)) ;
purge_socket(sock); purge_socket(sock);
i=0; i = 0;
while(setpoint <= phase_max) while (setpoint <= phase_max) {
{
ptpd_netif_get_dmtd_phase(sock, &phase); ptpd_netif_get_dmtd_phase(sock, &phase);
update_rx_queues(); update_rx_queues();
int n = ptpd_netif_recvfrom(sock, &from, buf, 128, &ts_rx); int n = ptpd_netif_recvfrom(sock, &from, buf, 128, &ts_rx);
if (n > 0) {
if(n>0)
{
msgUnpackHeader(buf, &mhdr); msgUnpackHeader(buf, &mhdr);
if(mhdr.messageType == 0) if (mhdr.messageType == 0)
ts_sync = ts_rx; ts_sync = ts_rx;
else if(mhdr.messageType == 8) else if (mhdr.messageType == 8) {
{
MsgFollowUp fup; MsgFollowUp fup;
msgUnpackFollowUp(buf, &fup); msgUnpackFollowUp(buf, &fup);
mprintf("Shift: %d/%dps [step %dps] \r", setpoint,phase_max,phase_step); mprintf("Shift: %d/%dps [step %dps] \r",
results[i].phase = phase; setpoint, phase_max, phase_step);
results[i].phase_sync = ts_sync.phase; results[i].phase = phase;
results[i].ahead = ts_sync.raw_ahead; results[i].phase_sync = ts_sync.phase;
results[i].delta_ns = fup.preciseOriginTimestamp.nanosecondsField - ts_sync.nsec; results[i].ahead = ts_sync.raw_ahead;
results[i].delta_ns += (fup.preciseOriginTimestamp.secondsField.lsb - ts_sync.sec) * 1000000000; results[i].delta_ns =
fup.preciseOriginTimestamp.
setpoint += phase_step; nanosecondsField - ts_sync.nsec;
spll_set_phase_shift(0, setpoint); results[i].delta_ns +=
while(spll_shifter_busy(0)); (fup.preciseOriginTimestamp.secondsField.
purge_socket(sock); lsb - ts_sync.sec) * 1000000000;
i++; setpoint += phase_step;
spll_set_phase_shift(0, setpoint);
while (spll_shifter_busy(0)) ;
purge_socket(sock);
i++;
} }
} }
} }
...@@ -92,14 +95,14 @@ static int meas_phase_range(wr_socket_t *sock, int phase_min, int phase_max, int ...@@ -92,14 +95,14 @@ static int meas_phase_range(wr_socket_t *sock, int phase_min, int phase_max, int
static int find_transition(struct meas_entry *results, int n, int positive) static int find_transition(struct meas_entry *results, int n, int positive)
{ {
int i; int i;
for(i=0;i<n;i++) for (i = 0; i < n; i++) {
{ if ((results[i].ahead ^ results[(i + 1) % n].ahead)
if ((results[i].ahead ^ results[(i+1)%n].ahead) && (results[(i+1)%n].ahead == positive)) && (results[(i + 1) % n].ahead == positive))
return i; return i;
} }
} }
extern void ptpd_netif_set_phase_transition(wr_socket_t *sock, int phase); extern void ptpd_netif_set_phase_transition(wr_socket_t * sock, int phase);
int measure_t24p(int *value) int measure_t24p(int *value)
{ {
...@@ -110,7 +113,7 @@ int measure_t24p(int *value) ...@@ -110,7 +113,7 @@ int measure_t24p(int *value)
spll_enable_ptracker(0, 1); spll_enable_ptracker(0, 1);
sock_addr.family = PTPD_SOCK_RAW_ETHERNET; // socket type sock_addr.family = PTPD_SOCK_RAW_ETHERNET; // socket type
sock_addr.ethertype = 0x88f7; sock_addr.ethertype = 0x88f7;
sock_addr.mac[0] = 0x1; sock_addr.mac[0] = 0x1;
sock_addr.mac[1] = 0x1b; sock_addr.mac[1] = 0x1b;
...@@ -120,53 +123,57 @@ int measure_t24p(int *value) ...@@ -120,53 +123,57 @@ int measure_t24p(int *value)
sock_addr.mac[5] = 0; sock_addr.mac[5] = 0;
mprintf("LNK: "); mprintf("LNK: ");
while( !ep_link_up(NULL) ) while (!ep_link_up(NULL)) {
{
mprintf("."); mprintf(".");
timer_delay(1000); timer_delay(1000);
} }
mprintf("\nPLL: "); mprintf("\nPLL: ");
spll_init(SPLL_MODE_SLAVE, 0, 1); spll_init(SPLL_MODE_SLAVE, 0, 1);
while(!spll_check_lock(0)); while (!spll_check_lock(0)) ;
mprintf("\n"); mprintf("\n");
if(ptpd_netif_init() != 0) if (ptpd_netif_init() != 0)
return -1; return -1;
sock = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET, 0, &sock_addr); sock = ptpd_netif_create_socket(PTPD_SOCK_RAW_ETHERNET, 0, &sock_addr);
nr=meas_phase_range(sock, 0, 8000, 1000, results); nr = meas_phase_range(sock, 0, 8000, 1000, results);
int tplus = find_transition(results, nr, 1); int tplus = find_transition(results, nr, 1);
int tminus = find_transition(results, nr, 0); int tminus = find_transition(results, nr, 0);
int approx_plus = results[tplus].phase; int approx_plus = results[tplus].phase;
int approx_minus = results[tminus].phase; int approx_minus = results[tminus].phase;
nr = meas_phase_range(sock, approx_plus - 1000, approx_plus + 1000, 100,
nr=meas_phase_range(sock, approx_plus-1000, approx_plus+1000, 100, results); results);
tplus = find_transition(results, nr, 1); tplus = find_transition(results, nr, 1);
int phase_plus = results[tplus].phase; int phase_plus = results[tplus].phase;
nr=meas_phase_range(sock, approx_minus-1000, approx_minus+1000, 100, results); nr = meas_phase_range(sock, approx_minus - 1000, approx_minus + 1000,
100, results);
tminus = find_transition(results, nr, 0); tminus = find_transition(results, nr, 0);
int phase_minus = results[tminus].phase; int phase_minus = results[tminus].phase;
mprintf("Transitions found: positive @ %d ps, negative @ %d ps.\n", phase_plus, phase_minus); mprintf("Transitions found: positive @ %d ps, negative @ %d ps.\n",
int ttrans = phase_minus-1000; phase_plus, phase_minus);
if(ttrans < 0) ttrans+=8000; int ttrans = phase_minus - 1000;
if (ttrans < 0)
ttrans += 8000;
mprintf("(t2/t4)_phase_transition = %dps\n", ttrans); mprintf("(t2/t4)_phase_transition = %dps\n", ttrans);
ptpd_netif_set_phase_transition(sock, ttrans); ptpd_netif_set_phase_transition(sock, ttrans);
mprintf("Verification... \n"); mprintf("Verification... \n");
nr =meas_phase_range(sock, 0, 16000, 500, results); nr = meas_phase_range(sock, 0, 16000, 500, results);
for(i=0;i<nr;i++) mprintf("phase_dmtd: %d delta_ns: %d, phase_sync: %d\n", results[i].phase, results[i].delta_ns, results[i].phase_sync); for (i = 0; i < nr; i++)
mprintf("phase_dmtd: %d delta_ns: %d, phase_sync: %d\n",
results[i].phase, results[i].delta_ns,
results[i].phase_sync);
if (value)
if(value) *value = ttrans; *value = ttrans;
return 0; return 0;
} }
...@@ -3,24 +3,24 @@ ...@@ -3,24 +3,24 @@
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
if(argc < 3) return -1; if (argc < 3)
FILE *f = fopen(argv[1],"rb"); return -1;
if(!f) return -1; FILE *f = fopen(argv[1], "rb");
unsigned char x[4]; if (!f)
int i=0; return -1;
int n = atoi(argv[2]); unsigned char x[4];
int i = 0;
int n = atoi(argv[2]);
while(!feof(f)) while (!feof(f)) {
{ fread(x, 1, 4, f);
fread(x,1,4,f); printf("write %x %02X%02X%02X%02X\n", i++, x[0], x[1], x[2],
printf("write %x %02X%02X%02X%02X\n", i++, x[0],x[1],x[2],x[3]); x[3]);
} }
for(;i<n;) for (; i < n;) {
{ printf("write %x %02X%02X%02X%02X\n", i++, 0, 0, 0, 0);
printf("write %x %02X%02X%02X%02X\n", i++, 0,0,0,0); }
} fclose(f);
fclose(f); return 0;
return 0;
} }
...@@ -3,228 +3,264 @@ ...@@ -3,228 +3,264 @@
#include <string.h> #include <string.h>
#include <errno.h> #include <errno.h>
#include <math.h> #include <math.h>
#include <unistd.h> /* getopt */ #include <unistd.h> /* getopt */
const char* program; const char *program;
const char* package; const char *package;
const char* filename; const char *filename;
long width; long width;
int bigendian; int bigendian;
int verbose; int verbose;
void help() { void help()
fprintf(stderr, "Usage: %s [OPTION] <filename>\n", program); {
fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s [OPTION] <filename>\n", program);
fprintf(stderr, " -w <width> width of values in bytes [1/2/4/8/16] (4)\n"); fprintf(stderr, "\n");
fprintf(stderr, " -p <package> name of the output package (filename)\n"); fprintf(stderr,
fprintf(stderr, " -s <size> pad the output up to size bytes (filesize)\n"); " -w <width> width of values in bytes [1/2/4/8/16] (4)\n");
fprintf(stderr, " -b big-endian operation (*)\n"); fprintf(stderr,
fprintf(stderr, " -l little-endian operation \n"); " -p <package> name of the output package (filename)\n");
fprintf(stderr, " -v verbose operation\n"); fprintf(stderr,
fprintf(stderr, " -h display this help and exit\n"); " -s <size> pad the output up to size bytes (filesize)\n");
fprintf(stderr, "\n"); fprintf(stderr,
fprintf(stderr, "Report Etherbone bugs to <white-rabbit-dev@ohwr.org>\n"); " -b big-endian operation (*)\n");
fprintf(stderr,
" -l little-endian operation \n");
fprintf(stderr, " -v verbose operation\n");
fprintf(stderr, " -h display this help and exit\n");
fprintf(stderr, "\n");
fprintf(stderr,
"Report Etherbone bugs to <white-rabbit-dev@ohwr.org>\n");
} }
/* We don't want localized versions from ctype.h */ /* We don't want localized versions from ctype.h */
inline int my_isalpha(char c) { inline int my_isalpha(char c)
return (c >= 'a' && c <= 'z') || {
(c >= 'A' && c <= 'Z'); return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
} }
inline int my_isok(char c) {
return c == '_' || my_isalpha(c) || inline int my_isok(char c)
(c >= '0' && c <= '9'); {
return c == '_' || my_isalpha(c) || (c >= '0' && c <= '9');
} }
int main(int argc, char **argv) { int main(int argc, char **argv)
int j, opt, error, i_width; {
long i, elements, size, columns, entry_width; int j, opt, error, i_width;
char* value_end; long i, elements, size, columns, entry_width;
unsigned char x[16]; /* Up to 128 bit */ char *value_end;
char buf[100]; unsigned char x[16]; /* Up to 128 bit */
FILE* f; char buf[100];
FILE *f;
/* Default values */
program = argv[0]; /* Default values */
package = 0; /* auto-detect */ program = argv[0];
width = 4; package = 0; /* auto-detect */
bigendian = 1; width = 4;
verbose = 0; bigendian = 1;
size = -1; /* file size */ verbose = 0;
size = -1; /* file size */
/* Process the command-line */
while ((opt = getopt(argc, argv, "w:p:s:blvh")) != -1) { /* Process the command-line */
switch (opt) { while ((opt = getopt(argc, argv, "w:p:s:blvh")) != -1) {
case 'w': switch (opt) {
width = strtol(optarg, &value_end, 0); case 'w':
if (*value_end || /* bad integer */ width = strtol(optarg, &value_end, 0);
((width-1)&width) != 0 || /* not a power of 2 */ if (*value_end || /* bad integer */
width == 0 || ((width - 1) & width) != 0 || /* not a power of 2 */
width > 16) { width == 0 || width > 16) {
fprintf(stderr, "%s: invalid value width -- '%s'\n", program, optarg); fprintf(stderr,
error = 1; "%s: invalid value width -- '%s'\n",
} program, optarg);
break; error = 1;
case 'p': }
package = optarg; break;
break; case 'p':
case 's': package = optarg;
size = strtol(optarg, &value_end, 0); break;
if (*value_end) { case 's':
fprintf(stderr, "%s: invalid value size -- '%s'\n", program, optarg); size = strtol(optarg, &value_end, 0);
error = 1; if (*value_end) {
} fprintf(stderr,
break; "%s: invalid value size -- '%s'\n",
case 'b': program, optarg);
bigendian = 1; error = 1;
break; }
case 'l': break;
bigendian = 0; case 'b':
break; bigendian = 1;
case 'v': break;
verbose = 1; case 'l':
break; bigendian = 0;
case 'h': break;
help(); case 'v':
return 1; verbose = 1;
case ':': break;
case '?': case 'h':
error = 1; help();
break; return 1;
default: case ':':
fprintf(stderr, "%s: bad getopt result\n", program); case '?':
return 1; error = 1;
} break;
} default:
fprintf(stderr, "%s: bad getopt result\n", program);
if (optind + 1 != argc) { return 1;
fprintf(stderr, "%s: expecting one non-optional argument: <filename>\n", program); }
return 1; }
}
if (optind + 1 != argc) {
filename = argv[optind]; fprintf(stderr,
"%s: expecting one non-optional argument: <filename>\n",
/* Confirm the filename exists */ program);
if ((f = fopen(filename, "r")) == 0) { return 1;
fprintf(stderr, "%s: %s while opening '%s'\n", program, strerror(errno), filename); }
return 1;
} filename = argv[optind];
/* Deduce if it's aligned */ /* Confirm the filename exists */
fseek(f, 0, SEEK_END); if ((f = fopen(filename, "r")) == 0) {
elements = ftell(f); fprintf(stderr, "%s: %s while opening '%s'\n", program,
rewind(f); strerror(errno), filename);
return 1;
if (size == -1) { }
size = elements;
} /* Deduce if it's aligned */
fseek(f, 0, SEEK_END);
if (size < elements) { elements = ftell(f);
fprintf(stderr, "%s: length of initialization file '%s' (%ld) exceeds specified size (%ld)\n", program, filename, elements, size); rewind(f);
return 1;
} if (size == -1) {
size = elements;
if (elements % width != 0) { }
fprintf(stderr, "%s: initialization file '%s' is not a multiple of %ld bytes\n", program, filename, width);
return 1; if (size < elements) {
} fprintf(stderr,
elements /= width; "%s: length of initialization file '%s' (%ld) exceeds specified size (%ld)\n",
program, filename, elements, size);
if (size % width != 0) { return 1;
fprintf(stderr, "%s: specified size '%ld' is not a multiple of %ld bytes\n", program, size, width); }
return 1;
} if (elements % width != 0) {
size /= width; fprintf(stderr,
"%s: initialization file '%s' is not a multiple of %ld bytes\n",
/* Find a suitable package name */ program, filename, width);
if (package == 0) { return 1;
if (strlen(filename) >= sizeof(buf)-5) { }
fprintf(stderr, "%s: filename too long to deduce package name -- '%s'\n", program, filename); elements /= width;
return 1;
} if (size % width != 0) {
fprintf(stderr,
/* Find the first alpha character */ "%s: specified size '%ld' is not a multiple of %ld bytes\n",
while (*filename && !my_isalpha(*filename)) ++filename; program, size, width);
return 1;
/* Start copying the filename to the package */ }
for (i = 0; filename[i]; ++i) { size /= width;
if (my_isok(filename[i]))
buf[i] = filename[i]; /* Find a suitable package name */
else if (package == 0) {
buf[i] = '_'; if (strlen(filename) >= sizeof(buf) - 5) {
} fprintf(stderr,
buf[i] = 0; "%s: filename too long to deduce package name -- '%s'\n",
program, filename);
if (i == 0) { return 1;
fprintf(stderr, "%s: no appropriate characters in filename to use for package name -- '%s'\n", program, filename); }
return 1;
} /* Find the first alpha character */
while (*filename && !my_isalpha(*filename))
package = &buf[0]; ++filename;
} else {
/* Check for valid VHDL identifier */ /* Start copying the filename to the package */
if (!my_isalpha(package[0])) { for (i = 0; filename[i]; ++i) {
fprintf(stderr, "%s: invalid package name -- '%s'\n", program, package); if (my_isok(filename[i]))
return 1; buf[i] = filename[i];
} else
for (i = 1; package[i]; ++i) { buf[i] = '_';
if (!my_isok(package[i])) { }
fprintf(stderr, "%s: invalid package name -- '%s'\n", program, package); buf[i] = 0;
return 1;
} if (i == 0) {
} fprintf(stderr,
} "%s: no appropriate characters in filename to use for package name -- '%s'\n",
program, filename);
/* Find how many digits it takes to fit 'size' */ return 1;
i_width = 1; }
for (i = 10; i <= size; i *= 10)
++i_width; package = &buf[0];
} else {
/* How wide is an entry of the table? */ /* Check for valid VHDL identifier */
entry_width = i_width + 6 + width*2 + 3; if (!my_isalpha(package[0])) {
columns = 76 / entry_width; fprintf(stderr, "%s: invalid package name -- '%s'\n",
program, package);
printf("-- AUTOGENERATED FILE (from genramvhd.c run on %s) --\n", argv[1]); return 1;
printf("library IEEE;\n"); }
printf("use IEEE.std_logic_1164.all;\n"); for (i = 1; package[i]; ++i) {
printf("use IEEE.numeric_std.all;\n"); if (!my_isok(package[i])) {
printf("\n"); fprintf(stderr,
printf("library work;\n"); "%s: invalid package name -- '%s'\n",
printf("use work.memory_loader_pkg.all;\n"); program, package);
printf("\n"); return 1;
}
printf("package %s_pkg is\n", package); }
printf(" constant %s_init : t_meminit_array(%ld downto 0, %ld downto 0) := (\n", package, size-1, (width*8)-1); }
for (i = 0; i < size; ++i) { /* Find how many digits it takes to fit 'size' */
if (i % columns == 0) printf(" "); i_width = 1;
for (i = 10; i <= size; i *= 10)
if (i < elements) { ++i_width;
if (fread(x, 1, width, f) != width) {
perror("fread"); /* How wide is an entry of the table? */
return 1; entry_width = i_width + 6 + width * 2 + 3;
} columns = 76 / entry_width;
} else {
memset(x, 0, sizeof(x)); printf("-- AUTOGENERATED FILE (from genramvhd.c run on %s) --\n",
} argv[1]);
printf("library IEEE;\n");
printf("%*ld => x\"", i_width, i); printf("use IEEE.std_logic_1164.all;\n");
if (bigendian) { printf("use IEEE.numeric_std.all;\n");
for (j = 0; j < width; ++j) printf("\n");
printf("%02x", x[j]); printf("library work;\n");
} else { printf("use work.memory_loader_pkg.all;\n");
for (j = width-1; j >= 0; --j) printf("\n");
printf("%02x", x[j]);
} printf("package %s_pkg is\n", package);
printf("\""); printf
(" constant %s_init : t_meminit_array(%ld downto 0, %ld downto 0) := (\n",
if ((i+1) == size) printf(");\n"); package, size - 1, (width * 8) - 1);
else if ((i+1) % columns == 0) printf(",\n");
else printf(", "); for (i = 0; i < size; ++i) {
} if (i % columns == 0)
fclose(f); printf(" ");
printf("end %s_pkg;\n", package); if (i < elements) {
if (fread(x, 1, width, f) != width) {
return 0; perror("fread");
return 1;
}
} else {
memset(x, 0, sizeof(x));
}
printf("%*ld => x\"", i_width, i);
if (bigendian) {
for (j = 0; j < width; ++j)
printf("%02x", x[j]);
} else {
for (j = width - 1; j >= 0; --j)
printf("%02x", x[j]);
}
printf("\"");
if ((i + 1) == size)
printf(");\n");
else if ((i + 1) % columns == 0)
printf(",\n");
else
printf(", ");
}
fclose(f);
printf("end %s_pkg;\n", package);
return 0;
} }
...@@ -23,52 +23,54 @@ int wrc_ui_mode = UI_SHELL_MODE; ...@@ -23,52 +23,54 @@ int wrc_ui_mode = UI_SHELL_MODE;
/////////////////////////////////// ///////////////////////////////////
//Calibration data (from EEPROM if available) //Calibration data (from EEPROM if available)
int32_t sfp_alpha = -73622176; //default values if could not read EEPROM int32_t sfp_alpha = -73622176; //default values if could not read EEPROM
int32_t sfp_deltaTx = 46407; int32_t sfp_deltaTx = 46407;
int32_t sfp_deltaRx = 167843; int32_t sfp_deltaRx = 167843;
uint32_t cal_phase_transition = 2389; uint32_t cal_phase_transition = 2389;
void wrc_initialize() void wrc_initialize()
{ {
int ret, i; int ret, i;
uint8_t mac_addr[6], ds18_id[8] = {0,0,0,0,0,0,0,0}; uint8_t mac_addr[6], ds18_id[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
char sfp_pn[17]; char sfp_pn[17];
sdb_find_devices(); sdb_find_devices();
uart_init(); uart_init();
mprintf("WR Core: starting up...\n"); mprintf("WR Core: starting up...\n");
timer_init(1); timer_init(1);
owInit(); owInit();
mac_addr[0] = 0x08; // mac_addr[0] = 0x08; //
mac_addr[1] = 0x00; // CERN OUI mac_addr[1] = 0x00; // CERN OUI
mac_addr[2] = 0x30; // mac_addr[2] = 0x30; //
own_scanbus(ONEWIRE_PORT); own_scanbus(ONEWIRE_PORT);
if (get_persistent_mac(ONEWIRE_PORT, mac_addr) == -1) { if (get_persistent_mac(ONEWIRE_PORT, mac_addr) == -1) {
mprintf("Unable to determine MAC address\n"); mprintf("Unable to determine MAC address\n");
mac_addr[0] = 0x11; // mac_addr[0] = 0x11; //
mac_addr[1] = 0x22; // mac_addr[1] = 0x22; //
mac_addr[2] = 0x33; // fallback MAC if get_persistent_mac fails mac_addr[2] = 0x33; // fallback MAC if get_persistent_mac fails
mac_addr[3] = 0x44; // mac_addr[3] = 0x44; //
mac_addr[4] = 0x55; // mac_addr[4] = 0x55; //
mac_addr[5] = 0x66; // mac_addr[5] = 0x66; //
} }
TRACE_DEV("Local MAC address: %x:%x:%x:%x:%x:%x\n", mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]); TRACE_DEV("Local MAC address: %x:%x:%x:%x:%x:%x\n", mac_addr[0],
mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4],
mac_addr[5]);
ep_init(mac_addr); ep_init(mac_addr);
ep_enable(1, 1); ep_enable(1, 1);
minic_init(); minic_init();
pps_gen_init(); pps_gen_init();
wrc_ptp_init(); wrc_ptp_init();
#if WITH_ETHERBONE #if WITH_ETHERBONE
ipv4_init("wru1"); ipv4_init("wru1");
arp_init("wru1"); arp_init("wru1");
#endif #endif
} }
...@@ -83,21 +85,19 @@ int wrc_check_link() ...@@ -83,21 +85,19 @@ int wrc_check_link()
int link_state = ep_link_up(NULL); int link_state = ep_link_up(NULL);
int rv = 0; int rv = 0;
if(!prev_link_state && link_state) if (!prev_link_state && link_state) {
{ TRACE_DEV("Link up.\n");
TRACE_DEV("Link up.\n"); gpio_out(GPIO_LED_LINK, 1);
gpio_out(GPIO_LED_LINK, 1); rv = LINK_WENT_UP;
rv = LINK_WENT_UP; } else if (prev_link_state && !link_state) {
} TRACE_DEV("Link down.\n");
else if(prev_link_state && !link_state) gpio_out(GPIO_LED_LINK, 0);
{ rv = LINK_WENT_DOWN;
TRACE_DEV("Link down.\n"); } else
gpio_out(GPIO_LED_LINK, 0); rv = (link_state ? LINK_UP : LINK_DOWN);
rv = LINK_WENT_DOWN; prev_link_state = link_state;
} else rv = (link_state ? LINK_UP : LINK_DOWN);
prev_link_state = link_state; return rv;
return rv;
} }
int wrc_extra_debug = 0; int wrc_extra_debug = 0;
...@@ -106,12 +106,13 @@ void wrc_debug_printf(int subsys, const char *fmt, ...) ...@@ -106,12 +106,13 @@ void wrc_debug_printf(int subsys, const char *fmt, ...)
{ {
va_list ap; va_list ap;
if(wrc_ui_mode) return; if (wrc_ui_mode)
return;
va_start(ap, fmt); va_start(ap, fmt);
if(wrc_extra_debug || (!wrc_extra_debug && (subsys & TRACE_SERVO))) if (wrc_extra_debug || (!wrc_extra_debug && (subsys & TRACE_SERVO)))
vprintf(fmt, ap); vprintf(fmt, ap);
va_end(ap); va_end(ap);
} }
...@@ -123,71 +124,63 @@ int wrc_man_phase = 0; ...@@ -123,71 +124,63 @@ int wrc_man_phase = 0;
static void ui_update() static void ui_update()
{ {
if(wrc_ui_mode == UI_GUI_MODE) if (wrc_ui_mode == UI_GUI_MODE) {
{ wrc_mon_gui();
wrc_mon_gui(); if (uart_read_byte() == 27) {
if(uart_read_byte() == 27) shell_init();
{ wrc_ui_mode = UI_SHELL_MODE;
shell_init();
wrc_ui_mode = UI_SHELL_MODE;
}
} }
else if(wrc_ui_mode == UI_STAT_MODE) } else if (wrc_ui_mode == UI_STAT_MODE) {
{ wrc_log_stats(0);
wrc_log_stats(0); if (uart_read_byte() == 27) {
if(uart_read_byte() == 27) shell_init();
{ wrc_ui_mode = UI_SHELL_MODE;
shell_init(); }
wrc_ui_mode = UI_SHELL_MODE; } else
} shell_interactive();
}
else
shell_interactive();
} }
int main(void) int main(void)
{ {
wrc_extra_debug = 1; wrc_extra_debug = 1;
wrc_ui_mode = UI_SHELL_MODE; wrc_ui_mode = UI_SHELL_MODE;
wrc_initialize(); wrc_initialize();
shell_init(); shell_init();
wrc_ptp_set_mode(WRC_MODE_SLAVE); wrc_ptp_set_mode(WRC_MODE_SLAVE);
wrc_ptp_start(); wrc_ptp_start();
//try to read and execute init script from EEPROM //try to read and execute init script from EEPROM
shell_boot_script(); shell_boot_script();
for (;;) for (;;) {
{ int l_status = wrc_check_link();
int l_status = wrc_check_link();
switch (l_status) switch (l_status) {
{
#if WITH_ETHERBONE #if WITH_ETHERBONE
case LINK_WENT_UP: case LINK_WENT_UP:
needIP = 1; needIP = 1;
break; break;
#endif #endif
case LINK_UP: case LINK_UP:
update_rx_queues(); update_rx_queues();
#if WITH_ETHERBONE #if WITH_ETHERBONE
ipv4_poll(); ipv4_poll();
arp_poll(); arp_poll();
#endif #endif
break; break;
case LINK_WENT_DOWN: case LINK_WENT_DOWN:
if( wrc_ptp_get_mode() == WRC_MODE_SLAVE ) if (wrc_ptp_get_mode() == WRC_MODE_SLAVE)
spll_init(SPLL_MODE_FREE_RUNNING_MASTER, 0, 1); spll_init(SPLL_MODE_FREE_RUNNING_MASTER, 0, 1);
break; break;
} }
ui_update(); ui_update();
wrc_ptp_update(); wrc_ptp_update();
spll_update_aux_clocks(); spll_update_aux_clocks();
} }
} }
...@@ -10,65 +10,64 @@ ...@@ -10,65 +10,64 @@
#include "pps_gen.h" #include "pps_gen.h"
static RunTimeOpts rtOpts = { static RunTimeOpts rtOpts = {
.ifaceName = { "wr1" }, .ifaceName = {"wr1"},
.announceInterval = DEFAULT_ANNOUNCE_INTERVAL, .announceInterval = DEFAULT_ANNOUNCE_INTERVAL,
.syncInterval = DEFAULT_SYNC_INTERVAL, .syncInterval = DEFAULT_SYNC_INTERVAL,
.clockQuality.clockAccuracy = DEFAULT_CLOCK_ACCURACY, .clockQuality.clockAccuracy = DEFAULT_CLOCK_ACCURACY,
.clockQuality.clockClass = DEFAULT_CLOCK_CLASS, .clockQuality.clockClass = DEFAULT_CLOCK_CLASS,
.clockQuality.offsetScaledLogVariance = DEFAULT_CLOCK_VARIANCE, .clockQuality.offsetScaledLogVariance = DEFAULT_CLOCK_VARIANCE,
.priority1 = DEFAULT_PRIORITY1, .priority1 = DEFAULT_PRIORITY1,
.priority2 = DEFAULT_PRIORITY2, .priority2 = DEFAULT_PRIORITY2,
.domainNumber = DEFAULT_DOMAIN_NUMBER, .domainNumber = DEFAULT_DOMAIN_NUMBER,
.currentUtcOffset = DEFAULT_UTC_OFFSET, .currentUtcOffset = DEFAULT_UTC_OFFSET,
.noResetClock = DEFAULT_NO_RESET_CLOCK, .noResetClock = DEFAULT_NO_RESET_CLOCK,
.noAdjust = NO_ADJUST, .noAdjust = NO_ADJUST,
.inboundLatency.nanoseconds = DEFAULT_INBOUND_LATENCY, .inboundLatency.nanoseconds = DEFAULT_INBOUND_LATENCY,
.outboundLatency.nanoseconds = DEFAULT_OUTBOUND_LATENCY, .outboundLatency.nanoseconds = DEFAULT_OUTBOUND_LATENCY,
.s = DEFAULT_DELAY_S, .s = DEFAULT_DELAY_S,
.ap = DEFAULT_AP, .ap = DEFAULT_AP,
.ai = DEFAULT_AI, .ai = DEFAULT_AI,
.max_foreign_records = DEFAULT_MAX_FOREIGN_RECORDS, .max_foreign_records = DEFAULT_MAX_FOREIGN_RECORDS,
/**************** White Rabbit *************************/ /**************** White Rabbit *************************/
.autoPortDiscovery = FALSE, /*if TRUE: automagically discovers how many ports we have (and how many up-s); else takes from .portNumber*/ .autoPortDiscovery = FALSE, /*if TRUE: automagically discovers how many ports we have (and how many up-s); else takes from .portNumber */
.portNumber = 1, .portNumber = 1,
.calPeriod = WR_DEFAULT_CAL_PERIOD, .calPeriod = WR_DEFAULT_CAL_PERIOD,
.E2E_mode = TRUE, .E2E_mode = TRUE,
.wrStateRetry = WR_DEFAULT_STATE_REPEAT, .wrStateRetry = WR_DEFAULT_STATE_REPEAT,
.wrStateTimeout= WR_DEFAULT_STATE_TIMEOUT_MS, .wrStateTimeout = WR_DEFAULT_STATE_TIMEOUT_MS,
.phyCalibrationRequired = FALSE, .phyCalibrationRequired = FALSE,
.disableFallbackIfWRFails = TRUE, .disableFallbackIfWRFails = TRUE,
.primarySource = FALSE, .primarySource = FALSE,
.wrConfig = WR_S_ONLY, .wrConfig = WR_S_ONLY,
.masterOnly = FALSE, .masterOnly = FALSE,
/********************************************************/ /********************************************************/
}; };
static PtpPortDS *ptpPortDS; static PtpPortDS *ptpPortDS;
static PtpClockDS ptpClockDS; static PtpClockDS ptpClockDS;
static int ptp_enabled = 0, ptp_mode = WRC_MODE_UNKNOWN; static int ptp_enabled = 0, ptp_mode = WRC_MODE_UNKNOWN;
int wrc_ptp_init() int wrc_ptp_init()
{ {
Integer16 ret; Integer16 ret;
netStartup(); netStartup();
ptpPortDS = ptpdStartup(0, NULL, &ret, &rtOpts, &ptpClockDS); ptpPortDS = ptpdStartup(0, NULL, &ret, &rtOpts, &ptpClockDS);
initDataClock(&rtOpts, &ptpClockDS); initDataClock(&rtOpts, &ptpClockDS);
//initialize sockets //initialize sockets
if(!netInit(&ptpPortDS->netPath, &rtOpts, ptpPortDS)) if (!netInit(&ptpPortDS->netPath, &rtOpts, ptpPortDS)) {
{ PTPD_TRACE(TRACE_WRPC, NULL, "failed to initialize network\n");
PTPD_TRACE(TRACE_WRPC, NULL,"failed to initialize network\n"); return -1;
return -1; }
}
ptpPortDS->linkUP = FALSE; ptpPortDS->linkUP = FALSE;
ptp_enabled = 0; ptp_enabled = 0;
return 0; return 0;
} }
#define LOCK_TIMEOUT_FM (4 * TICS_PER_SECOND) #define LOCK_TIMEOUT_FM (4 * TICS_PER_SECOND)
...@@ -80,35 +79,34 @@ int wrc_ptp_set_mode(int mode) ...@@ -80,35 +79,34 @@ int wrc_ptp_set_mode(int mode)
ptp_mode = 0; ptp_mode = 0;
wrc_ptp_stop(); wrc_ptp_stop();
switch(mode) switch (mode) {
{ case WRC_MODE_GM:
case WRC_MODE_GM: rtOpts.primarySource = TRUE;
rtOpts.primarySource = TRUE; rtOpts.wrConfig = WR_M_ONLY;
rtOpts.wrConfig = WR_M_ONLY; rtOpts.masterOnly = TRUE;
rtOpts.masterOnly = TRUE; spll_init(SPLL_MODE_GRAND_MASTER, 0, 1);
spll_init(SPLL_MODE_GRAND_MASTER, 0, 1); lock_timeout = LOCK_TIMEOUT_GM;
lock_timeout = LOCK_TIMEOUT_GM; break;
break;
case WRC_MODE_MASTER:
case WRC_MODE_MASTER: rtOpts.primarySource = FALSE;
rtOpts.primarySource = FALSE; rtOpts.wrConfig = WR_M_ONLY;
rtOpts.wrConfig = WR_M_ONLY; rtOpts.masterOnly = TRUE;
rtOpts.masterOnly = TRUE; spll_init(SPLL_MODE_FREE_RUNNING_MASTER, 0, 1);
spll_init(SPLL_MODE_FREE_RUNNING_MASTER, 0, 1); lock_timeout = LOCK_TIMEOUT_FM;
lock_timeout = LOCK_TIMEOUT_FM; break;
break;
case WRC_MODE_SLAVE: case WRC_MODE_SLAVE:
rtOpts.primarySource = FALSE; rtOpts.primarySource = FALSE;
rtOpts.wrConfig = WR_S_ONLY; rtOpts.wrConfig = WR_S_ONLY;
rtOpts.masterOnly = FALSE; rtOpts.masterOnly = FALSE;
spll_init(SPLL_MODE_SLAVE, 0, 1); spll_init(SPLL_MODE_SLAVE, 0, 1);
break; break;
} }
initDataClock(&rtOpts, &ptpClockDS); initDataClock(&rtOpts, &ptpClockDS);
start_tics = timer_get_tics(); start_tics = timer_get_tics();
...@@ -116,22 +114,19 @@ int wrc_ptp_set_mode(int mode) ...@@ -116,22 +114,19 @@ int wrc_ptp_set_mode(int mode)
pps_gen_enable_output(0); pps_gen_enable_output(0);
while(!spll_check_lock(0) && lock_timeout) while (!spll_check_lock(0) && lock_timeout) {
{
timer_delay(TICS_PER_SECOND); timer_delay(TICS_PER_SECOND);
mprintf("."); mprintf(".");
if(timer_get_tics() - start_tics > lock_timeout) if (timer_get_tics() - start_tics > lock_timeout) {
{
mprintf("\nLock timeout.\n"); mprintf("\nLock timeout.\n");
return -ETIMEDOUT; return -ETIMEDOUT;
} else if (uart_read_byte() == 27) } else if (uart_read_byte() == 27) {
{
mprintf("\n"); mprintf("\n");
return -EINTR; return -EINTR;
} }
} }
if(mode == WRC_MODE_MASTER || mode == WRC_MODE_GM) if (mode == WRC_MODE_MASTER || mode == WRC_MODE_GM)
pps_gen_enable_output(1); pps_gen_enable_output(1);
mprintf("\n"); mprintf("\n");
...@@ -146,27 +141,26 @@ int wrc_ptp_get_mode() ...@@ -146,27 +141,26 @@ int wrc_ptp_get_mode()
int wrc_ptp_start() int wrc_ptp_start()
{ {
ptpPortDS->linkUP = FALSE; ptpPortDS->linkUP = FALSE;
wr_servo_reset(); wr_servo_reset();
initDataClock(&rtOpts, &ptpClockDS); initDataClock(&rtOpts, &ptpClockDS);
ptp_enabled = 1; ptp_enabled = 1;
return 0; return 0;
} }
int wrc_ptp_stop() int wrc_ptp_stop()
{ {
ptp_enabled = 0; ptp_enabled = 0;
wr_servo_reset(); wr_servo_reset();
return 0; return 0;
} }
int wrc_ptp_update() int wrc_ptp_update()
{ {
if(ptp_enabled) if (ptp_enabled) {
{ singlePortLoop(&rtOpts, ptpPortDS, 0);
singlePortLoop(&rtOpts, ptpPortDS, 0); sharedPortsLoop(ptpPortDS);
sharedPortsLoop(ptpPortDS);
} }
return 0; return 0;
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment