Esempio n. 1
1
static struct imaptoken *do_readtoken(int touc)
{
int	c=0;
unsigned l;

#define	appendch(c)	alloc_tokenbuf(l+1); curtoken.tokenbuf[l++]=(c);

	if (curtoken.tokentype == IT_ERROR)	return (&curtoken);

	do
	{
		c=READ();
	} while (c == '\r' || c == ' ' || c == '\t');

	if (c == '\n')
	{
		UNREAD(c);
		curtoken.tokentype=IT_EOL;
		return (&curtoken);
	}
	c=(unsigned char)c;
	if (c == LPAREN_CHAR)
	{
		curtoken.tokentype=IT_LPAREN;
		return (&curtoken);
	}

	if (c == RPAREN_CHAR)
	{
		curtoken.tokentype=IT_RPAREN;
		return (&curtoken);
	}

	if (c == LBRACKET_CHAR)
	{
		curtoken.tokentype=IT_LBRACKET;
		return (&curtoken);
	}

	if (c == RBRACKET_CHAR)
	{
		curtoken.tokentype=IT_RBRACKET;
		return (&curtoken);
	}

	if (c == '"')
	{
		l=0;
		while ((c=READ()) != '"')
		{
			if (c == '\\')
				c=READ();
			if (c == '\r' || c == '\n')
			{
				UNREAD(c);
				curtoken.tokentype=IT_ERROR;
				return (&curtoken);
			}
			if (l < 8192)
			{
				appendch(c);
			}
		}
		appendch(0);
		curtoken.tokentype=IT_QUOTED_STRING;
		return (&curtoken);
	}

	if (c == '{')
	{
		curtoken.tokennum=0;
		while ((c=READ()) != '}')
		{
			if (!isdigit((int)(unsigned char)c))
			{
				UNREAD(c);
				curtoken.tokentype=IT_ERROR;
				return (&curtoken);
			}
			curtoken.tokennum = curtoken.tokennum*10 + (c-'0');
		}
		c=READ();
		if (c == '\r')
		{
			c=READ();
		}
		if (c != '\n')
		{
			curtoken.tokentype=IT_ERROR;
			return (&curtoken);
		}
		curtoken.tokentype=IT_LITERAL_STRING_START;
		return (&curtoken);
	}

	l=0;
	if (c == '\\')
	{
		appendch(c);	/* Message flag */
		c=READ();
	}
	else if (isdigit(c))
	{
		curtoken.tokentype=IT_NUMBER;
		curtoken.tokennum=0;
		do
		{
			appendch(c);
			curtoken.tokennum = curtoken.tokennum*10 +
				(c-'0');
			c=READ();
		} while (isdigit( (int)(unsigned char)c));

		/* Could be stuff like mime.spec, so continue reading. */
	}

	while (c != '\r' && c != '\n'
		&& !isspace((int)(unsigned char)c)
		&& c != '\\' && c != '"' && c != LPAREN_CHAR && c != RPAREN_CHAR
		&& c != '{' && c != '}' && c != LBRACKET_CHAR && c != RBRACKET_CHAR)
	{
		curtoken.tokentype=IT_ATOM;
		if (l < IT_MAX_ATOM_SIZE)
		{
			if (touc)
				c=toupper(c);
			appendch(c);
		}
		else
		{
			write_error_exit("max atom size too small");  
		}
		c=READ();
	}
	if (l == 0)
	{
		curtoken.tokentype=IT_ERROR;
		return (&curtoken);
	}
	appendch(0);
	UNREAD(c);

	if (strcmp(curtoken.tokenbuf, "NIL") == 0)
		curtoken.tokentype=IT_NIL;
	return (&curtoken);
}
//------------------------------------------------------------------------------
/// Initialize and configure the SDRAM for a 48 MHz MCK (ROM code clock settings)
//------------------------------------------------------------------------------
void BOARD_ConfigureSdram48MHz(unsigned char busWidth)
{
    volatile unsigned int i;
    static const Pin pinsSdram[] = {PINS_SDRAM};
    volatile unsigned int *pSdram = (unsigned int *) AT91C_EBI_SDRAM;
    unsigned short sdrc_dbw = 0;
    unsigned int tmp = 0;
	
    switch (busWidth) {
        case 16:
            sdrc_dbw = AT91C_SDRAMC_DBW_16_BITS;
            break;

        case 32:
        default:
            sdrc_dbw = AT91C_SDRAMC_DBW_32_BITS;
            break;

    }

    // Enable corresponding PIOs
    PIO_Configure(pinsSdram, 1);

    // Enable EBI chip select for the SDRAM
    tmp = READ(AT91C_BASE_MATRIX, MATRIX_EBICSA) | AT91C_MATRIX_CS1A_SDRAMC;
    WRITE(AT91C_BASE_MATRIX, MATRIX_EBICSA, tmp);


    // CFG Control Register
    WRITE(AT91C_BASE_SDRAMC, SDRAMC_CR, AT91C_SDRAMC_NC_9
                                        | AT91C_SDRAMC_NR_13
                                        | AT91C_SDRAMC_CAS_2
                                        | AT91C_SDRAMC_NB_4_BANKS
                                        | sdrc_dbw
                                        | AT91C_SDRAMC_TWR_1
                                        | AT91C_SDRAMC_TRC_4
                                        | AT91C_SDRAMC_TRP_1
                                        | AT91C_SDRAMC_TRCD_1
                                        | AT91C_SDRAMC_TRAS_2
                                        | AT91C_SDRAMC_TXSR_3);

    for (i = 0; i < 1000; i++);

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_NOP_CMD); // Perform NOP
    pSdram[0] = 0x00000000;

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_PRCGALL_CMD);     // Set PRCHG AL
    pSdram[0] = 0x00000000;                                         // Perform PRCHG

    for (i = 0; i < 10000; i++);

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 1st CBR
    pSdram[1] = 0x00000001;                                         // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 2 CBR
    pSdram[2] = 0x00000002;                                         // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 3 CBR
    pSdram[3] = 0x00000003;                                    // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 4 CBR
    pSdram[4] = 0x00000004;                                   // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 5 CBR
    pSdram[5] = 0x00000005;                                   // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 6 CBR
    pSdram[6] = 0x00000006;                                 // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 7 CBR
    pSdram[7] = 0x00000007;                                 // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_RFSH_CMD);        // Set 8 CBR
    pSdram[8] = 0x00000008;                                 // Perform CBR

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_LMR_CMD);         // Set LMR operation
    pSdram[9] = 0xcafedede;                                 // Perform LMR burst=1, lat=2

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_TR, (48000000 * 7) / 1000000);          // Set Refresh Timer

    WRITE(AT91C_BASE_SDRAMC, SDRAMC_MR, AT91C_SDRAMC_MODE_NORMAL_CMD);      // Set Normal mode
    pSdram[0] = 0x00000000;                                         // Perform Normal mode
}
Esempio n. 3
0
static struct imaptoken *readtoken(int touc)
{
struct imaptoken *tok=do_readtoken(touc);

	if (tok->tokentype == IT_LITERAL_STRING_START)
	{
	unsigned long nbytes=curtoken.tokennum;

		if (nbytes > 8192)
		{
			writes("* NO [ALERT] IMAP command too long.\r\n");
			tok->tokentype=IT_ERROR;
		}
		else
		{
		unsigned long i;

			writes("+ OK\r\n");
			writeflush();
			alloc_tokenbuf(nbytes+1);
			for (i=0; i<nbytes; i++)
				tok->tokenbuf[i]= READ();
			tok->tokenbuf[i]=0;
			tok->tokentype=IT_QUOTED_STRING;
		}
	}

	if (debugfile)
	{
	char	*p=0;

		fprintf(debugfile, "READ: ");
		switch (tok->tokentype) {
		case IT_ATOM:
			p=curtoken.tokenbuf; fprintf(debugfile, "ATOM"); break;
		case IT_NUMBER:
			p=curtoken.tokenbuf; fprintf(debugfile, "NUMBER"); break;
		case IT_QUOTED_STRING:
			p=curtoken.tokenbuf; fprintf(debugfile, "QUOTED_STRING"); break;
		case IT_LPAREN:
			fprintf(debugfile, "LPAREN"); break;
		case IT_RPAREN:
			fprintf(debugfile, "RPAREN"); break;
		case IT_NIL:
			fprintf(debugfile, "NIL"); break;
		case IT_ERROR:
			fprintf(debugfile, "ERROR"); break;
		case IT_EOL:
			fprintf(debugfile, "EOL"); break;
		case IT_LBRACKET:
			fprintf(debugfile, "LBRACKET"); break;
		case IT_RBRACKET:
			fprintf(debugfile, "RBRACKET"); break;
		}

		if (p)
			fprintf(debugfile, ": %s", p);
		fprintf(debugfile, "\n");
		fflush(debugfile);
	}
	return (tok);
}
Esempio n. 4
0
//------------------------------------------------------------------------------
/// Configure DDR
//------------------------------------------------------------------------------
void BOARD_ConfigureDdram(unsigned char ddrModel, unsigned char busWidth)
{    
    AT91PS_HDDRSDRC2 pDdrc = AT91C_BASE_DDR2C;
    volatile unsigned int *pDdr = (unsigned int *) AT91C_DDR2;
    int i;
    volatile unsigned int cr = 0;
    unsigned short ddrc_dbw = 0;

    switch (busWidth) {
        case 16:
        default:
            ddrc_dbw = AT91C_DDRC2_DBW_16_BITS;
            break;

        case 32:
            ddrc_dbw = AT91C_DDRC2_DBW_32_BITS;
            break;

    }

    // Enable DDR2 clock x2 in PMC
    WRITE(AT91C_BASE_PMC, PMC_SCER, AT91C_PMC_DDR);

    // Disable anticipated read
    WRITE(pDdrc, HDDRSDRC2_HS, (READ(pDdrc, HDDRSDRC2_HS) | AT91C_DDRC2_NO_ANT));

    switch (ddrModel) {

        case DDR_MICRON_MT47H64M8: 
            // Step 1: Program the memory device type
            WRITE(pDdrc, HDDRSDRC2_MDR, ddrc_dbw   |
                                        AT91C_DDRC2_MD_DDR2_SDRAM);     // DDR2
            
            // Step 2:                            
            // 1. Program the features of DDR2-SDRAM device into the Configuration Register.                    
            // 2. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T0PR.            
            // 3. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T1PR.            
            // 4. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T2PR.            

            WRITE(pDdrc, HDDRSDRC2_CR, AT91C_DDRC2_NC_DDR10_SDR9  |     // 10 column bits (1K)
                                       AT91C_DDRC2_NR_14          |     // 14 row bits    (8K)
                                       AT91C_DDRC2_CAS_3          |     // CAS Latency 3
                                       AT91C_DDRC2_DLL_RESET_DISABLED
                                       ); // DLL not reset

            // assume timings for 7.5ns min clock period
            WRITE(pDdrc, HDDRSDRC2_T0PR, AT91C_DDRC2_TRAS_6       |     //  6 * 7.5 = 45 ns
                                         AT91C_DDRC2_TRCD_2       |     //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TWR_2        |     //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TRC_8        |     //  8 * 7.5 = 75 ns
                                         AT91C_DDRC2_TRP_2        |     //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TRRD_1       |     //  1 * 7.5 = 7.5 ns
                                         AT91C_DDRC2_TWTR_1       |     //  1 clock cycle
                                         AT91C_DDRC2_TMRD_2);           //  2 clock cycles

            WRITE(pDdrc, HDDRSDRC2_T1PR, AT91C_DDRC2_TXP_2  |           //  2 * 7.5 = 15 ns
                                         200 << 16          |           // 200 clock cycles, TXSRD: Exit self refresh delay to Read command
                                         16 << 8            |           // 16 * 7.5 = 120 ns TXSNR: Exit self refresh delay to non read command
                                         AT91C_DDRC2_TRFC_14 << 0);     // 14 * 7.5 = 105 ns (must be 105 ns for 512M DDR)

            WRITE(pDdrc, HDDRSDRC2_T2PR, AT91C_DDRC2_TRTP_1   |         //  1 * 7.5 = 7.5 ns
                                         AT91C_DDRC2_TRPA_0   |         
                                         AT91C_DDRC2_TXARDS_7 |         //  7 clock cycles
                                         AT91C_DDRC2_TXARD_2);          //  2 clock cycles

            // Step 3: An NOP command is issued to the DDR2-SDRAM to enable clock.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
 
            // Initialization Step 3 (must wait 200 us) (6 core cycles per iteration, core is at 396MHz: min 13200 loops)
            for (i = 0; i < 13300; i++) {
                asm("    nop");
            }
            // Step 4:  An NOP command is issued to the DDR2-SDRAM 
            // NOP command -> allow to enable cke
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 5: An all banks precharge command is issued to the DDR2-SDRAM.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 6: An Extended Mode Register set (EMRS2) cycle is  issued to chose between commercialor high  temperature operations.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x4000000)) = 0;
         
            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 7: An Extended Mode Register set (EMRS3) cycle is issued to set all registers to 0.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x6000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
             
            // Step 8:  An Extended Mode Register set (EMRS1) cycle is issued to enable DLL.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x2000000)) = 0;

            // wait 200 cycles min
            for (i = 0; i < 10000; i++) {
                asm("    nop");
            }
            
            // Step 9:  Program DLL field into the Configuration Register.
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_DLL_RESET_ENABLED);
            
            // Step 10: A Mode Register set (MRS) cycle is issued to reset DLL.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 11: An all banks precharge command is issued to the DDR2-SDRAM.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *(pDdr) = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 12: Two auto-refresh (CBR) cycles are provided. Program the auto refresh command (CBR) into the Mode Register.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            // Set 2nd CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 13: Program DLL field into the Configuration Register to low(Disable DLL reset).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_DLL_RESET_ENABLED));
            
            // Step 14: A Mode Register set (MRS) cycle is issued to program the parameters of the DDR2-SDRAM devices.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0;
    
            // Step 15: Program OCD field into the Configuration Register to high (OCD calibration default).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_OCD_DEFAULT);
            
            // Step 16: An Extended Mode Register set (EMRS1) cycle is issued to OCD default value.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x2000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 17: Program OCD field into the Configuration Register to low (OCD calibration mode exit).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_OCD_EXIT));
         
           // Step 18: An Extended Mode Register set (EMRS1) cycle is issued to enable OCD exit.
           WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x6000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 19,20: A mode Normal command is provided. Program the Normal mode into Mode Register.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NORMAL_CMD);
            *(pDdr) = 0;

            // Step 21: Write the refresh rate into the count field in the Refresh Timer register. The DDR2-SDRAM device requires a
            // refresh every 15.625 ¦Ìs or 7.81 ¦Ìs. With a 100MHz frequency, the refresh timer count register must to be set with
            // (15.625 /100 MHz) = 1562 i.e. 0x061A or (7.81 /100MHz) = 781 i.e. 0x030d.
      
            // Set Refresh timer
            WRITE(pDdrc, HDDRSDRC2_RTR, 0x0000024B);

            // OK now we are ready to work on the DDRSDR

            // wait for end of calibration
            for (i = 0; i < 500; i++) {
                asm("    nop");
            }

            break;


        case DDR_SAMSUNG_M470T6554EZ3_CE6:

             // Step 1: Program the memory device type
            WRITE(pDdrc, HDDRSDRC2_MDR, ddrc_dbw   |
                                        AT91C_DDRC2_MD_DDR2_SDRAM);     // DDR2
            
            // Step 2:                            
            // 1. Program the features of DDR2-SDRAM device into the Configuration Register.                    
            // 2. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T0PR.            
            // 3. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T1PR.            
            // 4. Program the features of DDR2-SDRAM device into the Timing Register HDDRSDRC2_T2PR.            
            WRITE(pDdrc, HDDRSDRC2_CR, AT91C_DDRC2_NC_DDR10_SDR9  |     // 10 column bits (1K)
                                       AT91C_DDRC2_NR_13          |     // 13 row bits    (8K)
                                       AT91C_DDRC2_CAS_3          |     // CAS Latency 3
                                       AT91C_DDRC2_DLL_RESET_DISABLED); // DLL not reset
          
          // assume timings for 7.5ns min clock period
            WRITE(pDdrc, HDDRSDRC2_T0PR, AT91C_DDRC2_TRAS_6       |     //  6 * 7.5 = 45   ns
                                         AT91C_DDRC2_TRCD_2       |     //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TWR_2        |     //  2 * 7.5 = 15   ns
                                         AT91C_DDRC2_TRC_8       |      //  8 * 7.5 = 60   ns
                                         AT91C_DDRC2_TRP_2        |     //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TRRD_2       |     //  1 * 7.5 = 7.5   ns
                                         AT91C_DDRC2_TWTR_1       |     //  1 clock cycle
                                         AT91C_DDRC2_TMRD_2);           //  2 clock cycles
          
          
            WRITE(pDdrc, HDDRSDRC2_T1PR, AT91C_DDRC2_TXP_2  |           //  2 * 7.5 = 15 ns
                                         200 << 16          |           // 200 clock cycles, TXSRD: Exit self refresh delay to Read command
                                         16 << 8            |           // 16 * 7.5 = 120 ns TXSNR: Exit self refresh delay to non read command
                                         AT91C_DDRC2_TRFC_14 << 0);     // 14 * 7.5 = 105 ns (must be 105 ns for 512M DDR)
          
          
            WRITE(pDdrc, HDDRSDRC2_T2PR, AT91C_DDRC2_TRTP_1   |         //  1 * 7.5 = 7.5 ns
                                         AT91C_DDRC2_TRPA_0   |         
                                         AT91C_DDRC2_TXARDS_7 |         //  7 clock cycles
                                         AT91C_DDRC2_TXARD_2);          //  2 clock cycles

            // Step 3: An NOP command is issued to the DDR2-SDRAM to enable clock.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
 
            // Initialization Step 3 (must wait 200 us) (6 core cycles per iteration, core is at 396MHz: min 13200 loops)
            for (i = 0; i < 13300; i++) {
                asm("    nop");
            }
            // Step 4:  An NOP command is issued to the DDR2-SDRAM 
            // NOP command -> allow to enable cke
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 5: An all banks precharge command is issued to the DDR2-SDRAM.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 6: An Extended Mode Register set (EMRS2) cycle is  issued to chose between commercialor high  temperature operations.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x2000000)) = 0; // BA[1] is set to 1 and BA[0] are set to 0.
         
            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 7: An Extended Mode Register set (EMRS3) cycle is issued to set all registers to 0.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x3000000)) = 0; //BA[1] is set to 1 and BA[0] are set to 1.

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
             
            // Step 8:  An Extended Mode Register set (EMRS1) cycle is issued to enable DLL.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr)) = 0; //BA[1] and BA[0] are set to 0.

            // wait 200 cycles min
            for (i = 0; i < 10000; i++) {
                asm("    nop");
            }
            
            // Step 9:  Program DLL field into the Configuration Register.
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_DLL_RESET_ENABLED);
            
            // Step 10: A Mode Register set (MRS) cycle is issued to reset DLL.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 11: An all banks precharge command is issued to the DDR2-SDRAM.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *(pDdr) = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Step 12: Two auto-refresh (CBR) cycles are provided. Program the auto refresh command (CBR) into the Mode Register.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            // Set 2nd CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 13: Program DLL field into the Configuration Register to low(Disable DLL reset).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_DLL_RESET_ENABLED));
            
            // Step 14: A Mode Register set (MRS) cycle is issued to program the parameters of the DDR2-SDRAM devices.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0; //BA[1:0] are set to 0.
    
            // Step 15: Program OCD field into the Configuration Register to high (OCD calibration default).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_OCD_DEFAULT);
            
            // Step 16: An Extended Mode Register set (EMRS1) cycle is issued to OCD default value.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x1000000)) = 0; //BA[1] is set to 0 and BA[0] is set to 1

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 17: Program OCD field into the Configuration Register to low (OCD calibration mode exit).
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_OCD_EXIT));
         
            // Step 18: An Extended Mode Register set (EMRS1) cycle is issued to enable OCD exit.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x3000000)) = 0; //BA[1] is set to 1and BA[0] is set to 1.

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }
            
            // Step 19,20: A mode Normal command is provided. Program the Normal mode into Mode Register.
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NORMAL_CMD);
            *(pDdr) = 0;

            // Step 21: Write the refresh rate into the count field in the Refresh Timer register. The DDR2-SDRAM device requires a
            // refresh every 15.625 s or 7.81 s. With a 100MHz frequency, the refresh timer count register must to be set with
            // (15.625 /100 MHz) = 1562 i.e. 0x061A or (7.81 /100MHz) = 781 i.e. 0x030d.
      
            // Set Refresh timer
            WRITE(pDdrc, HDDRSDRC2_RTR, 0x0000024B);

            // OK now we are ready to work on the DDRSDR

            // wait for end of calibration
            for (i = 0; i < 500; i++) {
                asm("    nop");
            }

            break;


        default:
            break;
    }
}
Esempio n. 5
0
/******************************************************************************
 Update a new GIF file, given its file handle.
 Returns dynamically allocated GifFileType pointer which serves as the GIF
 info record.
******************************************************************************/
GifFileType *
DGifOpenFileHandle(int FileHandle, int *Error)
{
    char Buf[GIF_STAMP_LEN + 1];
    GifFileType *GifFile;
    GifFilePrivateType *Private;
    FILE *f;

    GifFile = (GifFileType *)malloc(sizeof(GifFileType));
    if (GifFile == NULL) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
        (void)close(FileHandle);
        return NULL;
    }

    /*@i1@*/memset(GifFile, '\0', sizeof(GifFileType));

    /* Belt and suspenders, in case the null pointer isn't zero */
    GifFile->SavedImages = NULL;
    GifFile->SColorMap = NULL;

    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
    if (Private == NULL) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
        (void)close(FileHandle);
        free((char *)GifFile);
        return NULL;
    }

    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));

#ifdef _WIN32
    _setmode(FileHandle, O_BINARY);    /* Make sure it is in binary mode. */
#endif /* _WIN32 */

    f = fdopen(FileHandle, "rb");    /* Make it into a stream: */

    /*@-mustfreeonly@*/
    GifFile->Private = (void *)Private;
    Private->FileHandle = FileHandle;
    Private->File = f;
    Private->FileState = FILE_STATE_READ;
    Private->Read = NULL;        /* don't use alternate input method (TVT) */
    GifFile->UserData = NULL;    /* TVT */
    /*@=mustfreeonly@*/

    /* Let's see if this is a GIF file: */
    /* coverity[check_return] */
    if (READ(GifFile, (unsigned char *)Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_READ_FAILED;
        (void)fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    /* Check for GIF prefix at start of file */
    Buf[GIF_STAMP_LEN] = 0;
    if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_GIF_FILE;
        (void)fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
        (void)fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    GifFile->Error = 0;

    /* What version of GIF? */
    Private->gif89 = (Buf[GIF_VERSION_POS] == '9');

    return GifFile;
}
Esempio n. 6
0
/******************************************************************************
 GifFileType constructor with user supplied input function (TVT)
******************************************************************************/
GifFileType *
DGifOpen(void *userData, InputFunc readFunc, int *Error)
{
    char Buf[GIF_STAMP_LEN + 1];
    GifFileType *GifFile;
    GifFilePrivateType *Private;

    GifFile = (GifFileType *)malloc(sizeof(GifFileType));
    if (GifFile == NULL) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
        return NULL;
    }

    memset(GifFile, '\0', sizeof(GifFileType));

    /* Belt and suspenders, in case the null pointer isn't zero */
    GifFile->SavedImages = NULL;
    GifFile->SColorMap = NULL;

    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
    if (!Private) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
        free((char *)GifFile);
        return NULL;
    }
    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));

    GifFile->Private = (void *)Private;
    Private->FileHandle = 0;
    Private->File = NULL;
    Private->FileState = FILE_STATE_READ;

    Private->Read = readFunc;    /* TVT */
    GifFile->UserData = userData;    /* TVT */

    /* Lets see if this is a GIF file: */
    /* coverity[check_return] */
    if (READ(GifFile, (unsigned char *)Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_READ_FAILED;
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    /* Check for GIF prefix at start of file */
    Buf[GIF_STAMP_LEN] = '\0';
    if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
        if (Error != NULL)
	    *Error = D_GIF_ERR_NOT_GIF_FILE;
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
        free((char *)Private);
        free((char *)GifFile);
        if (Error != NULL)
	    *Error = D_GIF_ERR_NO_SCRN_DSCR;
        return NULL;
    }

    GifFile->Error = 0;

    /* What version of GIF? */
    Private->gif89 = (Buf[GIF_VERSION_POS] == '9');

    return GifFile;
}
Esempio n. 7
0
Task*   import_heap_image__may_heapclean   (const char* fname, Heapcleaner_Args* params,  Roots* extra_roots) {
    //  ================================
    //
    // This fn is called (only) by   load_and_run_heap_image__may_heapclean   in   src/c/main/load-and-run-heap-image.c
    //
    Task*		task;
    Heapfile_Header	image_header;
    Heap_Header	heap_header;
    Val		*externs;
    Pthread_Image	image;
    Inbuf		inbuf;

    if (fname != NULL) {
	//
        // Resolve the name of the image.
        //  If the file exists use it, otherwise try the
        // pathname with the machine ID as an extension.

	if ((inbuf.file = fopen(fname, "rb"))) {
	    //
	    if (verbosity__global > 0)   say("loading %s ", fname);

	} else {
	    //
	    if ((inbuf.file = fopen(fname, "rb"))) {
		//
	        if (verbosity__global > 0)   say("loading %s ", fname);

	    } else {

		die ("unable to open heap image \"%s\"\n", fname);
	    }
	}

	inbuf.needs_to_be_byteswapped = FALSE;
	inbuf.buf	    = NULL;
	inbuf.nbytes    = 0;

    } else {
	//
	// fname == NULL, so try to find
	// an in-core heap image:

  	#if defined(DLOPEN) && !defined(OPSYS_WIN32)
	    //
	    void *lib = dlopen (NULL, RTLD_LAZY);
	    void *vimg, *vimglenptr;

	    if ((vimg       = dlsym(lib,HEAP_IMAGE_SYMBOL    )) == NULL)      die("no in-core heap image found\n");
	    if ((vimglenptr = dlsym(lib,HEAP_IMAGE_LEN_SYMBOL)) == NULL)      die("unable to find length of in-core heap image\n");

	    inbuf.file      = NULL;
	    inbuf.needs_to_be_byteswapped = FALSE;

	    inbuf.base      = vimg;
	    inbuf.buf       = inbuf.base;
	    inbuf.nbytes    = *(long*)vimglenptr;
        #else
	    die("in-core heap images not implemented\n");
        #endif
    }

    READ(&inbuf, image_header);

    if (image_header.byte_order != ORDER)						die ("incorrect byte order in heap image\n");
    if (image_header.magic != IMAGE_MAGIC)						die ("bad magic number (%#x) in heap image\n", image_header.magic);
    if ((image_header.kind != EXPORT_HEAP_IMAGE) && (image_header.kind != EXPORT_FN_IMAGE))	die ("bad image kind (%d) in heap image\n", image_header.kind);

    READ(&inbuf, heap_header);

    // Check for command-line overrides of heap parameters:
    //
    if (params->agegroup0_buffer_bytesize == 0) {
        params->agegroup0_buffer_bytesize = heap_header.agegroup0_buffer_bytesize;
    }
    if (params->active_agegroups < heap_header.active_agegroups) {
        params->active_agegroups = heap_header.active_agegroups;
    }
    if (params->oldest_agegroup_retaining_fromspace_sibs_between_heapcleanings < 0) {
        params->oldest_agegroup_retaining_fromspace_sibs_between_heapcleanings = heap_header.oldest_agegroup_retaining_fromspace_sibs_between_heapcleanings;
    } 

    task = make_task( /*is_boot:*/FALSE, params );					// make_task		def in   src/c/main/runtime-state.c

    // Get the run-time pointers into the heap:
    //
    *PTR_CAST( Val*, PERVASIVE_PACKAGE_PICKLE_LIST_REFCELL__GLOBAL )
        =
        heap_header.pervasive_package_pickle_list;

    // This carefully constructed fake looks like a normal
    // compiled package from the Mythryl side but actually
    // links to compile C code -- see the hack in
    //	
    //     src/c/main/load-compiledfiles.c
    //
    runtime_package__global =  heap_header.runtime_pseudopackage;

    #ifdef ASM_MATH
	mathvec__global = heap_header.math_package;
    #endif


    externs = heapio__read_externs_table (&inbuf);				// Read the externals table.

    READ(&inbuf, image);							// Read and initialize the Mythryl state info.
    //
    if (image_header.kind == EXPORT_HEAP_IMAGE) {

        // Load the live registers:
        //
	ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL,
                image.posix_interprocess_signal_handler
              );
	//
	task->argument		= image.stdArg;
	task->fate		= image.stdCont;
	task->current_closure	= image.stdClos;
	task->program_counter	= image.pc;
	task->exception_fate	= image.exception_fate;
	task->current_thread	= image.current_thread;
	//
	task->callee_saved_registers[0]	= image.calleeSave[0];
	task->callee_saved_registers[1]	= image.calleeSave[1];
	task->callee_saved_registers[2]	= image.calleeSave[2];

	read_heap (&inbuf, &heap_header, task, externs);			// Read the Mythryl heap.

	/* heapcleaner_messages_are_enabled__global = TRUE; */			// Heapcleaning messages are on by default for interactive images.

    } else { 									// EXPORT_FN_IMAGE

        // Restore the signal handler:
        //
	ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, image.posix_interprocess_signal_handler );

        // Read the Mythryl heap:
        //
	task->argument		= image.stdArg;
	read_heap (&inbuf, &heap_header, task, externs);

        // Initialize the calling context (taken from run_mythryl_function__may_heapclean):			// run_mythryl_function__may_heapclean	def in   src/c/main/run-mythryl-code-and-runtime-eventloop.c
        //
	Val function_to_run	= task->argument;
	//
	task->exception_fate	= PTR_CAST( Val,  handle_uncaught_exception_closure_v + 1 );
	task->current_thread	= HEAP_VOID;
	//
	task->fate		= PTR_CAST( Val,  return_to_c_level_c );
	task->current_closure	= function_to_run;
	//
	task->program_counter	=
	task->link_register	= GET_CODE_ADDRESS_FROM_CLOSURE( function_to_run );				// Last use of 'function_to_run'.

        // Set up the arguments to the imported function:
        //
	Val program_name =  make_ascii_string_from_c_string__may_heapclean(task, mythryl_program_name__global, extra_roots);		Roots roots1 = { &program_name, extra_roots };
        //
	Val args         =  make_ascii_strings_from_vector_of_c_strings__may_heapclean (task, commandline_args_without_argv0_or_runtime_args__global, &roots1 );

	task->argument = make_two_slot_record( task, program_name, args );

	// debug_say("arg = %#x : [%#x, %#x]\n", task->argument, GET_TUPLE_SLOT_AS_VAL(task->argument, 0), GET_TUPLE_SLOT_AS_VAL(task->argument, 1));

        // Heapcleaner messages are off by
        // default for spawn_to_disk images:
        //
	heapcleaner_messages_are_enabled__global =  FALSE;
    }

    FREE( externs );

    if (inbuf.file)   fclose (inbuf.file);

    if (verbosity__global > 0)   say(" done\n");

    return task;
}								// fun import_heap_image__may_heapclean
Esempio n. 8
0
static
void
readBuffer( MeshesVector& meshes,
            FILE*     f,
            const std::string& fn )
{
    int32_t meshIndex;
//    READ_I32( meshIndex );
    if ( fread( &meshIndex, 4, 1, f ) != 1 )
    {
        if ( feof( f ) )
        {
            return; // no error, file ended
        }
        else
        {
            throw std::runtime_error( "Can't read meshIndex" + std::string(" from ") + fn );
        }
    }

    MeshData* m = meshes[ meshIndex ].get();

    int bufferType;
    int bufferSize;

    READ_I32( bufferType );
    READ_I32( bufferSize );

#define CASE( _type, _name, _data_type )                \
        case BT_##_type:                                \
            m->_name = new _data_type( bufferSize );    \
            READ( m->_name );                           \
            break

//     printf( "reading %d mesh, buffer type = %d (0x%08X), buffer size = %d\n",
//             meshIndex, bufferType, bufferType, bufferSize );
//     fflush( stdout );
    
    switch ( bufferType & BT_MASK )
    {
        case BT_INDEX:
            switch ( bufferType & ET_MASK )
            {
                case ET_UBYTE:
                    m->indexBuffer = new osg::DrawElementsUByte( osg::PrimitiveSet::TRIANGLES, bufferSize );
                    break;

                case ET_USHORT:
                    m->indexBuffer = new osg::DrawElementsUShort( osg::PrimitiveSet::TRIANGLES, bufferSize );
                    break;

                case ET_UINT:
                    m->indexBuffer = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, bufferSize );
                    break;

                default:
                {
                    char err[ 1024 ];
                    sprintf( err, "Unknown index buffer element type %d (0x%08X)",
                             bufferType & ET_MASK, bufferType & ET_MASK );
                    throw std::runtime_error( err );
                }

            }
            READ( m->indexBuffer );
            break;

        CASE( VERTEX, vertexBuffer, VertexBuffer );
        CASE( WEIGHT, weightBuffer, WeightBuffer );
        CASE( MATRIX_INDEX, matrixIndexBuffer, MatrixIndexBuffer );
        CASE( NORMAL, normalBuffer, NormalBuffer );
        CASE( TEX_COORD, texCoordBuffer, TexCoordBuffer );
        CASE( TANGENT_AND_HANDEDNESS, tangentAndHandednessBuffer, TangentAndHandednessBuffer );

        default:
        {
            char err[ 1024 ];
            sprintf( err, "Unknown buffer type %d (0x%08X)", bufferType, bufferType );
            throw std::runtime_error( err );
        }
    }

#undef CASE
}
Esempio n. 9
0
/******************************************************************************
 * Update a new gif file, given its file handle.
 * Returns GifFileType pointer dynamically allocated which serves as the gif
 * info record. _GifError is cleared if succesfull.
 *****************************************************************************/
GifFileType *
DGifOpenFileHandle(int FileHandle) {

    unsigned char Buf[GIF_STAMP_LEN + 1];
    GifFileType *GifFile;
    GifFilePrivateType *Private;
    FILE *f;

    GifFile = (GifFileType *)malloc(sizeof(GifFileType));
    if (GifFile == NULL) {
        _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
        close(FileHandle);
        return NULL;
    }

    memset(GifFile, '\0', sizeof(GifFileType));

    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
    if (Private == NULL) {
        _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
        close(FileHandle);
        free((char *)GifFile);
        return NULL;
    }
#if defined(__MSDOS__) || defined(WIN32) || defined(WIN64) || defined(_OPEN_BINARY)
    setmode(FileHandle, O_BINARY);    /* Make sure it is in binary mode. */
#endif /* __MSDOS__ */

    f = fdopen(FileHandle, "rb");    /* Make it into a stream: */

#if defined(__MSDOS__) || defined(WIN32) || defined(WIN64)
    setvbuf(f, NULL, _IOFBF, GIF_FILE_BUFFER_SIZE);    /* And inc. stream
                                                          buffer. */
#endif /* __MSDOS__ */

    GifFile->Private = (VoidPtr)Private;
    Private->FileHandle = FileHandle;
    Private->File = f;
    Private->FileState = FILE_STATE_READ;
    Private->Read = 0;    /* don't use alternate input method (TVT) */
    GifFile->UserData = 0;    /* TVT */

    /* Lets see if this is a GIF file: */
    if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
        _GifError = D_GIF_ERR_READ_FAILED;
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    /* The GIF Version number is ignored at this time. Maybe we should do
     * something more useful with it.  */
    Buf[GIF_STAMP_LEN] = 0;
    if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
        _GifError = D_GIF_ERR_NOT_GIF_FILE;
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    _GifError = 0;

    return GifFile;
}
Esempio n. 10
0
/******************************************************************************
 * This routine should be called before any attempt to read an image.
 * Note it is assumed the Image desc. header (',') has been read.
 *****************************************************************************/
int
DGifGetImageDesc(GifFileType * GifFile) {

    int i, BitsPerPixel;
    GifByteType Buf[3];
    GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
    SavedImage *sp;

    if (!IS_READABLE(Private)) {
        /* This file was NOT open for reading: */
        _GifError = D_GIF_ERR_NOT_READABLE;
        return GIF_ERROR;
    }

    if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
            DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
            DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
            DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
        return GIF_ERROR;
    if (READ(GifFile, Buf, 1) != 1) {
        _GifError = D_GIF_ERR_READ_FAILED;
        return GIF_ERROR;
    }
    BitsPerPixel = (Buf[0] & 0x07) + 1;
    GifFile->Image.Interlace = (Buf[0] & 0x40);
    if (Buf[0] & 0x80) {    /* Does this image have local color map? */

        /*** FIXME: Why do we check both of these in order to do this?
         * Why do we have both Image and SavedImages? */
        if (GifFile->Image.ColorMap && GifFile->SavedImages == NULL)
            FreeMapObject(GifFile->Image.ColorMap);

        GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
        if (GifFile->Image.ColorMap == NULL) {
            _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }

        /* Get the image local color map: */
        for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
            if (READ(GifFile, Buf, 3) != 3) {
                FreeMapObject(GifFile->Image.ColorMap);
                _GifError = D_GIF_ERR_READ_FAILED;
                GifFile->Image.ColorMap = NULL;
                return GIF_ERROR;
            }
            GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
            GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
            GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
        }
    } else if (GifFile->Image.ColorMap) {
        FreeMapObject(GifFile->Image.ColorMap);
        GifFile->Image.ColorMap = NULL;
    }

    if (GifFile->SavedImages) {
        if ((GifFile->SavedImages = (SavedImage *)realloc(GifFile->SavedImages,
                                    sizeof(SavedImage) *
                                    (GifFile->ImageCount + 1))) == NULL) {
            _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
    } else {
        if ((GifFile->SavedImages =
                    (SavedImage *) malloc(sizeof(SavedImage))) == NULL) {
            _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
    }

    sp = &GifFile->SavedImages[GifFile->ImageCount];
    memcpy(&sp->ImageDesc, &GifFile->Image, sizeof(GifImageDesc));
    if (GifFile->Image.ColorMap != NULL) {
        sp->ImageDesc.ColorMap = MakeMapObject(
                                     GifFile->Image.ColorMap->ColorCount,
                                     GifFile->Image.ColorMap->Colors);
        if (sp->ImageDesc.ColorMap == NULL) {
            _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
    }
    sp->RasterBits = (unsigned char *)NULL;
    sp->ExtensionBlockCount = 0;
    sp->ExtensionBlocks = (ExtensionBlock *) NULL;

    GifFile->ImageCount++;

    Private->PixelCount = (long)GifFile->Image.Width *
                          (long)GifFile->Image.Height;

    DGifSetupDecompress(GifFile);  /* Reset decompress algorithm parameters. */

    return GIF_OK;
}
Esempio n. 11
0
static bool parse_element(FILE *in, int state, element_t *out)
{
    tag_t tag;
    element_t item;
    int length;
    char vr[3] = "  ";
    char tmp_buff[128];
    bool extra_len = false;
    int i;

    if (remain_size(in) == 0) return false;
    tag.group = READ(uint16_t, in);
    tag.element  = READ(uint16_t, in);

    if (state & STATE_IMPLICIT_VR) {
        length = READ(uint32_t, in);
        // XXX: Handle this with a static table.
        if (tag.v == TAG_INSTANCE_NUMBER.v) sprintf(vr, "IS");
        if (tag.v == TAG_SLICE_LOCATION.v) sprintf(vr, "DS");
        if (tag.v == TAG_SAMPLES_PER_PIXEL.v) sprintf(vr, "US");
        if (tag.v == TAG_ROWS.v) sprintf(vr, "US");
        if (tag.v == TAG_COLUMNS.v) sprintf(vr, "US");
        if (tag.v == TAG_BITS_ALLOCATED.v) sprintf(vr, "US");
        if (tag.v == TAG_BITS_STORED.v) sprintf(vr, "US");
        if (tag.v == TAG_HIGH_BIT.v) sprintf(vr, "US");
    } else {
        fread(vr, 2, 1, in);
        for (i = 0; i < ARRAY_SIZE(EXTRA_LEN_VRS); i++) {
            if (strncmp(vr, EXTRA_LEN_VRS[i], 2) == 0) {
                extra_len = true;
                break;
            }
        }
        if (extra_len) {
            READ(uint16_t, in);     // Reserved 2 bytes
            length = READ(uint32_t, in);
        } else {
            length = READ(uint16_t, in);
        }
    }

    LOG_V("(%.4x, %.4x) %s, length:%d", tag.group, tag.element, vr, length);

    // Read a sequence of undefined length.
    if (length == 0xffffffff && strncmp(vr, "SQ", 2) == 0) {
        while (true) {
            parse_element(in, STATE_SEQUENCE_ITEM | STATE_IMPLICIT_VR, &item);
            if (item.tag.v == TAG_SEQ_DEL.v) {
                break;
            }
            if (item.tag.v != TAG_ITEM.v)
                LOG_E("Expected item tag");
        }
    }
    if (state & STATE_SEQUENCE_ITEM && length == 0xffffffff) {
        while (true) {
            parse_element(in, 0, &item);
            if (item.tag.v == TAG_ITEM_DEL.v) {
                break;
            }
        }
    }

    if (out) {
        out->tag = tag;
        out->length = length;
        memcpy(out->vr, vr, 2);
    }

    // For the moment we just skip the data.
    if (length != 0xffffffff) {
        CHECK(length >= 0);
        if (length > remain_size(in)) {
            CHECK(false);
        }
        if (out && length == 2 && strncmp(vr, "US", 2) == 0) {
            out->value.us = READ(uint16_t, in);
        }  else if (out && strncmp(vr, "IS", 2) == 0) {
            CHECK(length < sizeof(tmp_buff) - 1);
            fread(tmp_buff, length, 1, in);
            tmp_buff[length] = '\0';
            sscanf(tmp_buff, "%d", &out->value.is);
        }  else if (out && strncmp(vr, "DS", 2) == 0) {
            CHECK(length < sizeof(tmp_buff) - 1);
            fread(tmp_buff, length, 1, in);
            tmp_buff[length] = '\0';
            sscanf(tmp_buff, "%f", &out->value.ds);
        }  else if (out && strncmp(vr, "UI", 2) == 0) {
            CHECK(length < sizeof(out->value.ui) - 1);
            fread(out->value.ui, length, 1, in);
            out->value.ui[length] = '\0';
        } else if (out && tag.v == TAG_PIXEL_DATA.v && out->buffer) {
            CHECK(out->buffer_size >= length);
            fread(out->buffer, length, 1, in);
        } else {
            // Skip the data.
            fseek(in, length, SEEK_CUR);
        }
    }

    if (tag.group == 0) return false;
    return true;
}
Esempio n. 12
0
#include "edmac.h"

#if defined(CONFIG_5D3) || defined(CONFIG_6D) /* 6D + 5D3 are Identical */

#define WRITE(x) (x)
#define READ(x)  (0x80000000 | (x))

#define IS_USED(x) ((x) != 0xFFFFFFFF)
#define IS_WRITE(x) (((x) & 0x80000000) == 0)
#define IS_READ(x)  (((x) & 0x80000000) != 0)

/* channel usage for 5D3 */
static uint32_t edmac_chanlist[] = 
{
    WRITE(0), WRITE(1), WRITE(2), WRITE(3), WRITE(4), WRITE(5), WRITE(6), 0xFFFFFFFF,
    READ(0), READ(1), READ(2), READ(3), READ(4), READ(5), 0xFFFFFFFF, 0xFFFFFFFF,
    WRITE(7),  WRITE(8), WRITE(9), WRITE(10), WRITE(11), WRITE(12), WRITE(13), 0xFFFFFFFF,
    READ(6), READ(7), READ(8), READ(9), READ(10), READ(11), 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
    WRITE(14), WRITE(15), 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
    READ(12), READ(13), READ(14), READ(15), 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF
};

uint32_t edmac_get_dir(uint32_t channel)
{
    if(!IS_USED(edmac_chanlist[channel]))
    {
        return EDMAC_DIR_UNUSED;
    }
    
    if(IS_WRITE(edmac_chanlist[channel]))
    {
Esempio n. 13
0
static void
fbBresDash(DrawablePtr drawable, GCPtr gc, int dashOffset,
           int sdx, int sdy, int axis,
	   int x1, int y1,
	   int e, int e1, int e3, int len)
{
	FbStip *dst;
	FbStride stride;
	int bpp;
	int dx, dy;
	FbGCPrivPtr pgc = fb_gc(gc);
	FbStip and = (FbStip) pgc->and;
	FbStip xor = (FbStip) pgc->xor;
	FbStip bgand = (FbStip) pgc->bgand;
	FbStip bgxor = (FbStip) pgc->bgxor;
	FbStip mask, mask0;

	FbDashDeclare;
	int dashlen;
	bool even;
	bool doOdd;

	fbGetStipDrawable(drawable, dst, stride, bpp, dx, dy);
	doOdd = gc->lineStyle == LineDoubleDash;

	FbDashInit(gc, pgc, dashOffset, dashlen, even);

	dst += ((y1 + dy) * stride);
	x1 = (x1 + dx) * bpp;
	dst += x1 >> FB_STIP_SHIFT;
	x1 &= FB_STIP_MASK;
	mask0 = FbStipMask(0, bpp);
	mask = FbStipRight(mask0, x1);
	if (sdx < 0)
		mask0 = FbStipRight(mask0, FB_STIP_UNIT - bpp);
	if (sdy < 0)
		stride = -stride;
	while (len--) {
		if (even)
			WRITE(dst, FbDoMaskRRop(READ(dst), and, xor, mask));
		else if (doOdd)
			WRITE(dst, FbDoMaskRRop(READ(dst), bgand, bgxor, mask));
		if (axis == X_AXIS) {
			mask = fbBresShiftMask(mask, sdx, bpp);
			if (!mask) {
				dst += sdx;
				mask = mask0;
			}
			e += e1;
			if (e >= 0) {
				dst += stride;
				e += e3;
			}
		} else {
			dst += stride;
			e += e1;
			if (e >= 0) {
				e += e3;
				mask = fbBresShiftMask(mask, sdx, bpp);
				if (!mask) {
					dst += sdx;
					mask = mask0;
				}
			}
		}
		FbDashStep(dashlen, even);
	}
}
Esempio n. 14
0
static void
fbBresSolid(DrawablePtr drawable, GCPtr gc, int dashOffset,
            int sdx, int sdy, int axis,
	    int x1, int y1,
	    int e, int e1, int e3, int len)
{
	FbStip *dst;
	FbStride stride;
	int bpp;
	int dx, dy;
	FbGCPrivPtr pgc = fb_gc(gc);
	FbStip and = (FbStip) pgc->and;
	FbStip xor = (FbStip) pgc->xor;
	FbStip mask, mask0;
	FbStip bits;

	fbGetStipDrawable(drawable, dst, stride, bpp, dx, dy);
	dst += ((y1 + dy) * stride);
	x1 = (x1 + dx) * bpp;
	dst += x1 >> FB_STIP_SHIFT;
	x1 &= FB_STIP_MASK;
	mask0 = FbStipMask(0, bpp);
	mask = FbStipRight(mask0, x1);
	if (sdx < 0)
		mask0 = FbStipRight(mask0, FB_STIP_UNIT - bpp);
	if (sdy < 0)
		stride = -stride;
	if (axis == X_AXIS) {
		bits = 0;
		while (len--) {
			bits |= mask;
			mask = fbBresShiftMask(mask, sdx, bpp);
			if (!mask) {
				WRITE(dst, FbDoMaskRRop(READ(dst), and, xor, bits));
				bits = 0;
				dst += sdx;
				mask = mask0;
			}
			e += e1;
			if (e >= 0) {
				WRITE(dst, FbDoMaskRRop(READ(dst), and, xor, bits));
				bits = 0;
				dst += stride;
				e += e3;
			}
		}
		if (bits)
			WRITE(dst, FbDoMaskRRop(READ(dst), and, xor, bits));
	} else {
		while (len--) {
			WRITE(dst, FbDoMaskRRop(READ(dst), and, xor, mask));
			dst += stride;
			e += e1;
			if (e >= 0) {
				e += e3;
				mask = fbBresShiftMask(mask, sdx, bpp);
				if (!mask) {
					dst += sdx;
					mask = mask0;
				}
			}
		}
	}
}
Esempio n. 15
0
VOID
RegReadDisplaySettings(HKEY hkey, PDEVMODEW pdm)
{
    DWORD dwValue;

    /* Zero out the structure */
    RtlZeroMemory(pdm, sizeof(DEVMODEW));

/* Helper macro */
#define READ(field, str, flag) \
    if (RegReadDWORD(hkey, L##str, &dwValue)) \
    { \
        pdm->field = dwValue; \
        pdm->dmFields |= flag; \
    }

    /* Read all present settings */
    READ(dmBitsPerPel, "DefaultSettings.BitsPerPel", DM_BITSPERPEL);
    READ(dmPelsWidth, "DefaultSettings.XResolution", DM_PELSWIDTH);
    READ(dmPelsHeight, "DefaultSettings.YResolution", DM_PELSHEIGHT);
    READ(dmDisplayFlags, "DefaultSettings.Flags", DM_DISPLAYFLAGS);
    READ(dmDisplayFrequency, "DefaultSettings.VRefresh", DM_DISPLAYFREQUENCY);
    READ(dmPanningWidth, "DefaultSettings.XPanning", DM_PANNINGWIDTH);
    READ(dmPanningHeight, "DefaultSettings.YPanning", DM_PANNINGHEIGHT);
    READ(dmDisplayOrientation, "DefaultSettings.Orientation", DM_DISPLAYORIENTATION);
    READ(dmDisplayFixedOutput, "DefaultSettings.FixedOutput", DM_DISPLAYFIXEDOUTPUT);
    READ(dmPosition.x, "Attach.RelativeX", DM_POSITION);
    READ(dmPosition.y, "Attach.RelativeY", DM_POSITION);
}
Esempio n. 16
0
/* Warning: This function is called from interrupt context */
void lcd_buttons_update()
{
#ifdef NEWPANEL
    uint8_t newbutton=0;
    if(READ(BTN_EN1)==0)  newbutton|=EN_A;
    if(READ(BTN_EN2)==0)  newbutton|=EN_B;
  #if BTN_ENC > 0
    if((blocking_enc<millis()) && (READ(BTN_ENC)==0))
        newbutton |= EN_C;
  #endif
    buttons = newbutton;
    #ifdef LCD_HAS_SLOW_BUTTONS
    buttons |= slow_buttons;
    #endif
    #ifdef REPRAPWORLD_KEYPAD
      // for the reprapworld_keypad
      uint8_t newbutton_reprapworld_keypad=0;
      WRITE(SHIFT_LD,LOW);
      WRITE(SHIFT_LD,HIGH);
      for(int8_t i=0;i<8;i++) {
          newbutton_reprapworld_keypad = newbutton_reprapworld_keypad>>1;
          if(READ(SHIFT_OUT))
              newbutton_reprapworld_keypad|=(1<<7);
          WRITE(SHIFT_CLK,HIGH);
          WRITE(SHIFT_CLK,LOW);
      }
      buttons_reprapworld_keypad=~newbutton_reprapworld_keypad; //invert it, because a pressed switch produces a logical 0
	#endif
#else   //read it from the shift register
    uint8_t newbutton=0;
    WRITE(SHIFT_LD,LOW);
    WRITE(SHIFT_LD,HIGH);
    unsigned char tmp_buttons=0;
    for(int8_t i=0;i<8;i++)
    {
        newbutton = newbutton>>1;
        if(READ(SHIFT_OUT))
            newbutton|=(1<<7);
        WRITE(SHIFT_CLK,HIGH);
        WRITE(SHIFT_CLK,LOW);
    }
    buttons=~newbutton; //invert it, because a pressed switch produces a logical 0
#endif//!NEWPANEL

    //manage encoder rotation
    uint8_t enc=0;
    if (buttons & EN_A) enc |= B01;
    if (buttons & EN_B) enc |= B10;
    if(enc != lastEncoderBits)
    {
        switch(enc)
        {
        case encrot0:
            if(lastEncoderBits==encrot3)
                encoderDiff++;
            else if(lastEncoderBits==encrot1)
                encoderDiff--;
            break;
        case encrot1:
            if(lastEncoderBits==encrot0)
                encoderDiff++;
            else if(lastEncoderBits==encrot2)
                encoderDiff--;
            break;
        case encrot2:
            if(lastEncoderBits==encrot1)
                encoderDiff++;
            else if(lastEncoderBits==encrot3)
                encoderDiff--;
            break;
        case encrot3:
            if(lastEncoderBits==encrot2)
                encoderDiff++;
            else if(lastEncoderBits==encrot0)
                encoderDiff--;
            break;
        }
    }
    lastEncoderBits = enc;
}
Esempio n. 17
0
File: main.c Progetto: pmdias/netgen
int
main(int argc, char **argv)
{
	/* Main Variables */
	long seed, problem;
	long parms[PROBLEM_PARMS];
	long arcs;
	int i;
	
	/* I/O Variables */
	FILE * fin = NULL;
	FILE * fout = NULL;
	char filename[256];
	unsigned char flag;
	
	/* The generator accepts two forms of input: a file from where the problem
	 * params are read or an input stream from stdin. If no file is provided in
	 * command line, it is assumed that the params are to be inputed from stdin.
	 */
	if(argc == 2) {
		flag = INPUT_FILE;
	} else if(argc == 1) {
		flag = INPUT_STDIN;
	} else {
		fprintf(stderr, "Usage: ./netgen [FILE]\n");
		goto TERMINATE;
	}
	
	if(flag == INPUT_FILE) {
		fprintf(stderr, "ERROR: reading from input file still not possible.\n");
		goto TERMINATE;
	} else if(flag == INPUT_STDIN) {
		/* First read the seed and the problem: if valid, read the rest of input */
		fprintf(stdout, "Seed: ");
		READ(seed);
		fprintf(stdout, "Problem: ");
		READ(problem);

		if(seed <= 0 || problem <= 0) {
			fprintf(stderr, "Incorrect seed value or problem value.\n");
			goto TERMINATE;
		}

		for(i = 0; i < PROBLEM_PARMS; i++) {
			switch(i) {
				case 0:
					fprintf(stdout, "Number of Nodes: ");
					break;
				case 1:
					fprintf(stdout, "Number of Sources: ");
					break;
				case 2:
					fprintf(stdout, "Number of Sinks: ");
					break;
				case 3:
					fprintf(stdout, "Number of Arcs: ");
					break;
				case 4:
					fprintf(stdout, "Arc Minimum Cost: ");
					break;
				case 5:
					fprintf(stdout, "Arc Maximum Cost: ");
					break;
				case 6:
					fprintf(stdout, "Total Supply: ");
					break;
				case 7:
					fprintf(stdout, "Transshipment Sources: ");
					break;
				case 8:
					fprintf(stdout, "Transshipment Sinks: ");
					break;
				case 9:
					fprintf(stdout, "Percent of skeleton arcs given maximum cost: ");
					break;
				case 10:
					fprintf(stdout, "Percent of arcs to be capacitated: ");
					break;
				case 11:
					fprintf(stdout, "Minimum capacity for capacitated arcs: ");
					break;
				case 12:
					fprintf(stdout, "Maximum capacity for capacitated arcs: ");
					break;
				default:
					break;
			}
			READ(parms[i]);
		}
	}
	
	/* Open output file */
	sprintf(filename, "%ld", problem);
	fout = fopen(filename, "w");
	if(!fout) {
		fprintf(stderr, "Unable to open output file.\n");
		exit(0);
	}
	
	/* Output to file */
	fprintf(fout, "c NETGEN flow network generator (C version)\n");
	fprintf(fout, "c  Problem %2ld input parameters\n", problem);
	fprintf(fout, "c  ---------------------------\n");
	fprintf(fout, "c   Random seed:          %10ld\n",   seed);
	fprintf(fout, "c   Number of nodes:      %10ld\n",   NODES);
	fprintf(fout, "c   Source nodes:         %10ld\n",   SOURCES);
	fprintf(fout, "c   Sink nodes:           %10ld\n",   SINKS);
	fprintf(fout, "c   Number of arcs:       %10ld\n",   DENSITY);
	fprintf(fout, "c   Minimum arc cost:     %10ld\n",   MINCOST);
	fprintf(fout, "c   Maximum arc cost:     %10ld\n",   MAXCOST);
	fprintf(fout, "c   Total supply:         %10ld\n",   SUPPLY);
	fprintf(fout, "c   Transshipment -\n");
	fprintf(fout, "c     Sources:            %10ld\n",   TSOURCES);
	fprintf(fout, "c     Sinks:              %10ld\n",   TSINKS);
	fprintf(fout, "c   Skeleton arcs -\n");
	fprintf(fout, "c     With max cost:      %10ld%%\n", HICOST);
	fprintf(fout, "c     Capacitated:        %10ld%%\n", CAPACITATED);
	fprintf(fout, "c   Minimum arc capacity: %10ld\n",   MINCAP);
	fprintf(fout, "c   Maximum arc capacity: %10ld\n",   MAXCAP);

	/* Generate Network */
	if((arcs = netgen(seed, parms)) < 0) {
		error_exit(arcs);
	}

	/* Print Network */
	if((SOURCES - TSOURCES) + (SINKS - TSINKS) == NODES && (SOURCES - TSOURCES) == (SINKS - TSINKS) && SOURCES == SUPPLY) {
		fprintf(fout, "c\n");
		fprintf(fout, "c  *** Assignment ***\n");
		fprintf(fout, "c\n");
		fprintf(fout, "p asn %ld %ld\n", NODES, arcs);
		for(i = 0; i < NODES; i++) {
			if(B[i] > 0) {
				fprintf(fout, "n %ld\n", (long) (i + 1));
			}
		}
		for(i = 0; i < arcs; i++) {
			fprintf(fout, "a %ld %ld %ld\n", FROM[i], TO[i], C[i]);
		}	
	} else if (MINCOST == 1 && MAXCOST == 1) {
		fprintf(fout, "c\n");
		fprintf(fout, "c  *** Maximum flow ***\n");
		fprintf(fout, "c\n");
		fprintf(fout, "p max %ld %ld\n", NODES, arcs);
		for(i = 0; i < NODES; i++) {
			if(B[i] > 0) {
				fprintf(fout, "n %ld s\n", (long) (i + 1));
			} else if(B[i] < 0) {
				fprintf(fout, "n %ld t\n", (long) (i + 1));
			}
		}
		for(i = 0; i < arcs; i++) {
			fprintf(fout, "a %ld %ld %ld\n", FROM[i], TO[i], U[i]);
		}
	} else {
		fprintf(fout, "c\n");
		fprintf(fout, "c  *** Minimum cost flow ***\n");
		fprintf(fout, "c\n");
		fprintf(fout, "p min %ld %ld\n", NODES, arcs);
		for(i = 0; i < NODES; i++) {
			if(B[i] != 0) {
				fprintf(fout, "n %ld %ld\n", (long) (i + 1), B[i]);
			}
		}
		for(i = 0; i < arcs; i++) {
			fprintf(fout, "a %ld %ld %ld %ld %ld\n", FROM[i], TO[i], (long) 0, U[i], C[i]);
		}
	}
	
TERMINATE:

	fclose(fout);
	exit(EXIT_SUCCESS);
} /* END OF MAIN */
Esempio n. 18
0
int check_content_type(struct sip_msg *msg)
{
	static unsigned int appl[16] = {
		0x6c707061/*appl*/,0x6c707041/*Appl*/,0x6c705061/*aPpl*/,
		0x6c705041/*APpl*/,0x6c507061/*apPl*/,0x6c507041/*ApPl*/,
		0x6c505061/*aPPl*/,0x6c505041/*APPl*/,0x4c707061/*appL*/,
		0x4c707041/*AppL*/,0x4c705061/*aPpL*/,0x4c705041/*APpL*/,
		0x4c507061/*apPL*/,0x4c507041/*ApPL*/,0x4c505061/*aPPL*/,
		0x4c505041/*APPL*/};
	static unsigned int icat[16] = {
		0x74616369/*icat*/,0x74616349/*Icat*/,0x74614369/*iCat*/,
		0x74614349/*ICat*/,0x74416369/*icAt*/,0x74416349/*IcAt*/,
		0x74414369/*iCAt*/,0x74414349/*ICAt*/,0x54616369/*icaT*/,
		0x54616349/*IcaT*/,0x54614369/*iCaT*/,0x54614349/*ICaT*/,
		0x54416369/*icAT*/,0x54416349/*IcAT*/,0x54414369/*iCAT*/,
		0x54414349/*ICAT*/};
	static unsigned int ion_[8] = {
		0x006e6f69/*ion_*/,0x006e6f49/*Ion_*/,0x006e4f69/*iOn_*/,
		0x006e4f49/*IOn_*/,0x004e6f69/*ioN_*/,0x004e6f49/*IoN_*/,
		0x004e4f69/*iON_*/,0x004e4f49/*ION_*/};
	static unsigned int sdp_[8] = {
		0x00706473/*sdp_*/,0x00706453/*Sdp_*/,0x00704473/*sDp_*/,
		0x00704453/*SDp_*/,0x00506473/*sdP_*/,0x00506453/*SdP_*/,
		0x00504473/*sDP_*/,0x00504453/*SDP_*/};
	str           str_type;
	unsigned int  x;
	char          *p;

	if (!msg->content_type)
	{
		LM_WARN("the header Content-TYPE is absent!"
			"let's assume the content is text/plain ;-)\n");
		return 1;
	}

	trim_len(str_type.len,str_type.s,msg->content_type->body);
	p = str_type.s;
	advance(p,4,str_type,error_1);
	x = READ(p-4);
	if (!one_of_16(x,appl))
		goto other;
	advance(p,4,str_type,error_1);
	x = READ(p-4);
	if (!one_of_16(x,icat))
		goto other;
	advance(p,3,str_type,error_1);
	x = READ(p-3) & 0x00ffffff;
	if (!one_of_8(x,ion_))
		goto other;

	/* skip spaces and tabs if any */
	while (*p==' ' || *p=='\t')
		advance(p,1,str_type,error_1);
	if (*p!='/')
	{
		LM_ERR("no / found after primary type\n");
		goto error;
	}
	advance(p,1,str_type,error_1);
	while ((*p==' ' || *p=='\t') && p+1<str_type.s+str_type.len)
		advance(p,1,str_type,error_1);

	advance(p,3,str_type,error_1);
	x = READ(p-3) & 0x00ffffff;
	if (!one_of_8(x,sdp_))
		goto other;

	if (*p==';'||*p==' '||*p=='\t'||*p=='\n'||*p=='\r'||*p==0) {
		LM_DBG("type <%.*s> found valid\n", (int)(p-str_type.s), str_type.s);
		return 1;
	} else {
		LM_ERR("bad end for type!\n");
		return -1;
	}

error_1:
	LM_ERR("body ended :-(!\n");
error:
	return -1;
other:
	LM_ERR("invalid type for a message\n");
	return -1;
}
BYTE8 CPURead(WORD16 address) {
	WORD16 _MA = MA;BYTE8 _MB = MB;BYTE8 result;
	MA = address;READ();result = MB;
	MA = _MA;MB = _MB;
	return result;
}
Esempio n. 20
0
void
fbBltOne(FbStip * src, FbStride srcStride,      /* FbStip units per scanline */
         int srcX,              /* bit position of source */
         FbBits * dst, FbStride dstStride,      /* FbBits units per scanline */
         int dstX,              /* bit position of dest */
         int dstBpp,            /* bits per destination unit */
         int width,             /* width in bits of destination */
         int height,            /* height in scanlines */
         FbBits fgand,          /* rrop values */
         FbBits fgxor, FbBits bgand, FbBits bgxor)
{
    const FbBits *fbBits;
    FbBits *srcEnd;
    int pixelsPerDst;           /* dst pixels per FbBits */
    int unitsPerSrc;            /* src patterns per FbStip */
    int leftShift, rightShift;  /* align source with dest */
    FbBits startmask, endmask;  /* dest scanline masks */
    FbStip bits = 0, bitsLeft, bitsRight;       /* source bits */
    FbStip left;
    FbBits mask;
    int nDst;                   /* dest longwords (w.o. end) */
    int w;
    int n, nmiddle;
    int dstS;                   /* stipple-relative dst X coordinate */
    Bool copy;                  /* accelerate dest-invariant */
    Bool transparent;           /* accelerate 0 nop */
    int srcinc;                 /* source units consumed */
    Bool endNeedsLoad = FALSE;  /* need load for endmask */
    CARD8 *fbLane;
    int startbyte, endbyte;

    if (dstBpp == 24) {
        fbBltOne24(src, srcStride, srcX,
                   dst, dstStride, dstX, dstBpp,
                   width, height, fgand, fgxor, bgand, bgxor);
        return;
    }

    /*
     * Do not read past the end of the buffer!
     */
    srcEnd = src + height * srcStride;

    /*
     * Number of destination units in FbBits == number of stipple pixels
     * used each time
     */
    pixelsPerDst = FB_UNIT / dstBpp;

    /*
     * Number of source stipple patterns in FbStip 
     */
    unitsPerSrc = FB_STIP_UNIT / pixelsPerDst;

    copy = FALSE;
    transparent = FALSE;
    if (bgand == 0 && fgand == 0)
        copy = TRUE;
    else if (bgand == FB_ALLONES && bgxor == 0)
        transparent = TRUE;

    /*
     * Adjust source and dest to nearest FbBits boundary
     */
    src += srcX >> FB_STIP_SHIFT;
    dst += dstX >> FB_SHIFT;
    srcX &= FB_STIP_MASK;
    dstX &= FB_MASK;

    FbMaskBitsBytes(dstX, width, copy,
                    startmask, startbyte, nmiddle, endmask, endbyte);

    /*
     * Compute effective dest alignment requirement for
     * source -- must align source to dest unit boundary
     */
    dstS = dstX / dstBpp;
    /*
     * Compute shift constants for effective alignement
     */
    if (srcX >= dstS) {
        leftShift = srcX - dstS;
        rightShift = FB_STIP_UNIT - leftShift;
    }
    else {
        rightShift = dstS - srcX;
        leftShift = FB_STIP_UNIT - rightShift;
    }
    /*
     * Get pointer to stipple mask array for this depth
     */
    fbBits = 0;                 /* unused */
    if (pixelsPerDst <= 8)
        fbBits = fbStippleTable[pixelsPerDst];
    fbLane = 0;
    if (transparent && fgand == 0 && dstBpp >= 8)
        fbLane = fbLaneTable[dstBpp];

    /*
     * Compute total number of destination words written, but 
     * don't count endmask 
     */
    nDst = nmiddle;
    if (startmask)
        nDst++;

    dstStride -= nDst;

    /*
     * Compute total number of source words consumed
     */

    srcinc = (nDst + unitsPerSrc - 1) / unitsPerSrc;

    if (srcX > dstS)
        srcinc++;
    if (endmask) {
        endNeedsLoad = nDst % unitsPerSrc == 0;
        if (endNeedsLoad)
            srcinc++;
    }

    srcStride -= srcinc;

    /*
     * Copy rectangle
     */
    while (height--) {
        w = nDst;               /* total units across scanline */
        n = unitsPerSrc;        /* units avail in single stipple */
        if (n > w)
            n = w;

        bitsLeft = 0;
        if (srcX > dstS)
            bitsLeft = READ(src++);
        if (n) {
            /*
             * Load first set of stipple bits
             */
            LoadBits;

            /*
             * Consume stipple bits for startmask
             */
            if (startmask) {
#if FB_UNIT > 32
                if (pixelsPerDst == 16)
                    mask = FbStipple16Bits(FbLeftStipBits(bits, 16));
                else
#endif
                    mask = fbBits[FbLeftStipBits(bits, pixelsPerDst)];
                if (fbLane) {
                    fbTransparentSpan(dst, mask & startmask, fgxor, 1);
                }
                else {
                    if (mask || !transparent)
                        FbDoLeftMaskByteStippleRRop(dst, mask,
                                                    fgand, fgxor, bgand, bgxor,
                                                    startbyte, startmask);
                }
                bits = FbStipLeft(bits, pixelsPerDst);
                dst++;
                n--;
                w--;
            }
            /*
             * Consume stipple bits across scanline
             */
            for (;;) {
                w -= n;
                if (copy) {
                    while (n--) {
#if FB_UNIT > 32
                        if (pixelsPerDst == 16)
                            mask = FbStipple16Bits(FbLeftStipBits(bits, 16));
                        else
#endif
                            mask = fbBits[FbLeftStipBits(bits, pixelsPerDst)];
                        WRITE(dst, FbOpaqueStipple(mask, fgxor, bgxor));
                        dst++;
                        bits = FbStipLeft(bits, pixelsPerDst);
                    }
                }
                else {
                    if (fbLane) {
                        while (bits && n) {
                            switch (fbLane[FbLeftStipBits(bits, pixelsPerDst)]) {
                                LaneCases((CARD8 *) dst);
                            }
                            bits = FbStipLeft(bits, pixelsPerDst);
                            dst++;
                            n--;
                        }
                        dst += n;
                    }
                    else {
                        while (n--) {
                            left = FbLeftStipBits(bits, pixelsPerDst);
                            if (left || !transparent) {
                                mask = fbBits[left];
                                WRITE(dst, FbStippleRRop(READ(dst), mask,
                                                         fgand, fgxor, bgand,
                                                         bgxor));
                            }
                            dst++;
                            bits = FbStipLeft(bits, pixelsPerDst);
                        }
                    }
                }
                if (!w)
                    break;
                /*
                 * Load another set and reset number of available units
                 */
                LoadBits;
                n = unitsPerSrc;
                if (n > w)
                    n = w;
            }
        }
        /*
         * Consume stipple bits for endmask
         */
        if (endmask) {
            if (endNeedsLoad) {
                LoadBits;
            }
#if FB_UNIT > 32
            if (pixelsPerDst == 16)
                mask = FbStipple16Bits(FbLeftStipBits(bits, 16));
            else
#endif
                mask = fbBits[FbLeftStipBits(bits, pixelsPerDst)];
            if (fbLane) {
                fbTransparentSpan(dst, mask & endmask, fgxor, 1);
            }
            else {
                if (mask || !transparent)
                    FbDoRightMaskByteStippleRRop(dst, mask,
                                                 fgand, fgxor, bgand, bgxor,
                                                 endbyte, endmask);
            }
        }
        dst += dstStride;
        src += srcStride;
    }
}
Esempio n. 21
0
/* Warning: This function is called from interrupt context */
void lcd_buttons_update()
{
#ifdef NEWPANEL
    uint8_t newbutton=0;
    if(READ(BTN_EN1)==0)  newbutton|=EN_A;
    if(READ(BTN_EN2)==0)  newbutton|=EN_B;
    if((blocking_enc<millis()) && (READ(BTN_ENC)==0))
        newbutton |= EN_C;
    buttons = newbutton;
#else   //read it from the shift register
    uint8_t newbutton=0;
    WRITE(SHIFT_LD,LOW);
    WRITE(SHIFT_LD,HIGH);
    unsigned char tmp_buttons=0;
    for(int8_t i=0;i<8;i++)
    { 
        newbutton = newbutton>>1;
        if(READ(SHIFT_OUT))
            newbutton|=(1<<7);
        WRITE(SHIFT_CLK,HIGH);
        WRITE(SHIFT_CLK,LOW);
    }
    buttons=~newbutton; //invert it, because a pressed switch produces a logical 0
#endif//!NEWPANEL

    //manage encoder rotation
    uint8_t enc=0;
    if(buttons&EN_A)
        enc|=(1<<0);
    if(buttons&EN_B)
        enc|=(1<<1);
    if(enc != lastEncoderBits)
    {
        switch(enc)
        {
        case encrot0:
            if(lastEncoderBits==encrot3)
                encoderDiff++;
            else if(lastEncoderBits==encrot1)
                encoderDiff--;
            break;
        case encrot1:
            if(lastEncoderBits==encrot0)
                encoderDiff++;
            else if(lastEncoderBits==encrot2)
                encoderDiff--;
            break;
        case encrot2:
            if(lastEncoderBits==encrot1)
                encoderDiff++;
            else if(lastEncoderBits==encrot3)
                encoderDiff--;
            break;
        case encrot3:
            if(lastEncoderBits==encrot2)
                encoderDiff++;
            else if(lastEncoderBits==encrot0)
                encoderDiff--;
            break;
        }
    }
    lastEncoderBits = enc;
}
Esempio n. 22
0
/*
 * Use deep mask tables that incorporate rotation, pull
 * a variable number of bits out of the stipple and
 * reuse the right bits as needed for the next write
 *
 * Yes, this is probably too much code, but most 24-bpp screens
 * have no acceleration so this code is used for stipples, copyplane
 * and text
 */
void
fbBltOne24(FbStip * srcLine, FbStride srcStride,        /* FbStip units per scanline */
           int srcX,            /* bit position of source */
           FbBits * dst, FbStride dstStride,    /* FbBits units per scanline */
           int dstX,            /* bit position of dest */
           int dstBpp,          /* bits per destination unit */
           int width,           /* width in bits of destination */
           int height,          /* height in scanlines */
           FbBits fgand,        /* rrop values */
           FbBits fgxor, FbBits bgand, FbBits bgxor)
{
    FbStip *src, *srcEnd;
    FbBits leftMask, rightMask, mask;
    int nlMiddle, nl;
    FbStip stip, bits;
    int remain;
    int dstS;
    int firstlen;
    int rot0, rot;
    int nDst;

    /*
     * Do not read past the end of the buffer!
     */
    srcEnd = srcLine + height * srcStride;

    srcLine += srcX >> FB_STIP_SHIFT;
    dst += dstX >> FB_SHIFT;
    srcX &= FB_STIP_MASK;
    dstX &= FB_MASK;
    rot0 = FbFirst24Rot(dstX);

    FbMaskBits(dstX, width, leftMask, nlMiddle, rightMask);

    dstS = (dstX + 23) / 24;
    firstlen = FbStip24Len - dstS;

    nDst = nlMiddle;
    if (leftMask)
        nDst++;
    dstStride -= nDst;

    /* opaque copy */
    if (bgand == 0 && fgand == 0) {
        while (height--) {
            rot = rot0;
            src = srcLine;
            srcLine += srcStride;
            fbInitStipBits(srcX, firstlen, stip);
            if (leftMask) {
                mask = fbStipple24Bits[rot >> 3][stip];
                WRITE(dst, (READ(dst) & ~leftMask) |
                      (FbOpaqueStipple(mask,
                                       FbRot24(fgxor, rot), FbRot24(bgxor, rot))
                       & leftMask));
                dst++;
                fbNextStipBits(rot, stip);
            }
            nl = nlMiddle;
            while (nl--) {
                mask = fbStipple24Bits[rot >> 3][stip];
                WRITE(dst, FbOpaqueStipple(mask,
                                           FbRot24(fgxor, rot),
                                           FbRot24(bgxor, rot)));
                dst++;
                fbNextStipBits(rot, stip);
            }
            if (rightMask) {
                mask = fbStipple24Bits[rot >> 3][stip];
                WRITE(dst, (READ(dst) & ~rightMask) |
                      (FbOpaqueStipple(mask,
                                       FbRot24(fgxor, rot), FbRot24(bgxor, rot))
                       & rightMask));
            }
            dst += dstStride;
            src += srcStride;
        }
    }
    /* transparent copy */
    else if (bgand == FB_ALLONES && bgxor == 0 && fgand == 0) {
Esempio n. 23
0
/******************************************************************************
 This routine should be called before any attempt to read an image.
 Note it is assumed the Image desc. header has been read.
******************************************************************************/
int
DGifGetImageDesc(GifFileType *GifFile)
{
    unsigned int BitsPerPixel;
    GifByteType Buf[3];
    GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
    SavedImage *sp;

    if (!IS_READABLE(Private)) {
        /* This file was NOT open for reading: */
        GifFile->Error = D_GIF_ERR_NOT_READABLE;
        return GIF_ERROR;
    }

    if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
        DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
        DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
        DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
        return GIF_ERROR;
    if (READ(GifFile, Buf, 1) != 1) {
        GifFile->Error = D_GIF_ERR_READ_FAILED;
	GifFreeMapObject(GifFile->Image.ColorMap);
	GifFile->Image.ColorMap = NULL;
        return GIF_ERROR;
    }
    BitsPerPixel = (Buf[0] & 0x07) + 1;
    GifFile->Image.Interlace = (Buf[0] & 0x40) ? true : false;

    /* Setup the colormap */
    if (GifFile->Image.ColorMap) {
        GifFreeMapObject(GifFile->Image.ColorMap);
        GifFile->Image.ColorMap = NULL;
    }
    /* Does this image have local color map? */
    if (Buf[0] & 0x80) {
	unsigned int i;

        GifFile->Image.ColorMap = GifMakeMapObject(1 << BitsPerPixel, NULL);
        if (GifFile->Image.ColorMap == NULL) {
            GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }

        /* Get the image local color map: */
        for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
	    /* coverity[check_return] */
            if (READ(GifFile, Buf, 3) != 3) {
                GifFreeMapObject(GifFile->Image.ColorMap);
                GifFile->Error = D_GIF_ERR_READ_FAILED;
                GifFile->Image.ColorMap = NULL;
                return GIF_ERROR;
            }
            GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
            GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
            GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
        }
    }

    if (GifFile->SavedImages) {
        SavedImage* new_saved_images =
            (SavedImage *)reallocarray(GifFile->SavedImages,
                            (GifFile->ImageCount + 1), sizeof(SavedImage));
        if (new_saved_images == NULL) {
            GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
        GifFile->SavedImages = new_saved_images;
    } else {
        if ((GifFile->SavedImages =
             (SavedImage *) malloc(sizeof(SavedImage))) == NULL) {
            GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
    }

    sp = &GifFile->SavedImages[GifFile->ImageCount];
    memcpy(&sp->ImageDesc, &GifFile->Image, sizeof(GifImageDesc));
    if (GifFile->Image.ColorMap != NULL) {
        sp->ImageDesc.ColorMap = GifMakeMapObject(
                                 GifFile->Image.ColorMap->ColorCount,
                                 GifFile->Image.ColorMap->Colors);
        if (sp->ImageDesc.ColorMap == NULL) {
            GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
            return GIF_ERROR;
        }
    }
    sp->RasterBits = (unsigned char *)NULL;
    sp->ExtensionBlockCount = 0;
    sp->ExtensionBlocks = (ExtensionBlock *) NULL;

    GifFile->ImageCount++;

    Private->PixelCount = (long)GifFile->Image.Width *
       (long)GifFile->Image.Height;

    /* Reset decompress algorithm parameters. */
    return DGifSetupDecompress(GifFile);
}
Esempio n. 24
0
void generateMap(string id) {
    srand(1);

    int n, l, m, s;
    READ(cin, n);
    READ(cin, l);
    READ(cin, m);
    READ(cin, s);

    vector<string> aname(n * l);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < l; j++) {
            READ_FRAG(cin, j, aname[i * l + j]);
        }
        READ_DONE();
    }

    int newL, newM, newS, tagNumber;
    READ(cin, newL);
    READ(cin, newM);
    READ(cin, newS);
    READ(cin, tagNumber);

    vector<string> nodeNameList;
    vector<string> nodeTagList;
    for (int j = 0; j < newM; j++) {
        string nodeName;
        READ_FRAG(cin, 0, nodeName);
        nodeNameList.push_back(nodeName);
        for (int i = 0; i < tagNumber; i++) {
            string nodeTag;
            READ_FRAG(cin, i+1, nodeTag);
            nodeTagList.push_back(nodeTag);
        }
        READ_DONE();
    }

    fixOldData(n, l, m, s, aname);
    fixNewData(n, newL, newM, newS, tagNumber, nodeNameList, nodeTagList);

    if (!validate(n, l, m, s)) {
        DIAG("ERROR: existing mapping failed validation" << endl);
        throw "Validation failure";
    }

    if (!validate(n, newL, newM, newS) || !validate(newM, nodeNameList, tagNumber, nodeTagList)) {
        DIAG("ERROR: new mapping failed validation" << endl);
        throw "Validation failure";
    }

    if (!IsInRow(nodeNameList, _NULL_NODE_NAME)) {
        nodeNameList.insert(nodeNameList.begin(), _NULL_NODE_NAME);
        for (int i = 0; i < tagNumber; i++) {
            nodeTagList.insert(nodeTagList.begin(), "");
        }
    }

    Mapping map0(n, l, m, s);
    map0.InitMapping(aname);

    vector<int> TagPrice(tagNumber,0);
    for (int i = 0; i < tagNumber; i++) {
        TagPrice[i] = 10;  // default to 10 for now
    }

    stack<int> addedNode;
    for (int j = 1; j <= newM; ++j ) {
        if (!IsInRow(map0.nodeNameList, nodeNameList[j])) {
            addedNode.push(j);
        }
    }
    // Deleted nodes map to zero, used for computing lower bound
    vector<int> oldNode2NewZero(map0.M + 1, 0);
    // Deleted nodes map to added nodes if possible
    // Used for initialize a search for RI
    vector<int> oldNode2NewMatch(map0.M + 1, 0);
    string currentNode;
    bool nodeFound;
    for (int i = 1; i <= map0.M; i++) {
        currentNode = map0.nodeNameList[i];
        nodeFound = 0;
        for (int j = 0; j <= newM; ++j ) {
            if (!currentNode.compare(nodeNameList[j])) {
                nodeFound = 1;
                oldNode2NewMatch[i] = j;
                oldNode2NewZero[i] = j;
                break;
            }
        }
        if (!nodeFound) {
            if (!addedNode.empty() ) {
                oldNode2NewMatch[i] = addedNode.top();
                addedNode.pop();
            }
        }
    }

    Mapping map1(map0.N, newL, newM, newS);
    map1.nodeNameList.swap(nodeNameList);
    map1.nodeTagList.swap(nodeTagList);
    map1.Rebalance(map0, oldNode2NewMatch, TagPrice);
    map1.nodeTagNumber = tagNumber;
    int LowerBound = map1.RebalanceLowerBound(map0, oldNode2NewZero, TagPrice);

    if (map1.imbalance)
        DIAG("WARNING : Output mapping has imbalance of " << map1.imbalance << "\n\n");

    DIAG("\nRebalance completed.\nNode number : " << map0.M << " ---> " << map1.M);
    DIAG("\nMove count (index/non-index) : " << map1.MoveCount(map0, 1) << " / ");
    DIAG(map1.MoveCount(map0, 0) << "\tLower bound : " << LowerBound);
    DIAG("\n\nSame tags replication :\nPrice : \t");

    vector<int> sameTagCount;
    map1.CheckTags(sameTagCount);
    for (int i = 0; i < map1.nodeTagNumber; i++) {
        DIAG(TagPrice[i] << '\t');
    }
    DIAG("\nCount : \t");
    for (int i = 0; i < map1.nodeTagNumber; i++) {
        DIAG(sameTagCount[i] << '\t');
    }
    DIAG(endl);

    ostringstream mapout;
    map1.PrintAname(mapout);
    WRITE(cout, mapout.str() << endl);
}
//------------------------------------------------------------------------------
/// Configure DDR
//------------------------------------------------------------------------------
void BOARD_ConfigureDdram(unsigned char ddrModel, unsigned char busWidth)
{    
    AT91PS_HDDRSDRC2 pDdrc = AT91C_BASE_DDR2C;
    volatile unsigned int *pDdr = (unsigned int *) AT91C_DDR2;
    int i;
    volatile unsigned int cr = 0;
    unsigned short ddrc_dbw = 0;

    switch (busWidth) {
        case 16:
        default:
            ddrc_dbw = AT91C_DDRC2_DBW_16_BITS;
            break;

        case 32:
            ddrc_dbw = AT91C_DDRC2_DBW_32_BITS;
            break;

    }

    // Enable DDR2 clock x2 in PMC
    WRITE(AT91C_BASE_PMC, PMC_SCER, AT91C_PMC_DDR);


    switch (ddrModel) {

        case DDR_MICRON_MT47H64M8: 

            // Configure the DDR controller
            WRITE(pDdrc, HDDRSDRC2_MDR, ddrc_dbw   |
                                        AT91C_DDRC2_MD_DDR2_SDRAM);     // DDR2

            // Program the DDR Controller
            WRITE(pDdrc, HDDRSDRC2_CR, AT91C_DDRC2_NC_DDR10_SDR9  |     // 10 column bits (1K)
                                       AT91C_DDRC2_NR_14          |     // 14 row bits    (8K)
                                       AT91C_DDRC2_CAS_3          |     // CAS Latency 3
                                       AT91C_DDRC2_DLL_RESET_DISABLED
                                       ); // DLL not reset

            // assume timings for 7.5ns min clock period
            WRITE(pDdrc, HDDRSDRC2_T0PR, AT91C_DDRC2_TRAS_6       |     //  6 * 7.5 = 45   ns
                                         AT91C_DDRC2_TRCD_3       |     //  3 * 7.5 = 22.5 ns
                                         AT91C_DDRC2_TWR_2        |     //  2 * 7.5 = 15   ns
                                         AT91C_DDRC2_TRC_10       |     // 10 * 7.5 = 75   ns
                                         AT91C_DDRC2_TRP_3        |     //  3 * 7.5 = 22.5 ns
                                         AT91C_DDRC2_TRRD_2       |     //  2 * 7.5 = 15   ns
                                         AT91C_DDRC2_TWTR_1       |     //  1 clock cycle
                                         AT91C_DDRC2_TMRD_2);           //  2 clock cycles

            // pSDDRC->HDDRSDRC2_T1PR = 0x00000008;
            WRITE(pDdrc, HDDRSDRC2_T1PR, AT91C_DDRC2_TXP_2  |           //  2 * 7.5 = 15 ns
                                         200 << 16          |           // 200 clock cycles, TXSRD: Exit self refresh delay to Read command
                                         27 << 8            |           // 27 * 7.5 = 202 ns TXSNR: Exit self refresh delay to non read command
                                         AT91C_DDRC2_TRFC_19 << 0);     // 19 * 7.5 = 142 ns (must be 140 ns for 1Gb DDR)

            WRITE(pDdrc, HDDRSDRC2_T2PR, AT91C_DDRC2_TRTP_2   |         //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TRPA_2   |         //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TXARDS_7 |         //  7 clock cycles
                                         AT91C_DDRC2_TXARD_2);          //  2 clock cycles

        /*   pSDDRC->HDDRSDRC2_LPR = ( 5 << 16  |  // TXSRD: Exit self refresh delay to Read command */
        /*                          5 <<  8  |  // TXSNR: Exit self refresh delay to non read command */
        /*                          8 <<  0     // TRFC :row cycle delay */
        /*                                     ); */

            // Initialization Step 1 + 2: NOP command -> allow to enable clk
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
 
            // Initialization Step 3 (must wait 200 us) (6 core cycles per iteration, core is at 396MHz: min 13200 loops)
            for (i = 0; i < 13300; i++) {
                asm("    nop");
            }

            // NOP command -> allow to enable cke
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 4: Set All Bank Precharge
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *pDdr = 0;
            
            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 5: Set EMR operation (EMRS2)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x4000000)) = 0;
         
            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 6: Set EMR operation (EMRS3)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x6000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 7: Set EMR operation (EMRS1)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x2000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 8a: enable DLL reset
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_DLL_RESET_ENABLED);
            
            // Initialization Step 8b: reset DLL
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            //*(pDdr) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 9: Set All Bank Precharge
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *(pDdr) = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 11: Set 1st CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }


            // Set 2nd CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 12: disable DLL reset
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_DLL_RESET_ENABLED));

            // Initialization Step 13: Set LMR operation
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0;
         
            // Skip Initialization Step 14 to 17 (not supported by the DDR2 model)

            // Initialization Step 18: Set Normal mode
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NORMAL_CMD);
            *(pDdr) = 0;

            //allow to do calibration of DLL
            // address is used to avoid to corrupt bank 0 (in case of preloaded data) data value does not matter
//          *(pDdr + (2 * ddrBankSizeInWord)) = 0x0000FFFF;

            // WRITE(DDRSDR_BASE + (2*__DDR_BANK_SIZE) + 4, 0x0000FFFF);
            // data value should not matter but needs to set it to 0xaa5555aa to work around issue in HDDRSDRC2
//          *(pDdr + (2 * ddrBankSizeInWord + 4)) = 0xAA5555AA;

            // Set Refresh timer
            WRITE(pDdrc, HDDRSDRC2_RTR, 0x00000410);

            // OK now we are ready to work on the DDRSDR

            // wait for end of calibration
            for (i = 0; i < 500; i++) {
                asm("    nop");
            }

            break;


        case DDR_SAMSUNG_M470T6554EZ3_CE6:

            // Configure the DDR controller
            WRITE(pDdrc, HDDRSDRC2_MDR, ddrc_dbw   |
                                        AT91C_DDRC2_MD_DDR2_SDRAM);     // DDR2

            // Program the DDR Controller
            WRITE(pDdrc, HDDRSDRC2_CR, AT91C_DDRC2_NC_DDR10_SDR9  |     // 10 column bits (1K)
                                       AT91C_DDRC2_NR_13          |     // 13 row bits    (8K)
                                       AT91C_DDRC2_CAS_3          |     // CAS Latency 3
                                       AT91C_DDRC2_DLL_RESET_DISABLED); // DLL not reset

            // assume timings for 7.5ns min clock period
            WRITE(pDdrc, HDDRSDRC2_T0PR, AT91C_DDRC2_TRAS_6       |     //  6 * 7.5 = 45   ns
                                         AT91C_DDRC2_TRCD_3       |     //  3 * 7.5 = 22.5 ns
                                         AT91C_DDRC2_TWR_2        |     //  2 * 7.5 = 15   ns
                                         AT91C_DDRC2_TRC_10       |     // 10 * 7.5 = 75   ns
                                         AT91C_DDRC2_TRP_3        |     //  3 * 7.5 = 22.5 ns
                                         AT91C_DDRC2_TRRD_2       |     //  2 * 7.5 = 15   ns
                                         AT91C_DDRC2_TWTR_1       |     //  1 clock cycle
                                         AT91C_DDRC2_TMRD_2);           //  2 clock cycles

            // pSDDRC->HDDRSDRC2_T1PR = 0x00000008;
            WRITE(pDdrc, HDDRSDRC2_T1PR, AT91C_DDRC2_TXP_2  |           //  2 * 7.5 = 15 ns
                                         200 << 16          |           // 200 clock cycles, TXSRD: Exit self refresh delay to Read command
                                         27 << 8            |           // 27 * 7.5 = 202 ns TXSNR: Exit self refresh delay to non read command
                                         AT91C_DDRC2_TRFC_19 << 0);     // 19 * 7.5 = 142 ns (must be 140 ns for 1Gb DDR)

            WRITE(pDdrc, HDDRSDRC2_T2PR, AT91C_DDRC2_TRTP_2   |         //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TRPA_2   |         //  2 * 7.5 = 15 ns
                                         AT91C_DDRC2_TXARDS_7 |         //  7 clock cycles
                                         AT91C_DDRC2_TXARD_2);          //  2 clock cycles

            /*   pSDDRC->HDDRSDRC2_LPR = ( 5 << 16  |  // TXSRD: Exit self refresh delay to Read command */
            /*                          5 <<  8  |  // TXSNR: Exit self refresh delay to non read command */
            /*                          8 <<  0     // TRFC :row cycle delay */
            /*                                     ); */

            // Initialization Step 1 + 2: NOP command -> allow to enable clk
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;

            // TODO Initialization Step 3 (must wait 200 us) (6 core cycles per iteration, core is at 396MHz: min 13200 loops)
            for (i = 0; i < 13300; i++) {
                asm("    nop");
            }

            // NOP command -> allow to enable cke
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NOP_CMD);
            *pDdr = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 4: Set All Bank Precharge
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *pDdr = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 5: Set EMR operation (EMRS2)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x2000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 6: Set EMR operation (EMRS3)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x3000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 7: Set EMR operation (EMRS1)
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            *((unsigned int *)((unsigned char *)pDdr + 0x1000000)) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 8a: enable DLL reset
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr | AT91C_DDRC2_DLL_RESET_ENABLED);

            // Initialization Step 8b: reset DLL
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_EXT_LMR_CMD);
            //    *(pDdr) = 0;

            // wait 2 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 9: Set All Bank Precharge
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_PRCGALL_CMD);
            *(pDdr) = 0;

            // wait 400 ns min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 11: Set 1st CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }


            // Set 2nd CBR
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_RFSH_CMD);
            *(pDdr) = 0;

            // wait 10 cycles min
            for (i = 0; i < 100; i++) {
                asm("    nop");
            }

            // Initialization Step 12: disable DLL reset
            cr = READ(pDdrc, HDDRSDRC2_CR);
            WRITE(pDdrc, HDDRSDRC2_CR, cr & (~AT91C_DDRC2_DLL_RESET_ENABLED));

            // Initialization Step 13: Set LMR operation
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_LMR_CMD);
            *(pDdr) = 0;

            // Skip Initialization Step 14 to 17 (not supported by the DDR2 model)

            // Initialization Step 18: Set Normal mode
            WRITE(pDdrc, HDDRSDRC2_MR, AT91C_DDRC2_MODE_NORMAL_CMD);
            *(pDdr) = 0;

            //allow to do calibration of DLL
            // address is used to avoid to corrupt bank 0 (in case of preloaded data) data value does not matter
            //    *(pDdr + (2 * ddrBankSizeInWord)) = 0x0000FFFF;

            // WRITE(DDRSDR_BASE + (2*__DDR_BANK_SIZE) + 4, 0x0000FFFF);
            // data value should not matter but needs to set it to 0xaa5555aa to work around issue in HDDRSDRC2
            //    *(pDdr + (2 * ddrBankSizeInWord + 4)) = 0xAA5555AA;

            // Set Refresh timer
            WRITE(pDdrc, HDDRSDRC2_RTR, 0x00000410); // = (64ms/8192)/7.8ns

            // OK now we are ready to work on the DDRSDR

            // wait for end of calibration
            for (i = 0; i < 500; i++) {
                asm("    nop");
            }

            break;


        default:
            break;
    }
}
Esempio n. 26
0
int
ELFNAMEEND(loadfile)(int fd, Elf_Ehdr *elf, u_long *marks, int flags)
{
	Elf_Shdr *shp;
	Elf_Phdr *phdr;
	int i, j;
	ssize_t sz;
	int first;
	Elf_Addr shpp;
	Elf_Addr minp = ~0, maxp = 0, pos = 0, elfp = 0;
	u_long offset = marks[MARK_START];
	ssize_t nr;
	struct __packed {
		Elf_Nhdr	nh;
		uint8_t		name[ELF_NOTE_NETBSD_NAMESZ + 1];
		uint8_t		desc[ELF_NOTE_NETBSD_DESCSZ];
	} note;
	char *shstr = NULL;
	int boot_load_ctf = 1;

	/* some ports dont use the offset */
	(void)&offset;

	internalize_ehdr(elf->e_ident[EI_DATA], elf);

	sz = elf->e_phnum * sizeof(Elf_Phdr);
	phdr = ALLOC(sz);

	if (lseek(fd, elf->e_phoff, SEEK_SET) == -1)  {
		WARN(("lseek phdr"));
		goto freephdr;
	}
	nr = read(fd, phdr, sz);
	if (nr == -1) {
		WARN(("read program headers"));
		goto freephdr;
	}
	if (nr != sz) {
		errno = EIO;
		WARN(("read program headers"));
		goto freephdr;
	}

	for (first = 1, i = 0; i < elf->e_phnum; i++) {
		internalize_phdr(elf->e_ident[EI_DATA], &phdr[i]);

#ifndef MD_LOADSEG /* Allow processor ABI specific segment loads */
#define MD_LOADSEG(a) /*CONSTCOND*/0
#endif
		if (MD_LOADSEG(&phdr[i]))
			goto loadseg;

		if (phdr[i].p_type != PT_LOAD ||
		    (phdr[i].p_flags & (PF_W|PF_X)) == 0)
			continue;

#define IS_TEXT(p)	(p.p_flags & PF_X)
#define IS_DATA(p)	(p.p_flags & PF_W)
#define IS_BSS(p)	(p.p_filesz < p.p_memsz)
		/*
		 * XXX: Assume first address is lowest
		 */
		if ((IS_TEXT(phdr[i]) && (flags & LOAD_TEXT)) ||
		    (IS_DATA(phdr[i]) && (flags & LOAD_DATA))) {

		loadseg:
			if (marks[MARK_DATA] == 0 && IS_DATA(phdr[i]))
				marks[MARK_DATA] = LOADADDR(phdr[i].p_vaddr);

			/* Read in segment. */
			PROGRESS(("%s%lu", first ? "" : "+",
			    (u_long)phdr[i].p_filesz));

			if (lseek(fd, phdr[i].p_offset, SEEK_SET) == -1)  {
				WARN(("lseek text"));
				goto freephdr;
			}
			nr = READ(fd, phdr[i].p_vaddr, phdr[i].p_filesz);
			if (nr == -1) {
				WARN(("read text error"));
				goto freephdr;
			}
			if (nr != (ssize_t)phdr[i].p_filesz) {
				errno = EIO;
				WARN(("read text"));
				goto freephdr;
			}
			first = 0;

		}
		if ((IS_TEXT(phdr[i]) && (flags & (LOAD_TEXT|COUNT_TEXT))) ||
		    (IS_DATA(phdr[i]) && (flags & (LOAD_DATA|COUNT_TEXT)))) {
			pos = phdr[i].p_vaddr;
			if (minp > pos)
				minp = pos;
			pos += phdr[i].p_filesz;
			if (maxp < pos)
				maxp = pos;
		}

		/* Zero out bss. */
		if (IS_BSS(phdr[i]) && (flags & LOAD_BSS)) {
			PROGRESS(("+%lu",
			    (u_long)(phdr[i].p_memsz - phdr[i].p_filesz)));
			BZERO((phdr[i].p_vaddr + phdr[i].p_filesz),
			    phdr[i].p_memsz - phdr[i].p_filesz);
		}
		if (IS_BSS(phdr[i]) && (flags & (LOAD_BSS|COUNT_BSS))) {
			pos += phdr[i].p_memsz - phdr[i].p_filesz;
			if (maxp < pos)
				maxp = pos;
		}
	}
	DEALLOC(phdr, sz);

	/*
	 * Copy the ELF and section headers.
	 */
	maxp = roundup(maxp, ELFROUND);
	if (flags & (LOAD_HDR|COUNT_HDR)) {
		elfp = maxp;
		maxp += sizeof(Elf_Ehdr);
	}

	if (flags & (LOAD_SYM|COUNT_SYM)) {
		if (lseek(fd, elf->e_shoff, SEEK_SET) == -1)  {
			WARN(("lseek section headers"));
			return 1;
		}
		sz = elf->e_shnum * sizeof(Elf_Shdr);

		shp = ALLOC(sz);

		nr = read(fd, shp, sz);
		if (nr == -1) {
			WARN(("read section headers"));
			goto freeshp;
		}
		if (nr != sz) {
			errno = EIO;
			WARN(("read section headers"));
			goto freeshp;
		}

		shpp = maxp;
		maxp += roundup(sz, ELFROUND);

#ifndef _STANDALONE
		/* Internalize the section headers. */
		for (i = 0; i < elf->e_shnum; i++)
			internalize_shdr(elf->e_ident[EI_DATA], &shp[i]);
#endif /* ! _STANDALONE */

		/*
		 * First load the section names section.
		 */
		if (boot_load_ctf && (elf->e_shstrndx != 0)) {
			if (flags & LOAD_SYM) {
				if (lseek(fd, shp[elf->e_shstrndx].sh_offset,
				    SEEK_SET) == -1) {
					WARN(("lseek symbols"));
					goto freeshp;
				}
				nr = READ(fd, maxp,
				    shp[elf->e_shstrndx].sh_size);
				if (nr == -1) {
					WARN(("read symbols"));
					goto freeshp;
				}
				if (nr !=
				    (ssize_t)shp[elf->e_shstrndx].sh_size) {
					errno = EIO;
					WARN(("read symbols"));
					goto freeshp;
				}

				shstr = ALLOC(shp[elf->e_shstrndx].sh_size);
				if (lseek(fd, shp[elf->e_shstrndx].sh_offset,
				    SEEK_SET) == -1) {
					WARN(("lseek symbols"));
					goto freeshp;
				}
				nr = read(fd, shstr,
				    shp[elf->e_shstrndx].sh_size);
				if (nr == -1) {
					WARN(("read symbols"));
					goto freeshp;
				}
			}
			shp[elf->e_shstrndx].sh_offset = maxp - elfp;
			maxp += roundup(shp[elf->e_shstrndx].sh_size, ELFROUND);
		}

		/*
		 * Now load the symbol sections themselves.  Make sure
		 * the sections are aligned. Don't bother with any
		 * string table that isn't referenced by a symbol
		 * table.
		 */
		for (first = 1, i = 0; i < elf->e_shnum; i++) {
		    	if (i == elf->e_shstrndx) {
			    /* already loaded this section */
			    continue;
			}
			switch (shp[i].sh_type) {
			case SHT_PROGBITS:
			    	if (boot_load_ctf && shstr) {
					/* got a CTF section? */
					if (strncmp(".SUNW_ctf",
						    &shstr[shp[i].sh_name],
						    10) == 0) {
					    	goto havesym;
					}
				}

				/* Not loading this, so zero out the offset. */
				shp[i].sh_offset = 0;
			    	break;
			case SHT_STRTAB:
				for (j = 0; j < elf->e_shnum; j++)
					if (shp[j].sh_type == SHT_SYMTAB &&
					    shp[j].sh_link == (unsigned int)i)
						goto havesym;
				/* FALLTHROUGH */
			default:
				/* Not loading this, so zero out the offset. */
				shp[i].sh_offset = 0;
				break;
			havesym:
			case SHT_SYMTAB:
				if (flags & LOAD_SYM) {
					PROGRESS(("%s%ld", first ? " [" : "+",
					    (u_long)shp[i].sh_size));
					if (lseek(fd, shp[i].sh_offset,
					    SEEK_SET) == -1) {
						WARN(("lseek symbols"));
						goto freeshp;
					}
					nr = READ(fd, maxp, shp[i].sh_size);
					if (nr == -1) {
						WARN(("read symbols"));
						goto freeshp;
					}
					if (nr != (ssize_t)shp[i].sh_size) {
						errno = EIO;
						WARN(("read symbols"));
						goto freeshp;
					}
				}
				shp[i].sh_offset = maxp - elfp;
				maxp += roundup(shp[i].sh_size, ELFROUND);
				first = 0;
				break;
			case SHT_NOTE:
				if ((flags & LOAD_NOTE) == 0)
					break;
				if (shp[i].sh_size < sizeof(note)) {
					shp[i].sh_offset = 0;
					break;
				}
				if (lseek(fd, shp[i].sh_offset, SEEK_SET)
				    == -1) {
					WARN(("lseek note"));
					goto freeshp;
				}
				nr = read(fd, &note, sizeof(note));
				if (nr == -1) {
					WARN(("read note"));
					goto freeshp;
				}
				if (note.nh.n_namesz ==
				    ELF_NOTE_NETBSD_NAMESZ &&
				    note.nh.n_descsz ==
				    ELF_NOTE_NETBSD_DESCSZ &&
				    note.nh.n_type ==
				    ELF_NOTE_TYPE_NETBSD_TAG &&
				    memcmp(note.name, ELF_NOTE_NETBSD_NAME,
				    sizeof(note.name)) == 0) {
				    	memcpy(&netbsd_version, &note.desc,
				    	    sizeof(netbsd_version));
				}
				shp[i].sh_offset = 0;
				break;
			}
		}
		if (flags & LOAD_SYM) {
#ifndef _STANDALONE
			/* Externalize the section headers. */
			for (i = 0; i < elf->e_shnum; i++)
				externalize_shdr(elf->e_ident[EI_DATA],
				    &shp[i]);
#endif /* ! _STANDALONE */
			BCOPY(shp, shpp, sz);

			if (first == 0)
				PROGRESS(("]"));
		}
		DEALLOC(shp, sz);
	}
	
	if (shstr) {
	    DEALLOC(shstr, shp[elf->e_shstrndx].sh_size);
	}

	/*
	 * Frob the copied ELF header to give information relative
	 * to elfp.
	 */
	if (flags & LOAD_HDR) {
		elf->e_phoff = 0;
		elf->e_shoff = sizeof(Elf_Ehdr);
		elf->e_phentsize = 0;
		elf->e_phnum = 0;
		externalize_ehdr(elf->e_ident[EI_DATA], elf);
		BCOPY(elf, elfp, sizeof(*elf));
		internalize_ehdr(elf->e_ident[EI_DATA], elf);
	}

	marks[MARK_START] = LOADADDR(minp);
	marks[MARK_ENTRY] = LOADADDR(elf->e_entry);
	/*
	 * Since there can be more than one symbol section in the code
	 * and we need to find strtab too in order to do anything
	 * useful with the symbols, we just pass the whole elf
	 * header back and we let the kernel debugger find the
	 * location and number of symbols by itself.
	 */
	marks[MARK_NSYM] = 1;	/* XXX: Kernel needs >= 0 */
	marks[MARK_SYM] = LOADADDR(elfp);
	marks[MARK_END] = LOADADDR(maxp);
	return 0;
freephdr:
	DEALLOC(phdr, sz);
	return 1;
freeshp:
	DEALLOC(shp, sz);
	return 1;
}
Esempio n. 27
0
/*
 * Parse Supported HF body.
 */
int parse_supported_body(str *body, unsigned int *sup)
{
	register char* p;
	register unsigned int val;
	int len, pos = 0;

	*sup = 0;

	p = body->s;
	len = body->len;

	while (pos < len) {
		/* skip spaces and commas */
		for (; pos < len && IS_DELIM(p); ++pos, ++p);

		val = LOWER_DWORD(READ(p));
		switch (val) {

			/* "path" */
			case _path_:
				if(pos + 4 <= len && IS_DELIM(p+4)) {
					*sup |= F_SUPPORTED_PATH;
					pos += 5; p += 5;
				} else
					goto default_label;
				break;

			/* "gruu" */
			case _gruu_:
				if(pos + 4 <= len && IS_DELIM(p+4)) {
					*sup |= F_SUPPORTED_GRUU;
					pos += 5; p += 5;
				} else
					goto default_label;
				break;

			/* "100rel" */
			case _100r_:
				if ( pos+6 <= len
					 && LOWER_BYTE(*(p+4))=='e' && LOWER_BYTE(*(p+5))=='l'
					 && IS_DELIM(p+6)) {
					*sup |= F_SUPPORTED_100REL;
					pos += SUPPORTED_100REL_LEN + 1;
					p   += SUPPORTED_100REL_LEN + 1;
				} else
					goto default_label;
				break;

			/* "timer" */
			case _time_:
				if ( pos+5 <= len && LOWER_BYTE(*(p+4))=='r'
					 && IS_DELIM(p+5) ) {
					*sup |= F_SUPPORTED_TIMER;
					pos += SUPPORTED_TIMER_LEN + 1;
					p   += SUPPORTED_TIMER_LEN + 1;
				} else
					goto default_label;
				break;

			/* "eventlist" */
			case _even_:
				if ( pos+9 <= len && LOWER_DWORD(READ(p+4))==_tlis_ && LOWER_BYTE(*(p+8))=='t'
					 && IS_DELIM(p+9) ) {
					*sup |= F_SUPPORTED_EVENTLIST;
					pos += SUPPORTED_EVENTLIST_LEN + 1;
					p   += SUPPORTED_EVENTLIST_LEN + 1;
				} else
					goto default_label;
				break;

			/* unknown */
			default:
default_label:
				/* skip element */
				for (; pos < len && !IS_DELIM(p); ++pos, ++p);
				break;
		}
	}

	return 0;
}
void FirmwareTest() {
  ECHO_EM("---------- FIRMWARE TEST --------------");
  ECHO_EM("--------- by MarlinKimbra -------------");
  ECHO_EV(MSG_FWTEST_01);
  ECHO_EV(MSG_FWTEST_02);
  ECHO_EV(MSG_FWTEST_YES_NO);
  serial_answer = ' ';
  while (serial_answer!='y' && serial_answer!='Y' && serial_answer!='n' && serial_answer!='N') {
    serial_answer = MYSERIAL.read();
  }
  if (serial_answer=='y' || serial_answer=='Y') {
    ECHO_EV(MSG_FWTEST_03);

    ECHO_EM(" ");
    ECHO_EM("***** ENDSTOP X *****");
    #if PIN_EXISTS(X_MIN) && (X_HOME_DIR == -1)
      if (!READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP X: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("X ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define X_MIN_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("X");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP X: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("X ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif PIN_EXISTS(X_MAX) && X_HOME_DIR == 1
      if (!READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP X: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("X ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define X_MAX_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("X");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP X: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("X ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif X_HOME_DIR == -1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! X_MIN_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #elif X_HOME_DIR == 1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! X_MAX_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #endif

    ECHO_EM(" ");
    ECHO_EM("***** ENDSTOP Y *****");
    #if PIN_EXISTS(Y_MIN) && Y_HOME_DIR == -1
      if (!READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP Y: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("Y ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define Y_MIN_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("Y");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP Y: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("Y ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif PIN_EXISTS(Y_MAX) && Y_HOME_DIR == 1
      if (!READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP Y: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("Y ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define Y_MAX_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("Y");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP Y: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("Y ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif Y_HOME_DIR == -1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! Y_MIN_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #elif Y_HOME_DIR == 1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! Y_MAX_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #endif

    ECHO_EM(" ");
    ECHO_EM("***** ENDSTOP Z *****");
    #if PIN_EXISTS(Z_MIN) && Z_HOME_DIR == -1
      if (!READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP Z: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("Z ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define Z_MIN_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("Z");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING) {
        ECHO_M("MIN ENDSTOP Z: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("Z ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif PIN_EXISTS(Z_MAX) && Z_HOME_DIR == 1
      if (!READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP Z: ");
        ECHO_EV(MSG_ENDSTOP_OPEN);
      }
      else {
        ECHO_M("Z ENDSTOP ");
        ECHO_EM(MSG_FWTEST_ERROR);
        ECHO_M(MSG_FWTEST_INVERT);
        ECHO_M("#define Z_MAX_ENDSTOP_LOGIC ");
        ECHO_M(MSG_FWTEST_INTO);
        #if MECH(CARTESIAN)
          ECHO_EM("Configuration_Cartesian.h");
        #elif MECH(COREXY)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(COREXZ)
          ECHO_EM("Configuration_Core.h");
        #elif MECH(DELTA)
          ECHO_EM("Configuration_Delta.h");
        #elif MECH(SCARA)
          ECHO_EM("Configuration_Scara.h");
        #endif
        return;
      }
      ECHO_V(MSG_FWTEST_PRESS);
      ECHO_EM("Z");
      ECHO_EV(MSG_FWTEST_YES);
      serial_answer = ' ';
      while (serial_answer!='y' && serial_answer!='Y' && !(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING)) {
        serial_answer = MYSERIAL.read();
      }
      if (READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING) {
        ECHO_M("MAX ENDSTOP Z: ");
        ECHO_EV(MSG_ENDSTOP_HIT);
      }
      else {
        ECHO_M("Z ");
        ECHO_EV(MSG_FWTEST_ENDSTOP_ERR);
        return;
      }
    #elif Z_HOME_DIR == -1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! Z_MIN_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #elif Z_HOME_DIR == 1
      ECHO_M(MSG_FWTEST_ERROR);
      ECHO_M("!!! Z_MAX_PIN ");
      ECHO_EM(MSG_FWTEST_NDEF);
      return;
    #endif

    ECHO_EM("ENDSTOP ");
    ECHO_M(MSG_FWTEST_OK);
    ECHO_EM(" ");
  }

  #if HAS(POWER_SWITCH)
    SET_OUTPUT(PS_ON_PIN);
    WRITE(PS_ON_PIN, PS_ON_AWAKE);
  #endif

  // Reset position to 0
  st_synchronize();
  for (int8_t i = 0; i < NUM_AXIS; i++) current_position[i] = 0;
  plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);

  ECHO_EM("***** TEST MOTOR  *****");
  ECHO_EV(MSG_FWTEST_ATTENTION);
  ECHO_EV(MSG_FWTEST_YES);
  serial_answer = ' ';
  while (serial_answer!='y' && serial_answer!='Y') {
    serial_answer = MYSERIAL.read();
  }
  ECHO_EV(MSG_FWTEST_04);
  ECHO_EM(" ");
  ECHO_EM("***** MOTOR X *****");
  destination[X_AXIS] = 10;
  prepare_move();
  st_synchronize();

  ECHO_EV(MSG_FWTEST_XAXIS);
  ECHO_EV(MSG_FWTEST_YES_NO);
  serial_answer = ' ';
  while (serial_answer!='y' && serial_answer!='Y' && serial_answer!='n' && serial_answer!='N') {
    serial_answer = MYSERIAL.read();
  }
  if (serial_answer=='y' || serial_answer=='Y') {
    ECHO_EM("MOTOR X ");
    ECHO_M(MSG_FWTEST_OK);
  }
  else {
    ECHO_M(MSG_FWTEST_INVERT);
    ECHO_M("#define INVERT_X_DIR ");
    ECHO_M(MSG_FWTEST_INTO);
    #if MECH(CARTESIAN)
      ECHO_EM("Configuration_Cartesian.h");
    #elif MECH(COREXY)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(COREXZ)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(DELTA)
      ECHO_EM("Configuration_Delta.h");
    #elif MECH(SCARA)
      ECHO_EM("Configuration_Scara.h");
    #endif
    return;
  }
  ECHO_EM(" ");
  ECHO_EM("***** MOTOR Y *****");
  destination[Y_AXIS] = 10;
  prepare_move();
  st_synchronize();
  ECHO_EV(MSG_FWTEST_YAXIS);
  ECHO_EV(MSG_FWTEST_YES_NO);
  serial_answer = ' ';
  while (serial_answer!='y' && serial_answer!='Y' && serial_answer!='n' && serial_answer!='N') {
    serial_answer = MYSERIAL.read();
  }
  if (serial_answer=='y' || serial_answer=='Y') {
    ECHO_EM("MOTOR Y ");
    ECHO_M(MSG_FWTEST_OK);
  }
  else {
    ECHO_M(MSG_FWTEST_INVERT);
    ECHO_M("#define INVERT_Y_DIR ");
    ECHO_M(MSG_FWTEST_INTO);
    #if MECH(CARTESIAN)
      ECHO_EM("Configuration_Cartesian.h");
    #elif MECH(COREXY)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(COREXZ)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(DELTA)
      ECHO_EM("Configuration_Delta.h");
    #elif MECH(SCARA)
      ECHO_EM("Configuration_Scara.h");
    #endif
    return;
  }
  ECHO_EM(" ");
  ECHO_EM("***** MOTOR Z *****");
  destination[Z_AXIS] = 10;
  prepare_move();
  st_synchronize();
  ECHO_EV(MSG_FWTEST_ZAXIS);
  ECHO_EV(MSG_FWTEST_YES_NO);
  serial_answer = ' ';
  while (serial_answer!='y' && serial_answer!='Y' && serial_answer!='n' && serial_answer!='N') {
    serial_answer = MYSERIAL.read();
  }
  if (serial_answer=='y' || serial_answer=='Y') {
    ECHO_EM("MOTOR Z ");
    ECHO_M(MSG_FWTEST_OK);
  }
  else {
    ECHO_M(MSG_FWTEST_INVERT);
    ECHO_M("#define INVERT_Z_DIR ");
    ECHO_M(MSG_FWTEST_INTO);
    #if MECH(CARTESIAN)
      ECHO_EM("Configuration_Cartesian.h");
    #elif MECH(COREXY)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(COREXZ)
      ECHO_EM("Configuration_Core.h");
    #elif MECH(DELTA)
      ECHO_EM("Configuration_Delta.h");
    #elif MECH(SCARA)
      ECHO_EM("Configuration_Scara.h");
    #endif
    return;
  }
  ECHO_EM("MOTOR ");
  ECHO_M(MSG_FWTEST_OK);
  ECHO_EM(" ");
  ECHO_V(MSG_FWTEST_END);
}
Esempio n. 29
0
// ////////////////////////////////////////////////////////////////////////////
// load keymaps from registry.
bool loadKeyMap(void)
{
	KEY_STATUS	status;
	KEY_CODE	metaCode;
	KEY_CODE	subCode;
	KEY_ACTION	action;
	char		name[128];
	SDWORD		count;
	UDWORD		funcmap;
	char		ver[8];
	PHYSFS_file *pfile;
	PHYSFS_sint64 filesize;
	PHYSFS_sint64 countsize = 0;
	PHYSFS_sint64 length_read;

	// throw away any keymaps!!
	keyClearMappings();

	if (!PHYSFS_exists(KeyMapPath))
	{
		debug(LOG_WZ, "%s not found", KeyMapPath);
		return false;
	}
	pfile = PHYSFS_openRead(KeyMapPath);
	if (!pfile)
	{
		// NOTE: Changed to LOG_FATAL, since we want to inform user via pop-up (windows only)
		debug(LOG_FATAL, "loadKeyMap: [directory: %s] %s could not be opened: %s", PHYSFS_getRealDir(KeyMapPath),
			KeyMapPath, PHYSFS_getLastError());
		assert(false);
		return false;
	}
	filesize = PHYSFS_fileLength(pfile);

#define READ(var, size)                                       \
	length_read = PHYSFS_read(pfile, var, 1, size);             \
	countsize += length_read;                                   \
	if (length_read != size) {                                  \
		debug(LOG_FATAL, "loadKeyMap: Reading %s short: %s",      \
		      KeyMapPath, PHYSFS_getLastError());                 \
		assert(false);                                            \
		(void) PHYSFS_close(pfile);                               \
		return false;                                             \
	}

	READ(&count, sizeof(count));
	READ(&ver, 8);	// get version number.

	if (strncmp(ver, keymapVersion, 8) != 0)
	{
		/* If wrong version, create a new one instead. */
		PHYSFS_close(pfile);
		return false;
	}

	for(; count > 0; count--) {
		READ(&name, 128);	// name
		READ(&status, sizeof(KEY_STATUS));	// status
		READ(&metaCode, sizeof(KEY_CODE));	// metakey
		READ(&subCode, sizeof(KEY_CODE));	// subkey
		READ(&action, sizeof(KEY_ACTION));	// action
		READ(&funcmap, sizeof(funcmap));	// function

		// add mapping
		keyAddMapping( status, metaCode, subCode, action, keyMapSaveTable[funcmap],(char*)&name);
	}

	if (!PHYSFS_close(pfile))
	{
		debug(LOG_ERROR, "Error closing %s: %s", KeyMapPath, PHYSFS_getLastError());
		assert(false);
		return false;
	}
	if (countsize != filesize)
	{
		debug(LOG_FATAL, "File size different from bytes read!");
		assert(false);
	}
	return true;
}
Esempio n. 30
0
static void ioparse_regdef( struct regdef *reg )
{
    reg->offset = yytok.v.i;
    reg->numElements = 1;
    reg->numBytes = 0;
    reg->initValue.i = 0;
    reg->flags.maskValue.i = -1;
    unsigned rangeOffset = reg->offset;

    int tok = iolex(TOK_COLON);
    if( tok == TOK_RANGE ) {
        READ(TOK_INTEGER);
        rangeOffset = yytok.v.i;
        if( rangeOffset < reg->offset ) {
            YYPARSE_ERROR( "Range end (0x%x) must be greater than the range start (0x%x)", rangeOffset, reg->offset );
        }
        READ(TOK_COLON);
    } else if( tok != TOK_COLON ) {
        YYPARSE_ERROR( "Expected ':' but was %s\n", TOKEN_NAMES[tok] );
    }
    READ(TOK_IDENTIFIER);
    reg->mode = yymatch(MODE_NAMES, elementsof(MODE_NAMES));
    if( reg->mode == -1 ) {
        YYPARSE_ERROR( "Unknown register mode '%s'", yystrdup() );
    }
    if( reg->mode == REG_MIRROR ) {
        /* Mirror regions have a target range only */
        READ(TOK_INTEGER);
        reg->initValue.i = yytok.v.i;
        reg->type = REG_I8;
        tok = iolex(TOK_RANGE);
        if( tok == TOK_RANGE ) {
            READ(TOK_INTEGER);
            if( yytok.v.i < reg->initValue.i ) {
                YYPARSE_ERROR( "Invalid mirror target range 0x%x..0x%x", reg->initValue.i, yytok.v.i );
            }
            reg->numBytes = yytok.v.i - reg->initValue.i + 1;
            tok = iolex(TOK_STRIDE);
        }
        if( tok == TOK_STRIDE ) {
            READ(TOK_INTEGER);
            reg->stride = yytok.v.i;
            tok = iolex(TOK_ACTION);
        } else {
            reg->stride = reg->numBytes;
        }

        if( tok != TOK_SEMI ) {
            YYPARSE_ERROR( "Expected ; but gut %s", TOKEN_NAMES[tok] );
        }

        if( reg->stride < reg->numBytes ) {
            YYPARSE_ERROR( "Invalid mirror stride: %x is less than block size %x\n", reg->stride, reg->numBytes );
        }

        if( rangeOffset != reg->offset ) {
            reg->numElements *= ((rangeOffset - reg->offset) + reg->stride - 1) / reg->stride;
        }

    } else {
        READ(TOK_IDENTIFIER);
        reg->type = yymatch(TYPE_NAMES, elementsof(TYPE_NAMES));
        if( reg->type == -1 ) {
            YYPARSE_ERROR( "Unknown register type '%s'", yystrdup() );
        }
        reg->numBytes = TYPE_SIZES[reg->type];
        tok = iolex(TOK_IDENTIFIER);
        if( tok == TOK_IDENTIFIER ) {
            reg->name = yystrdup();
            tok = iolex(TOK_ACTION);
        }
        if( tok == TOK_STRING ) {
            reg->description = yytok.v.s;
            tok = iolex(TOK_ACTION);
        }
        if( tok == TOK_LPAREN ) {
            ioparse_regflags(&reg->flags, &reg->numBytes);
            tok = iolex(TOK_ACTION);
        }
        if( tok == TOK_EQUALS ) {
            tok = iolex(TOK_INTEGER);
            if( tok == TOK_UNDEFINED ) {
                reg->initValue.i = 0xDEADBEEFDEADBEEF;
                reg->initUndefined = TRUE;
            } else {
                ioparse_apval(tok, &reg->initValue, &reg->numBytes);
            }
            tok = iolex(TOK_ACTION);
        } else if( reg->type == REG_STRING ) {
            YYPARSE_ERROR( "String declarations must have an initializer (ie = 'abcd')",0 );
        }
        if( tok == TOK_ACTION ) {
            // reg->action = yystrdup();
        } else if( tok != TOK_SEMI ) {
            YYPARSE_ERROR( "Expected ; or {, but got %s", TOKEN_NAMES[tok] );
        }

        if( rangeOffset != reg->offset ) {
            reg->numElements *= ((rangeOffset - reg->offset) + reg->numBytes - 1) / reg->numBytes;
        }
    }

}