Exemplo n.º 1
0
/**
 *****************************************************************************
 * @ingroup dsaPerformance
 *      dsaPerform
 *
 * @description
 *     This function generates all the DSA parameters required to perform a DSA
 *     sign and DSA verify operation. A user defined number of random messages
 *     are generated and signed, then the signature is verified
 *
 *****************************************************************************/
CpaStatus dsaPerform(dsa_test_params_t* setup)
{
    Cpa32U i=0;
    Cpa32U outerLoop = 0;
    CpaBoolean verifyStatus = CPA_TRUE;
    CpaStatus status = CPA_STATUS_SUCCESS;
    /*DSA parameters */
    /*DSA Q parameter, this shall be populated by the hard coded Q at the top
     * of this file */
    CpaFlatBuffer dsaQ = {0};
    /*random number X used to generate Y and Sign R&S */
    CpaFlatBuffer* dsaX = NULL;
    /*DSA P parameter, this shall be populated by the hard coded P at the top
         * of this file */
    CpaFlatBuffer dsaP = {0};
    /*H is used to generate G, H is hard coded to DEFAULT_H_VALUE */
    CpaFlatBuffer dsaH = {0};
    /* DSA G parameter used to generate Y, the signature R&S, and to verify */
    CpaFlatBuffer dsaG = {0};
    /*DSA Y parameter is used in the verification stage */
    CpaFlatBuffer* dsaY = NULL;
    /*K is a random number used in the generation of signature R&S */
    CpaFlatBuffer* dsaK = NULL;
    /*M is the message to be signed */
    CpaFlatBuffer* dsaM = NULL;
    /*R&S is used to store the DSA Signature */
    CpaFlatBuffer* dsaR = NULL;
    CpaFlatBuffer* dsaS = NULL;
    /*Z is the digest of the message in dsaM */
    CpaFlatBuffer* dsaZ = NULL;
    perf_data_t* pDsaData  = NULL;
    /*GCC compiler complains without the double {{}} to init the following
     * structures*/
    CpaCyDsaGParamGenOpData gOpData = {{0, NULL}, {0, NULL}, {0, NULL}};
    CpaCyDsaYParamGenOpData yOpData = {{0}};
    CpaCyDsaRSSignOpData rsOpData = {{0}};
    CpaCyDsaVerifyOpData* verifyOpData = NULL;
    Cpa8U* pDataPtr = NULL;
    Cpa32U sizeOfp = 0;
    Cpa8U* qDataPtr = NULL;
    Cpa32U sizeOfq = 0;
    Cpa32U node = 0;
    CpaCyDsaVerifyCbFunc cbFunc = NULL;

    status = sampleCodeCyGetNode(setup->cyInstanceHandle, &node);
    if(CPA_STATUS_SUCCESS != status)
    {
        PRINT_ERR("Could not determibne node for memory allocation\n");
        return status;
    }
    pDsaData = setup->performanceStats;
    pDsaData->threadReturnStatus = CPA_STATUS_FAIL;
    pDsaData->numOperations = (Cpa64U)setup->numBuffers * setup->numLoops;

    /*check the p and q input len and set the pointers to the data */
    if(MODULUS_1024_BIT / NUM_BITS_IN_BYTE == setup->pLenInBytes &&
            EXPONENT_160_BIT / NUM_BITS_IN_BYTE == setup->qLenInBytes)
    {
        pDataPtr = dsa_1024_160_p;
        qDataPtr = dsa_1024_160_q;
        sizeOfp = sizeof(dsa_1024_160_p);
        sizeOfq = sizeof(dsa_1024_160_q);
    }
    else if(MODULUS_2048_BIT / NUM_BITS_IN_BYTE == setup->pLenInBytes &&
            EXPONENT_224_BIT / NUM_BITS_IN_BYTE == setup->qLenInBytes)
    {
        pDataPtr = dsa_2048_224_p;
        qDataPtr = dsa_2048_224_q;
        sizeOfp = sizeof(dsa_2048_224_p);
        sizeOfq = sizeof(dsa_2048_224_q);
    }
    else if(MODULUS_2048_BIT / NUM_BITS_IN_BYTE == setup->pLenInBytes &&
            EXPONENT_256_BIT / NUM_BITS_IN_BYTE == setup->qLenInBytes)
    {
        pDataPtr = dsa_2048_256_p;
        qDataPtr = dsa_2048_256_q;
        sizeOfp = sizeof(dsa_2048_256_p);
        sizeOfq = sizeof(dsa_2048_256_q);
    }
    else if(MODULUS_3072_BIT / NUM_BITS_IN_BYTE == setup->pLenInBytes &&
            EXPONENT_256_BIT / NUM_BITS_IN_BYTE == setup->qLenInBytes)
    {
        pDataPtr = dsa_3072_256_p;
        qDataPtr = dsa_3072_256_q;
        sizeOfp = sizeof(dsa_3072_256_p);
        sizeOfq = sizeof(dsa_3072_256_q);
    }
    else
    {
        PRINT_ERR("P & Q len not supported\n");
        /*thread status is init to fail so just reutrn fail here*/
        return CPA_STATUS_FAIL;
    }
    /* Completion used in callback */
    sampleCodeSemaphoreInit(&pDsaData->comp, 0);

#define ALLOC_STRUCT(ptr, size) \
do{ \
    ptr = qaeMemAlloc(size * setup->numBuffers); \
    if(NULL == ptr) \
    { \
        PRINT_ERR("Could not allocate memory\n"); \
        FREE_DSA_MEM; \
        return CPA_STATUS_FAIL; \
    } \
    memset(ptr,0,size * setup->numBuffers); \
}while(0)

    /*Allocate all the buffers */
    ALLOC_STRUCT(dsaX, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaY, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaK, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaM, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaR, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaS, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(dsaZ, sizeof(CpaFlatBuffer));
    ALLOC_STRUCT(verifyOpData, sizeof(CpaCyDsaVerifyOpData));
/************************************************************************
 * STAGE 1 Setup up the DSA parameters, generate X, G, Y, K, Z,
 *          generate user defined number of messages to be signed
 *          calculate the digest of the messages
 *          sign all the messages
 *          setup the verification data structure
 **************************************************************************/
    /*set Q */
    ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaQ,
            setup->qLenInBytes, qDataPtr, sizeOfq, FREE_DSA_MEM);

    /*generate X for each buffer */
    for(i=0; i<setup->numBuffers; i++)
    {
        /*Choose X is generated by random method, where 0 < X < Q */
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaX[i],
                setup->qLenInBytes, NULL, 0, FREE_DSA_MEM);
        dsaGenRandom(&dsaX[i], &dsaQ);
    }

    /*set P */
    ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaP,
            setup->pLenInBytes, pDataPtr, sizeOfp, FREE_DSA_MEM);

    /***************************************************************************
     * set genG opData and generate G
     * ************************************************************************/

    /*H is required to genG */
    ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaH,
            setup->pLenInBytes, NULL, 0, FREE_DSA_MEM);
    memset(dsaH.pData, 0, dsaH.dataLenInBytes);
    dsaH.pData[setup->pLenInBytes-1] = DEFAULT_H_VALUE;

    /*allocate space for G */
    ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaG,
            setup->pLenInBytes, NULL, 0, FREE_DSA_MEM);

    /*set opData to generate G */
    gOpData.P.pData = dsaP.pData;
    gOpData.P.dataLenInBytes = dsaP.dataLenInBytes;
    gOpData.Q.pData = dsaQ.pData;
    gOpData.Q.dataLenInBytes = dsaQ.dataLenInBytes;
    gOpData.H.pData = dsaH.pData;
    gOpData.H.dataLenInBytes = dsaH.dataLenInBytes;
    status = dsaGenG(setup->cyInstanceHandle, &gOpData, &dsaG);
    if(CPA_STATUS_SUCCESS != status)
    {
        PRINT_ERR("Failed to generate DSA parameter G\n");
        FREE_DSA_MEM;
        return CPA_STATUS_FAIL;
    }

    /*generate a Y for each buffer */
    for(i=0;i<setup->numBuffers;i++)
    {
        /*set the opData to gen Y */
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaY[i],
                setup->pLenInBytes, NULL, 0, FREE_DSA_MEM);
        yOpData.P.pData = dsaP.pData;
        yOpData.P.dataLenInBytes = dsaP.dataLenInBytes;
        yOpData.G.pData = dsaG.pData;
        yOpData.G.dataLenInBytes = dsaG.dataLenInBytes;
        yOpData.X.pData = dsaX[i].pData;
        yOpData.X.dataLenInBytes = dsaX[i].dataLenInBytes;
        status = dsaGenY(setup->cyInstanceHandle,&yOpData,&dsaY[i]);
        if(CPA_STATUS_SUCCESS != status)
        {
            PRINT_ERR("Error Generating Y for buffer %d\n", i);
            /*free all the pData buffers allocated and Array of pointers
             * allocated */
            FREE_DSA_MEM;
            return CPA_STATUS_FAIL;
        }

        /*Generate a random per-message value K, where 0 < K < Q. */
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaK[i],
                setup->qLenInBytes, NULL, 0, FREE_DSA_MEM);
        dsaGenRandom(&dsaK[i], &dsaQ);

        /*generate a message to sign */
        /*allocate space for message */
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaM[i],
                setup->pLenInBytes, NULL, 0, FREE_DSA_MEM);

        /*allocate space for digest of message */
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaZ[i],
                setup->qLenInBytes, NULL, 0, FREE_DSA_MEM);

        /*generate random message */
        generateRandomData(dsaM[i].pData, dsaM[i].dataLenInBytes);

        /*calculate digest of message */
        status = dsaGenZ(setup->cyInstanceHandle,
                &dsaM[i],
                setup->hashAlg,
                &dsaZ[i]);
        if(CPA_STATUS_SUCCESS != status)
        {
            PRINT_ERR("Error Generating Z for buffer %d\n", i);
            FREE_DSA_MEM;
            return CPA_STATUS_FAIL;
        }

        /*Gen R & S signature */
        rsOpData.G.pData = dsaG.pData;
        rsOpData.G.dataLenInBytes = dsaG.dataLenInBytes;
        rsOpData.K.pData = dsaK[i].pData;
        rsOpData.K.dataLenInBytes = dsaK[i].dataLenInBytes;
        rsOpData.P.pData = dsaP.pData;
        rsOpData.P.dataLenInBytes = dsaP.dataLenInBytes;
        rsOpData.Q.pData = dsaQ.pData;
        rsOpData.Q.dataLenInBytes = dsaQ.dataLenInBytes;
        rsOpData.X.pData = dsaX[i].pData;
        rsOpData.X.dataLenInBytes = dsaX[i].dataLenInBytes;
        rsOpData.Z.pData = dsaZ[i].pData;
        rsOpData.Z.dataLenInBytes = dsaZ[i].dataLenInBytes;
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaR[i],
                setup->qLenInBytes, NULL, 0, FREE_DSA_MEM);
        ALLOC_FLAT_BUFF_DATA(setup->cyInstanceHandle, &dsaS[i],
                setup->qLenInBytes, NULL, 0, FREE_DSA_MEM);
        status = dsaGenRS(setup->cyInstanceHandle,
                &rsOpData,
                &dsaR[i],
                &dsaS[i]);
        if(CPA_STATUS_SUCCESS != status)
        {
            PRINT_ERR("Error Generating R&S for buffer %d\n", i);
            FREE_DSA_MEM;
            return CPA_STATUS_FAIL;
        }

        /*Verify signature */

        verifyOpData[i].P.pData = dsaP.pData;
        verifyOpData[i].P.dataLenInBytes = dsaP.dataLenInBytes;
        verifyOpData[i].Q.pData = dsaQ.pData;
        verifyOpData[i].Q.dataLenInBytes = dsaQ.dataLenInBytes;
        verifyOpData[i].G.pData= dsaG.pData;
        verifyOpData[i].G.dataLenInBytes = dsaG.dataLenInBytes;
        verifyOpData[i].Y.pData= dsaY[i].pData;
        verifyOpData[i].Y.dataLenInBytes = dsaY[i].dataLenInBytes;
        verifyOpData[i].Z.pData= dsaZ[i].pData;
        verifyOpData[i].Z.dataLenInBytes = dsaZ[i].dataLenInBytes;
        verifyOpData[i].R.pData= dsaR[i].pData;
        verifyOpData[i].R.dataLenInBytes = dsaR[i].dataLenInBytes;
        verifyOpData[i].S.pData= dsaS[i].pData;
        verifyOpData[i].S.dataLenInBytes = dsaS[i].dataLenInBytes;
    }
    /*set the callback function if asynchronous mode is set*/
    if(ASYNC == setup->syncMode)
    {
        cbFunc = dsaVerifyCb;
    }


/************************************************************************
 * STAGE 2 repeatedly verify all the signatures and measure the performance
 ************************************************************************* */

    /*this barrier will wait until all threads get to this point */
    sampleCodeBarrier();
    /* get a timestamp before submitting any requests. After submitting
     * all requests a final timestamp is taken in the callback function.
     * These two times and the number of requests submitted are used  to
     * calculate operations per second  */
    pDsaData->startCyclesTimestamp = sampleCodeTimestamp();
    for(outerLoop = 0; outerLoop<setup->numLoops; outerLoop++)
    {
        for(i=0;i<setup->numBuffers;i++)
        {
            do
            {
                status = cpaCyDsaVerify(setup->cyInstanceHandle,
                    cbFunc,
                    pDsaData,
                    &verifyOpData[i],
                    &verifyStatus);
                if(CPA_STATUS_RETRY == status)
                {
                     pDsaData->retries++;
                     /*once we get to many retries, perform a context switch
                      * to give the acceleration engine a small break */
                     if(RETRY_LIMIT == (pDsaData->retries % (RETRY_LIMIT+1)))
                     {
                         AVOID_SOFTLOCKUP;
                     }
                 }
             } while (CPA_STATUS_RETRY == status);
            /*if for some reason the DSA verify returns fail, decrease the
             * numOperations expected in the callback so that the code does not
             * wait forever */
            if(CPA_STATUS_SUCCESS != status)
            {
                PRINT_ERR("DSA Verify function failed with status:%d\n",
                        status);
                break;
            }
        }
        if(CPA_STATUS_SUCCESS != status)
        {
            break;
        }
    }
    if (CPA_STATUS_SUCCESS == status)
    {
        status = waitForResponses(pDsaData, setup->syncMode, setup->numBuffers,
                setup->numLoops);
    }

    /*free Arrays of buffer pointers and pData */
    FREE_DSA_MEM;
    sampleCodeSemaphoreDestroy(&pDsaData->comp);
    pDsaData->threadReturnStatus = status;
    if(CPA_STATUS_SUCCESS != setup->performanceStats->threadReturnStatus)
    {
        status = CPA_STATUS_FAIL;
    }
return status;
}
Exemplo n.º 2
0
/*
 * This function analyses the tape's sense-data in case of a unit-check.
 * If possible, it tries to recover from the error. Else the user is
 * informed about the problem.
 */
static int
tape_34xx_unit_check(struct tape_device *device, struct tape_request *request,
		     struct irb *irb)
{
	int inhibit_cu_recovery;
	__u8* sense;

	inhibit_cu_recovery = (*device->modeset_byte & 0x80) ? 1 : 0;
	sense = irb->ecw;

#ifdef CONFIG_S390_TAPE_BLOCK
	if (request->op == TO_BLOCK) {
		/*
		 * Recovery for block device requests. Set the block_position
		 * to something invalid and retry.
		 */
		device->blk_data.block_position = -1;
		if (request->retries-- <= 0)
			return tape_34xx_erp_failed(request, -EIO);
		else
			return tape_34xx_erp_retry(request);
	}
#endif

	if (
		sense[0] & SENSE_COMMAND_REJECT &&
		sense[1] & SENSE_WRITE_PROTECT
	) {
		if (
			request->op == TO_DSE ||
			request->op == TO_WRI ||
			request->op == TO_WTM
		) {
			/* medium is write protected */
			return tape_34xx_erp_failed(request, -EACCES);
		} else {
			return tape_34xx_erp_bug(device, request, irb, -3);
		}
	}

	/*
	 * Special cases for various tape-states when reaching
	 * end of recorded area
	 *
	 * FIXME: Maybe a special case of the special case:
	 *        sense[0] == SENSE_EQUIPMENT_CHECK &&
	 *        sense[1] == SENSE_DRIVE_ONLINE    &&
	 *        sense[3] == 0x47 (Volume Fenced)
	 *
	 *        This was caused by continued FSF or FSR after an
	 *        'End Of Data'.
	 */
	if ((
		sense[0] == SENSE_DATA_CHECK      ||
		sense[0] == SENSE_EQUIPMENT_CHECK ||
		sense[0] == SENSE_EQUIPMENT_CHECK + SENSE_DEFERRED_UNIT_CHECK
	) && (
		sense[1] == SENSE_DRIVE_ONLINE ||
		sense[1] == SENSE_BEGINNING_OF_TAPE + SENSE_WRITE_MODE
	)) {
		switch (request->op) {
		/*
		 * sense[0] == SENSE_DATA_CHECK   &&
		 * sense[1] == SENSE_DRIVE_ONLINE
		 * sense[3] == 0x36 (End Of Data)
		 *
		 * Further seeks might return a 'Volume Fenced'.
		 */
		case TO_FSF:
		case TO_FSB:
			/* Trying to seek beyond end of recorded area */
			return tape_34xx_erp_failed(request, -ENOSPC);
		case TO_BSB:
			return tape_34xx_erp_retry(request);

		/*
		 * sense[0] == SENSE_DATA_CHECK   &&
		 * sense[1] == SENSE_DRIVE_ONLINE &&
		 * sense[3] == 0x36 (End Of Data)
		 */
		case TO_LBL:
			/* Block could not be located. */
			tape_34xx_delete_sbid_from(device, 0);
			return tape_34xx_erp_failed(request, -EIO);

		case TO_RFO:
			/* Read beyond end of recorded area -> 0 bytes read */
			return tape_34xx_erp_failed(request, 0);

		/*
		 * sense[0] == SENSE_EQUIPMENT_CHECK &&
		 * sense[1] == SENSE_DRIVE_ONLINE    &&
		 * sense[3] == 0x38 (Physical End Of Volume)
		 */
		case TO_WRI:
			/* Writing at physical end of volume */
			return tape_34xx_erp_failed(request, -ENOSPC);
		default:
			PRINT_ERR("Invalid op in %s:%i\n",
				  __FUNCTION__, __LINE__);
			return tape_34xx_erp_failed(request, 0);
		}
	}

	/* Sensing special bits */
	if (sense[0] & SENSE_BUS_OUT_CHECK)
		return tape_34xx_erp_retry(request);

	if (sense[0] & SENSE_DATA_CHECK) {
		/*
		 * hardware failure, damaged tape or improper
		 * operating conditions
		 */
		switch (sense[3]) {
		case 0x23:
			/* a read data check occurred */
			if ((sense[2] & SENSE_TAPE_SYNC_MODE) ||
			    inhibit_cu_recovery)
				// data check is not permanent, may be
				// recovered. We always use async-mode with
				// cu-recovery, so this should *never* happen.
				return tape_34xx_erp_bug(device, request,
							 irb, -4);

			/* data check is permanent, CU recovery has failed */
			PRINT_WARN("Permanent read error\n");
			return tape_34xx_erp_failed(request, -EIO);
		case 0x25:
			// a write data check occurred
			if ((sense[2] & SENSE_TAPE_SYNC_MODE) ||
			    inhibit_cu_recovery)
				// data check is not permanent, may be
				// recovered. We always use async-mode with
				// cu-recovery, so this should *never* happen.
				return tape_34xx_erp_bug(device, request,
							 irb, -5);

			// data check is permanent, cu-recovery has failed
			PRINT_WARN("Permanent write error\n");
			return tape_34xx_erp_failed(request, -EIO);
		case 0x26:
			/* Data Check (read opposite) occurred. */
			return tape_34xx_erp_read_opposite(device, request);
		case 0x28:
			/* ID-Mark at tape start couldn't be written */
			PRINT_WARN("ID-Mark could not be written.\n");
			return tape_34xx_erp_failed(request, -EIO);
		case 0x31:
			/* Tape void. Tried to read beyond end of device. */
			PRINT_WARN("Read beyond end of recorded area.\n");
			return tape_34xx_erp_failed(request, -ENOSPC);
		case 0x41:
			/* Record sequence error. */
			PRINT_WARN("Invalid block-id sequence found.\n");
			return tape_34xx_erp_failed(request, -EIO);
		default:
			/* all data checks for 3480 should result in one of
			 * the above erpa-codes. For 3490, other data-check
			 * conditions do exist. */
			if (device->cdev->id.driver_info == tape_3480)
				return tape_34xx_erp_bug(device, request,
							 irb, -6);
		}
	}

	if (sense[0] & SENSE_OVERRUN)
		return tape_34xx_erp_overrun(device, request, irb);

	if (sense[1] & SENSE_RECORD_SEQUENCE_ERR)
		return tape_34xx_erp_sequence(device, request, irb);

	/* Sensing erpa codes */
	switch (sense[3]) {
	case 0x00:
		/* Unit check with erpa code 0. Report and ignore. */
		PRINT_WARN("Non-error sense was found. "
			   "Unit-check will be ignored.\n");
		return TAPE_IO_SUCCESS;
	case 0x21:
		/*
		 * Data streaming not operational. CU will switch to
		 * interlock mode. Reissue the command.
		 */
		PRINT_WARN("Data streaming not operational. "
			   "Switching to interlock-mode.\n");
		return tape_34xx_erp_retry(request);
	case 0x22:
		/*
		 * Path equipment check. Might be drive adapter error, buffer
		 * error on the lower interface, internal path not usable,
		 * or error during cartridge load.
		 */
		PRINT_WARN("A path equipment check occurred. One of the "
			   "following conditions occurred:\n");
		PRINT_WARN("drive adapter error, buffer error on the lower "
			   "interface, internal path not usable, error "
			   "during cartridge load.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x24:
		/*
		 * Load display check. Load display was command was issued,
		 * but the drive is displaying a drive check message. Can
		 * be threated as "device end".
		 */
		return tape_34xx_erp_succeeded(request);
	case 0x27:
		/*
		 * Command reject. May indicate illegal channel program or
		 * buffer over/underrun. Since all channel programs are
		 * issued by this driver and ought be correct, we assume a
		 * over/underrun situation and retry the channel program.
		 */
		return tape_34xx_erp_retry(request);
	case 0x29:
		/*
		 * Function incompatible. Either the tape is idrc compressed
		 * but the hardware isn't capable to do idrc, or a perform
		 * subsystem func is issued and the CU is not on-line.
		 */
		PRINT_WARN ("Function incompatible. Try to switch off idrc\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x2a:
		/*
		 * Unsolicited environmental data. An internal counter
		 * overflows, we can ignore this and reissue the cmd.
		 */
		return tape_34xx_erp_retry(request);
	case 0x2b:
		/*
		 * Environmental data present. Indicates either unload
		 * completed ok or read buffered log command completed ok.
		 */
		if (request->op == TO_RUN) {
			/* Rewind unload completed ok. */
			tape_med_state_set(device, MS_UNLOADED);
			return tape_34xx_erp_succeeded(request);
		}
		/* tape_34xx doesn't use read buffered log commands. */
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x2c:
		/*
		 * Permanent equipment check. CU has tried recovery, but
		 * did not succeed.
		 */
		return tape_34xx_erp_failed(request, -EIO);
	case 0x2d:
		/* Data security erase failure. */
		if (request->op == TO_DSE)
			return tape_34xx_erp_failed(request, -EIO);
		/* Data security erase failure, but no such command issued. */
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x2e:
		/*
		 * Not capable. This indicates either that the drive fails
		 * reading the format id mark or that that format specified
		 * is not supported by the drive.
		 */
		PRINT_WARN("Drive not capable processing the tape format!\n");
		return tape_34xx_erp_failed(request, -EMEDIUMTYPE);
	case 0x30:
		/* The medium is write protected. */
		PRINT_WARN("Medium is write protected!\n");
		return tape_34xx_erp_failed(request, -EACCES);
	case 0x32:
		// Tension loss. We cannot recover this, it's an I/O error.
		PRINT_WARN("The drive lost tape tension.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x33:
		/*
		 * Load Failure. The cartridge was not inserted correctly or
		 * the tape is not threaded correctly.
		 */
		PRINT_WARN("Cartridge load failure. Reload the cartridge "
			   "and try again.\n");
		tape_34xx_delete_sbid_from(device, 0);
		return tape_34xx_erp_failed(request, -EIO);
	case 0x34:
		/*
		 * Unload failure. The drive cannot maintain tape tension
		 * and control tape movement during an unload operation.
		 */
		PRINT_WARN("Failure during cartridge unload. "
			   "Please try manually.\n");
		if (request->op == TO_RUN)
			return tape_34xx_erp_failed(request, -EIO);
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x35:
		/*
		 * Drive equipment check. One of the following:
		 * - cu cannot recover from a drive detected error
		 * - a check code message is shown on drive display
		 * - the cartridge loader does not respond correctly
		 * - a failure occurs during an index, load, or unload cycle
		 */
		PRINT_WARN("Equipment check! Please check the drive and "
			   "the cartridge loader.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x36:
		if (device->cdev->id.driver_info == tape_3490)
			/* End of data. */
			return tape_34xx_erp_failed(request, -EIO);
		/* This erpa is reserved for 3480 */
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x37:
		/*
		 * Tape length error. The tape is shorter than reported in
		 * the beginning-of-tape data.
		 */
		PRINT_WARN("Tape length error.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x38:
		/*
		 * Physical end of tape. A read/write operation reached
		 * the physical end of tape.
		 */
		if (request->op==TO_WRI ||
		    request->op==TO_DSE ||
		    request->op==TO_WTM)
			return tape_34xx_erp_failed(request, -ENOSPC);
		return tape_34xx_erp_failed(request, -EIO);
	case 0x39:
		/* Backward at Beginning of tape. */
		return tape_34xx_erp_failed(request, -EIO);
	case 0x3a:
		/* Drive switched to not ready. */
		PRINT_WARN("Drive not ready. Turn the ready/not ready switch "
			   "to ready position and try again.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x3b:
		/* Manual rewind or unload. This causes an I/O error. */
		PRINT_WARN("Medium was rewound or unloaded manually.\n");
		tape_34xx_delete_sbid_from(device, 0);
		return tape_34xx_erp_failed(request, -EIO);
	case 0x42:
		/*
		 * Degraded mode. A condition that can cause degraded
		 * performance is detected.
		 */
		PRINT_WARN("Subsystem is running in degraded mode.\n");
		return tape_34xx_erp_retry(request);
	case 0x43:
		/* Drive not ready. */
		tape_34xx_delete_sbid_from(device, 0);
		tape_med_state_set(device, MS_UNLOADED);
		/* Some commands commands are successful even in this case */
		if (sense[1] & SENSE_DRIVE_ONLINE) {
			switch(request->op) {
				case TO_ASSIGN:
				case TO_UNASSIGN:
				case TO_DIS:
				case TO_NOP:
					return tape_34xx_done(request);
					break;
				default:
					break;
			}
		}
		PRINT_WARN("The drive is not ready.\n");
		return tape_34xx_erp_failed(request, -ENOMEDIUM);
	case 0x44:
		/* Locate Block unsuccessful. */
		if (request->op != TO_BLOCK && request->op != TO_LBL)
			/* No locate block was issued. */
			return tape_34xx_erp_bug(device, request,
						 irb, sense[3]);
		return tape_34xx_erp_failed(request, -EIO);
	case 0x45:
		/* The drive is assigned to a different channel path. */
		PRINT_WARN("The drive is assigned elsewhere.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x46:
		/*
		 * Drive not on-line. Drive may be switched offline,
		 * the power supply may be switched off or
		 * the drive address may not be set correctly.
		 */
		PRINT_WARN("The drive is not on-line.");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x47:
		/* Volume fenced. CU reports volume integrity is lost. */
		PRINT_WARN("Volume fenced. The volume integrity is lost.\n");
		tape_34xx_delete_sbid_from(device, 0);
		return tape_34xx_erp_failed(request, -EIO);
	case 0x48:
		/* Log sense data and retry request. */
		return tape_34xx_erp_retry(request);
	case 0x49:
		/* Bus out check. A parity check error on the bus was found. */
		PRINT_WARN("Bus out check. A data transfer over the bus "
			   "has been corrupted.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x4a:
		/* Control unit erp failed. */
		PRINT_WARN("The control unit I/O error recovery failed.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x4b:
		/*
		 * CU and drive incompatible. The drive requests micro-program
		 * patches, which are not available on the CU.
		 */
		PRINT_WARN("The drive needs microprogram patches from the "
			   "control unit, which are not available.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x4c:
		/*
		 * Recovered Check-One failure. Cu develops a hardware error,
		 * but is able to recover.
		 */
		return tape_34xx_erp_retry(request);
	case 0x4d:
		if (device->cdev->id.driver_info == tape_3490)
			/*
			 * Resetting event received. Since the driver does
			 * not support resetting event recovery (which has to
			 * be handled by the I/O Layer), retry our command.
			 */
			return tape_34xx_erp_retry(request);
		/* This erpa is reserved for 3480. */
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x4e:
		if (device->cdev->id.driver_info == tape_3490) {
			/*
			 * Maximum block size exceeded. This indicates, that
			 * the block to be written is larger than allowed for
			 * buffered mode.
			 */
			PRINT_WARN("Maximum block size for buffered "
				   "mode exceeded.\n");
			return tape_34xx_erp_failed(request, -ENOBUFS);
		}
		/* This erpa is reserved for 3480. */
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x50:
		/*
		 * Read buffered log (Overflow). CU is running in extended
		 * buffered log mode, and a counter overflows. This should
		 * never happen, since we're never running in extended
		 * buffered log mode.
		 */
		return tape_34xx_erp_retry(request);
	case 0x51:
		/*
		 * Read buffered log (EOV). EOF processing occurs while the
		 * CU is in extended buffered log mode. This should never
		 * happen, since we're never running in extended buffered
		 * log mode.
		 */
		return tape_34xx_erp_retry(request);
	case 0x52:
		/* End of Volume complete. Rewind unload completed ok. */
		if (request->op == TO_RUN) {
			tape_med_state_set(device, MS_UNLOADED);
			tape_34xx_delete_sbid_from(device, 0);
			return tape_34xx_erp_succeeded(request);
		}
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	case 0x53:
		/* Global command intercept. */
		return tape_34xx_erp_retry(request);
	case 0x54:
		/* Channel interface recovery (temporary). */
		return tape_34xx_erp_retry(request);
	case 0x55:
		/* Channel interface recovery (permanent). */
		PRINT_WARN("A permanent channel interface error occurred.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x56:
		/* Channel protocol error. */
		PRINT_WARN("A channel protocol error occurred.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x57:
		if (device->cdev->id.driver_info == tape_3480) {
			/* Attention intercept. */
			PRINT_WARN("An attention intercept occurred, "
				   "which will be recovered.\n");
			return tape_34xx_erp_retry(request);
		} else {
			/* Global status intercept. */
			PRINT_WARN("An global status intercept was received, "
				   "which will be recovered.\n");
			return tape_34xx_erp_retry(request);
		}
	case 0x5a:
		/*
		 * Tape length incompatible. The tape inserted is too long,
		 * which could cause damage to the tape or the drive.
		 */
		PRINT_WARN("Tape Length Incompatible\n");
		PRINT_WARN("Tape length exceeds IBM enhanced capacity "
			"cartdridge length or a medium\n");
		PRINT_WARN("with EC-CST identification mark has been mounted "
			"in a device that writes\n");
		PRINT_WARN("3480 or 3480 XF format.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x5b:
		/* Format 3480 XF incompatible */
		if (sense[1] & SENSE_BEGINNING_OF_TAPE)
			/* The tape will get overwritten. */
			return tape_34xx_erp_retry(request);
		PRINT_WARN("Format 3480 XF Incompatible\n");
		PRINT_WARN("Medium has been created in 3480 format. "
			"To change the format writes\n");
		PRINT_WARN("must be issued at BOT.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x5c:
		/* Format 3480-2 XF incompatible */
		PRINT_WARN("Format 3480-2 XF Incompatible\n");
		PRINT_WARN("Device can only read 3480 or 3480 XF format.\n");
		return tape_34xx_erp_failed(request, -EIO);
	case 0x5d:
		/* Tape length violation. */
		PRINT_WARN("Tape Length Violation\n");
		PRINT_WARN("The mounted tape exceeds IBM Enhanced Capacity "
			"Cartdridge System Tape length.\n");
		PRINT_WARN("This may cause damage to the drive or tape when "
			"processing to the EOV\n");
		return tape_34xx_erp_failed(request, -EMEDIUMTYPE);
	case 0x5e:
		/* Compaction algorithm incompatible. */
		PRINT_WARN("Compaction Algorithm Incompatible\n");
		PRINT_WARN("The volume is recorded using an incompatible "
			"compaction algorithm,\n");
		PRINT_WARN("which is not supported by the device.\n");
		return tape_34xx_erp_failed(request, -EMEDIUMTYPE);

		/* The following erpas should have been covered earlier. */
	case 0x23: /* Read data check. */
	case 0x25: /* Write data check. */
	case 0x26: /* Data check (read opposite). */
	case 0x28: /* Write id mark check. */
	case 0x31: /* Tape void. */
	case 0x40: /* Overrun error. */
	case 0x41: /* Record sequence error. */
		/* All other erpas are reserved for future use. */
	default:
		return tape_34xx_erp_bug(device, request, irb, sense[3]);
	}
}
static int wifi_gpio_request(struct sdio_wifi_gpio_cfg *gpio)
{
	int rc = 0;

	printk(KERN_ERR "%s:ENTRY\n",__FUNCTION__);

	if(gpio->reserved){
		return rc;
	}

	PRINT_INFO("gpio pins reset:%d, req:%d wake:%d shutdown:%d\n",
	gpio->reset, gpio->reg, gpio->host_wake, gpio->shutdown);

	if (gpio->reg >= 0) {
		rc = gpio_request(gpio->reg, "wl_reg_on");
		if (rc < 0) {
			PRINT_ERR("unable to request reg GPIO pin %d\n",
				  gpio->reg);
			return -EBUSY;
		}
		PRINT_INFO("current value of reg GPIO: %d\n",
			   gpio_get_value(gpio->reg));
		printk(KERN_ERR "%s: REG=%x\n",__FUNCTION__,gpio->reg);
		gpio_direction_output(gpio->reg, 1);
		gpio_set_value(gpio->reg, 1);
	}

	if (gpio->reset >= 0) {
		rc = gpio_request(gpio->reset, "wl_reset");
		if (rc < 0) {
			PRINT_ERR("unable to request reset GPIO pin %d\n",
				  gpio->reset);
			goto err_free_gpio_reg;
		}
		printk(KERN_ERR "%s: RESET=%x\n", __FUNCTION__, gpio->reset);
		PRINT_INFO("current value of reset GPIO: %d\n",
			   gpio_get_value(gpio->reset));
		gpio_direction_output(gpio->reset, 0);
//      gpio_set_value(gpio->reset, 0);
	}

	if (gpio->shutdown >= 0) {
		rc = gpio_request(gpio->shutdown, "wl_shutdown");
		if (rc < 0) {
			PRINT_ERR("unable to request shutdown GPIO pin %d\n",
				  gpio->shutdown);
			goto err_free_gpio_reset;
		}
		printk(KERN_ERR "%s: SHUTDOWN=%x\n", __FUNCTION__,
		       gpio->shutdown);
		PRINT_INFO("current value of shutdown GPIO: %d\n", 
		gpio_get_value(gpio->shutdown));
		gpio_direction_output(gpio->shutdown, 1);
		gpio_set_value(gpio->shutdown, 1);
	}

	if (gpio->host_wake >= 0) {
		rc = gpio_request(gpio->host_wake, "wl_host_wake");
		if (rc < 0) {
			PRINT_ERR("unable to request wake GPIO pin %d\n",
				  gpio->host_wake);
			goto err_free_gpio_shutdown;
		}
		gpio_direction_input(gpio->host_wake);
		rc = irq_set_irq_type(gpio_to_irq(gpio->host_wake),
				      IRQ_TYPE_EDGE_RISING);
		if (rc < 0) {
			PRINT_ERR("unable to set irq type for GPIO pin %d\n",
				  gpio->host_wake);
			goto err_free_gpio_shutdown;
		}
	}
	printk(KERN_ERR "%s: HOST_WAKE=%x\n",__FUNCTION__,gpio->host_wake);

	gpio->reserved = 1;

	return 0;

err_free_gpio_shutdown:
	if (gpio->shutdown >= 0)
		gpio_free(gpio->shutdown);

err_free_gpio_reset:
	if (gpio->reset >= 0)
		gpio_free(gpio->reset);

err_free_gpio_reg:
	if (gpio->reg >= 0)
		gpio_free(gpio->reg);

	return rc;
}
Exemplo n.º 4
0
/**
 * Validate the mesh, \a do_fixes requires \a mesh to be non-null.
 *
 * \return false if no changes needed to be made.
 */
bool BKE_mesh_validate_arrays(Mesh *mesh,
                              MVert *mverts, unsigned int totvert,
                              MEdge *medges, unsigned int totedge,
                              MFace *mfaces, unsigned int totface,
                              MLoop *mloops, unsigned int totloop,
                              MPoly *mpolys, unsigned int totpoly,
                              MDeformVert *dverts, /* assume totvert length */
                              const bool do_verbose, const bool do_fixes,
                              bool *r_changed)
{
#   define REMOVE_EDGE_TAG(_me) { _me->v2 = _me->v1; free_flag.edges = do_fixes; } (void)0
#   define IS_REMOVED_EDGE(_me) (_me->v2 == _me->v1)

#   define REMOVE_LOOP_TAG(_ml) { _ml->e = INVALID_LOOP_EDGE_MARKER; free_flag.polyloops = do_fixes; } (void)0
#   define REMOVE_POLY_TAG(_mp) { _mp->totloop *= -1; free_flag.polyloops = do_fixes; } (void)0

	MVert *mv = mverts;
	MEdge *me;
	MLoop *ml;
	MPoly *mp;
	unsigned int i, j;
	int *v;

	bool is_valid = true;

	union {
		struct {
			int verts : 1;
			int verts_weight : 1;
		};
		int as_flag;
	} fix_flag;

	union {
		struct {
			int edges : 1;
			int faces : 1;
			/* This regroups loops and polys! */
			int polyloops : 1;
			int mselect : 1;
		};
		int as_flag;
	} free_flag;

	union {
		struct {
			int edges : 1;
		};
		int as_flag;
	} recalc_flag;

	EdgeHash *edge_hash = BLI_edgehash_new_ex(__func__, totedge);

	BLI_assert(!(do_fixes && mesh == NULL));

	fix_flag.as_flag = 0;
	free_flag.as_flag = 0;
	recalc_flag.as_flag = 0;

	PRINT_MSG("%s: verts(%u), edges(%u), loops(%u), polygons(%u)\n",
	          __func__, totvert, totedge, totloop, totpoly);

	if (totedge == 0 && totpoly != 0) {
		PRINT_ERR("\tLogical error, %u polygons and 0 edges\n", totpoly);
		recalc_flag.edges = do_fixes;
	}

	for (i = 0; i < totvert; i++, mv++) {
		bool fix_normal = true;

		for (j = 0; j < 3; j++) {
			if (!finite(mv->co[j])) {
				PRINT_ERR("\tVertex %u: has invalid coordinate\n", i);

				if (do_fixes) {
					zero_v3(mv->co);

					fix_flag.verts = true;
				}
			}

			if (mv->no[j] != 0)
				fix_normal = false;
		}

		if (fix_normal) {
			PRINT_ERR("\tVertex %u: has zero normal, assuming Z-up normal\n", i);
			if (do_fixes) {
				mv->no[2] = SHRT_MAX;
				fix_flag.verts = true;
			}
		}
	}

	for (i = 0, me = medges; i < totedge; i++, me++) {
		bool remove = false;

		if (me->v1 == me->v2) {
			PRINT_ERR("\tEdge %u: has matching verts, both %u\n", i, me->v1);
			remove = do_fixes;
		}
		if (me->v1 >= totvert) {
			PRINT_ERR("\tEdge %u: v1 index out of range, %u\n", i, me->v1);
			remove = do_fixes;
		}
		if (me->v2 >= totvert) {
			PRINT_ERR("\tEdge %u: v2 index out of range, %u\n", i, me->v2);
			remove = do_fixes;
		}

		if ((me->v1 != me->v2) && BLI_edgehash_haskey(edge_hash, me->v1, me->v2)) {
			PRINT_ERR("\tEdge %u: is a duplicate of %d\n", i,
			          GET_INT_FROM_POINTER(BLI_edgehash_lookup(edge_hash, me->v1, me->v2)));
			remove = do_fixes;
		}

		if (remove == false) {
			if (me->v1 != me->v2) {
				BLI_edgehash_insert(edge_hash, me->v1, me->v2, SET_INT_IN_POINTER(i));
			}
		}
		else {
			REMOVE_EDGE_TAG(me);
		}
	}

	if (mfaces && !mpolys) {
#		define REMOVE_FACE_TAG(_mf) { _mf->v3 = 0; free_flag.faces = do_fixes; } (void)0
#		define CHECK_FACE_VERT_INDEX(a, b) \
					if (mf->a == mf->b) { \
						PRINT_ERR("    face %u: verts invalid, " STRINGIFY(a) "/" STRINGIFY(b) " both %u\n", i, mf->a); \
						remove = do_fixes; \
					} (void)0
#		define CHECK_FACE_EDGE(a, b) \
					if (!BLI_edgehash_haskey(edge_hash, mf->a, mf->b)) { \
						PRINT_ERR("    face %u: edge " STRINGIFY(a) "/" STRINGIFY(b) \
						          " (%u,%u) is missing edge data\n", i, mf->a, mf->b); \
						recalc_flag.edges = do_fixes; \
					} (void)0

		MFace *mf;
		MFace *mf_prev;

		SortFace *sort_faces = MEM_callocN(sizeof(SortFace) * totface, "search faces");
		SortFace *sf;
		SortFace *sf_prev;
		unsigned int totsortface = 0;

		PRINT_ERR("No Polys, only tesselated Faces\n");

		for (i = 0, mf = mfaces, sf = sort_faces; i < totface; i++, mf++) {
			bool remove = false;
			int fidx;
			unsigned int fv[4];

			fidx = mf->v4 ? 3 : 2;
			do {
				fv[fidx] = *(&(mf->v1) + fidx);
				if (fv[fidx] >= totvert) {
					PRINT_ERR("\tFace %u: 'v%d' index out of range, %u\n", i, fidx + 1, fv[fidx]);
					remove = do_fixes;
				}
			} while (fidx--);

			if (remove == false) {
				if (mf->v4) {
					CHECK_FACE_VERT_INDEX(v1, v2);
					CHECK_FACE_VERT_INDEX(v1, v3);
					CHECK_FACE_VERT_INDEX(v1, v4);

					CHECK_FACE_VERT_INDEX(v2, v3);
					CHECK_FACE_VERT_INDEX(v2, v4);

					CHECK_FACE_VERT_INDEX(v3, v4);
				}
				else {
					CHECK_FACE_VERT_INDEX(v1, v2);
					CHECK_FACE_VERT_INDEX(v1, v3);

					CHECK_FACE_VERT_INDEX(v2, v3);
				}

				if (remove == false) {
					if (totedge) {
						if (mf->v4) {
							CHECK_FACE_EDGE(v1, v2);
							CHECK_FACE_EDGE(v2, v3);
							CHECK_FACE_EDGE(v3, v4);
							CHECK_FACE_EDGE(v4, v1);
						}
						else {
							CHECK_FACE_EDGE(v1, v2);
							CHECK_FACE_EDGE(v2, v3);
							CHECK_FACE_EDGE(v3, v1);
						}
					}

					sf->index = i;

					if (mf->v4) {
						edge_store_from_mface_quad(sf->es, mf);

						qsort(sf->es, 4, sizeof(int64_t), int64_cmp);
					}
					else {
						edge_store_from_mface_tri(sf->es, mf);
						qsort(sf->es, 3, sizeof(int64_t), int64_cmp);
					}

					totsortface++;
					sf++;
				}
			}

			if (remove) {
				REMOVE_FACE_TAG(mf);
			}
		}

		qsort(sort_faces, totsortface, sizeof(SortFace), search_face_cmp);

		sf = sort_faces;
		sf_prev = sf;
		sf++;

		for (i = 1; i < totsortface; i++, sf++) {
			bool remove = false;

			/* on a valid mesh, code below will never run */
			if (memcmp(sf->es, sf_prev->es, sizeof(sf_prev->es)) == 0) {
				mf = mfaces + sf->index;

				if (do_verbose) {
					mf_prev = mfaces + sf_prev->index;

					if (mf->v4) {
						PRINT_ERR("\tFace %u & %u: are duplicates (%u,%u,%u,%u) (%u,%u,%u,%u)\n",
						          sf->index, sf_prev->index, mf->v1, mf->v2, mf->v3, mf->v4,
						          mf_prev->v1, mf_prev->v2, mf_prev->v3, mf_prev->v4);
					}
					else {
						PRINT_ERR("\tFace %u & %u: are duplicates (%u,%u,%u) (%u,%u,%u)\n",
						          sf->index, sf_prev->index, mf->v1, mf->v2, mf->v3,
						          mf_prev->v1, mf_prev->v2, mf_prev->v3);
					}
				}

				remove = do_fixes;
			}
			else {
				sf_prev = sf;
			}

			if (remove) {
				REMOVE_FACE_TAG(mf);
			}
		}

		MEM_freeN(sort_faces);

#		undef REMOVE_FACE_TAG
#		undef CHECK_FACE_VERT_INDEX
#		undef CHECK_FACE_EDGE
	}

	/* Checking loops and polys is a bit tricky, as they are quite intricate...
	 *
	 * Polys must have:
	 * - a valid loopstart value.
	 * - a valid totloop value (>= 3 and loopstart+totloop < me.totloop).
	 *
	 * Loops must have:
	 * - a valid v value.
	 * - a valid e value (corresponding to the edge it defines with the next loop in poly).
	 *
	 * Also, loops not used by polys can be discarded.
	 * And "intersecting" loops (i.e. loops used by more than one poly) are invalid,
	 * so be sure to leave at most one poly per loop!
	 */
	{
		SortPoly *sort_polys = MEM_callocN(sizeof(SortPoly) * totpoly, "mesh validate's sort_polys");
		SortPoly *prev_sp, *sp = sort_polys;
		int prev_end;
		for (i = 0, mp = mpolys; i < totpoly; i++, mp++, sp++) {
			sp->index = i;

			if (mp->loopstart < 0 || mp->totloop < 3) {
				/* Invalid loop data. */
				PRINT_ERR("\tPoly %u is invalid (loopstart: %d, totloop: %d)\n",
				          sp->index, mp->loopstart, mp->totloop);
				sp->invalid = true;
			}
			else if (mp->loopstart + mp->totloop > totloop) {
				/* Invalid loop data. */
				PRINT_ERR("\tPoly %u uses loops out of range (loopstart: %d, loopend: %d, max nbr of loops: %u)\n",
				          sp->index, mp->loopstart, mp->loopstart + mp->totloop - 1, totloop - 1);
				sp->invalid = true;
			}
			else {
				/* Poly itself is valid, for now. */
				int v1, v2; /* v1 is prev loop vert idx, v2 is current loop one. */
				sp->invalid = false;
				sp->verts = v = MEM_mallocN(sizeof(int) * mp->totloop, "Vert idx of SortPoly");
				sp->numverts = mp->totloop;
				sp->loopstart = mp->loopstart;

				/* Test all poly's loops' vert idx. */
				for (j = 0, ml = &mloops[sp->loopstart]; j < mp->totloop; j++, ml++, v++) {
					if (ml->v >= totvert) {
						/* Invalid vert idx. */
						PRINT_ERR("\tLoop %u has invalid vert reference (%u)\n", sp->loopstart + j, ml->v);
						sp->invalid = true;
					}
					else {
						mverts[ml->v].flag |= ME_VERT_TMP_TAG;
					}
					*v = ml->v;
				}

				/* is the same vertex used more than once */
				if (!sp->invalid) {
					v = sp->verts;
					for (j = 0; j < mp->totloop; j++, v++) {
						if ((mverts[*v].flag & ME_VERT_TMP_TAG) == 0) {
							PRINT_ERR("\tPoly %u has duplicate vert reference at corner (%u)\n", i, j);
							sp->invalid = true;
						}
						mverts[*v].flag &= ~ME_VERT_TMP_TAG;
					}
				}

				if (sp->invalid)
					continue;

				/* Test all poly's loops. */
				for (j = 0, ml = &mloops[sp->loopstart]; j < mp->totloop; j++, ml++) {
					v1 = ml->v;
					v2 = mloops[sp->loopstart + (j + 1) % mp->totloop].v;
					if (!BLI_edgehash_haskey(edge_hash, v1, v2)) {
						/* Edge not existing. */
						PRINT_ERR("\tPoly %u needs missing edge (%d, %d)\n", sp->index, v1, v2);
						if (do_fixes)
							recalc_flag.edges = true;
						else
							sp->invalid = true;
					}
					else if (ml->e >= totedge) {
						/* Invalid edge idx.
						 * We already know from previous text that a valid edge exists, use it (if allowed)! */
						if (do_fixes) {
							int prev_e = ml->e;
							ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(edge_hash, v1, v2));
							PRINT_ERR("\tLoop %u has invalid edge reference (%d), fixed using edge %u\n",
							          sp->loopstart + j, prev_e, ml->e);
						}
						else {
							PRINT_ERR("\tLoop %u has invalid edge reference (%u)\n", sp->loopstart + j, ml->e);
							sp->invalid = true;
						}
					}
					else {
						me = &medges[ml->e];
						if (IS_REMOVED_EDGE(me) || !((me->v1 == v1 && me->v2 == v2) || (me->v1 == v2 && me->v2 == v1))) {
							/* The pointed edge is invalid (tagged as removed, or vert idx mismatch),
							 * and we already know from previous test that a valid one exists, use it (if allowed)! */
							if (do_fixes) {
								int prev_e = ml->e;
								ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(edge_hash, v1, v2));
								PRINT_ERR("\tPoly %u has invalid edge reference (%d), fixed using edge %u\n",
								          sp->index, prev_e, ml->e);
							}
							else {
								PRINT_ERR("\tPoly %u has invalid edge reference (%u)\n", sp->index, ml->e);
								sp->invalid = true;
							}
						}
					}
				}

				/* Now check that that poly does not use a same vertex more than once! */
				if (!sp->invalid) {
					const int *prev_v = v = sp->verts;
					j = sp->numverts;

					qsort(sp->verts, j, sizeof(int), int_cmp);

					for (j--, v++; j; j--, v++) {
						if (*v != *prev_v) {
							int dlt = v - prev_v;
							if (dlt > 1) {
								PRINT_ERR("\tPoly %u is invalid, it multi-uses vertex %d (%d times)\n",
								          sp->index, *prev_v, dlt);
								sp->invalid = true;
							}
							prev_v = v;
						}
					}
					if (v - prev_v > 1) { /* Don't forget final verts! */
						PRINT_ERR("\tPoly %u is invalid, it multi-uses vertex %d (%d times)\n",
						          sp->index, *prev_v, (int)(v - prev_v));
						sp->invalid = true;
					}
				}
			
			}
		}

		/* Second check pass, testing polys using the same verts. */
		qsort(sort_polys, totpoly, sizeof(SortPoly), search_poly_cmp);
		sp = prev_sp = sort_polys;
		sp++;

		for (i = 1; i < totpoly; i++, sp++) {
			int p1_nv = sp->numverts, p2_nv = prev_sp->numverts;
			const int *p1_v = sp->verts, *p2_v = prev_sp->verts;
			short p1_sub = true, p2_sub = true;
			if (sp->invalid)
				break;
			/* Test same polys. */
#if 0
			/* NOTE: This performs a sub-set test. */
			/* XXX This (and the sort of verts list) is better than systematic
			 *     search of all verts of one list into the other if lists have
			 *     a fair amount of elements.
			 *     Not sure however it's worth it in this case?
			 *     But as we also need sorted vert list to check verts multi-used
			 *     (in first pass of checks)... */
			/* XXX If we consider only "equal" polys (i.e. using exactly same set of verts)
			 *     as invalid, better to replace this by a simple memory cmp... */
			while ((p1_nv && p2_nv) && (p1_sub || p2_sub)) {
				if (*p1_v < *p2_v) {
					if (p1_sub)
						p1_sub = false;
					p1_nv--;
					p1_v++;
				}
				else if (*p2_v < *p1_v) {
					if (p2_sub)
						p2_sub = false;
					p2_nv--;
					p2_v++;
				}
				else {
					/* Equality, both next verts. */
					p1_nv--;
					p2_nv--;
					p1_v++;
					p2_v++;
				}
			}
			if (p1_nv && p1_sub)
				p1_sub = false;
			else if (p2_nv && p2_sub)
				p2_sub = false;

			if (p1_sub && p2_sub) {
				PRINT("\tPolys %u and %u use same vertices, considering poly %u as invalid.\n",
				      prev_sp->index, sp->index, sp->index);
				sp->invalid = true;
			}
			/* XXX In fact, these might be valid? :/ */
			else if (p1_sub) {
				PRINT("\t%u is a sub-poly of %u, considering it as invalid.\n", sp->index, prev_sp->index);
				sp->invalid = true;
			}
			else if (p2_sub) {
				PRINT("\t%u is a sub-poly of %u, considering it as invalid.\n", prev_sp->index, sp->index);
				prev_sp->invalid = true;
				prev_sp = sp; /* sp is new reference poly. */
			}
#else
			if (0) {
				p1_sub += 0;
				p2_sub += 0;
			}
			if ((p1_nv == p2_nv) && (memcmp(p1_v, p2_v, p1_nv * sizeof(*p1_v)) == 0)) {
				if (do_verbose) {
					PRINT_ERR("\tPolys %u and %u use same vertices (%d",
					          prev_sp->index, sp->index, *p1_v);
					for (j = 1; j < p1_nv; j++)
						PRINT_ERR(", %d", p1_v[j]);
					PRINT_ERR("), considering poly %u as invalid.\n", sp->index);
				}
				else {
					is_valid = false;
				}
				sp->invalid = true;
			}
#endif
			else {
				prev_sp = sp;
			}
		}

		/* Third check pass, testing loops used by none or more than one poly. */
		qsort(sort_polys, totpoly, sizeof(SortPoly), search_polyloop_cmp);
		sp = sort_polys;
		prev_sp = NULL;
		prev_end = 0;
		for (i = 0; i < totpoly; i++, sp++) {
			/* Free this now, we don't need it anymore, and avoid us another loop! */
			if (sp->verts)
				MEM_freeN(sp->verts);

			/* Note above prev_sp: in following code, we make sure it is always valid poly (or NULL). */
			if (sp->invalid) {
				if (do_fixes) {
					REMOVE_POLY_TAG((&mpolys[sp->index]));
					/* DO NOT REMOVE ITS LOOPS!!!
					 * As already invalid polys are at the end of the SortPoly list, the loops they
					 * were the only users have already been tagged as "to remove" during previous
					 * iterations, and we don't want to remove some loops that may be used by
					 * another valid poly! */
				}
			}
			/* Test loops users. */
			else {
				/* Unused loops. */
				if (prev_end < sp->loopstart) {
					for (j = prev_end, ml = &mloops[prev_end]; j < sp->loopstart; j++, ml++) {
						PRINT_ERR("\tLoop %u is unused.\n", j);
						if (do_fixes)
							REMOVE_LOOP_TAG(ml);
					}
					prev_end = sp->loopstart + sp->numverts;
					prev_sp = sp;
				}
				/* Multi-used loops. */
				else if (prev_end > sp->loopstart) {
					PRINT_ERR("\tPolys %u and %u share loops from %d to %d, considering poly %u as invalid.\n",
					          prev_sp->index, sp->index, sp->loopstart, prev_end, sp->index);
					if (do_fixes) {
						REMOVE_POLY_TAG((&mpolys[sp->index]));
						/* DO NOT REMOVE ITS LOOPS!!!
						 * They might be used by some next, valid poly!
						 * Just not updating prev_end/prev_sp vars is enough to ensure the loops
						 * effectively no more needed will be marked as "to be removed"! */
					}
				}
				else {
					prev_end = sp->loopstart + sp->numverts;
					prev_sp = sp;
				}
			}
		}
		/* We may have some remaining unused loops to get rid of! */
		if (prev_end < totloop) {
			for (j = prev_end, ml = &mloops[prev_end]; j < totloop; j++, ml++) {
				PRINT_ERR("\tLoop %u is unused.\n", j);
				if (do_fixes)
					REMOVE_LOOP_TAG(ml);
			}
		}

		MEM_freeN(sort_polys);
	}

	BLI_edgehash_free(edge_hash, NULL);

	/* fix deform verts */
	if (dverts) {
		MDeformVert *dv;
		for (i = 0, dv = dverts; i < totvert; i++, dv++) {
			MDeformWeight *dw;

			for (j = 0, dw = dv->dw; j < dv->totweight; j++, dw++) {
				/* note, greater than max defgroups is accounted for in our code, but not < 0 */
				if (!finite(dw->weight)) {
					PRINT_ERR("\tVertex deform %u, group %d has weight: %f\n", i, dw->def_nr, dw->weight);
					if (do_fixes) {
						dw->weight = 0.0f;
						fix_flag.verts_weight = true;
					}
				}
				else if (dw->weight < 0.0f || dw->weight > 1.0f) {
					PRINT_ERR("\tVertex deform %u, group %d has weight: %f\n", i, dw->def_nr, dw->weight);
					if (do_fixes) {
						CLAMP(dw->weight, 0.0f, 1.0f);
						fix_flag.verts_weight = true;
					}
				}

				if (dw->def_nr < 0) {
					PRINT_ERR("\tVertex deform %u, has invalid group %d\n", i, dw->def_nr);
					if (do_fixes) {
						defvert_remove_group(dv, dw);
						fix_flag.verts_weight = true;

						if (dv->dw) {
							/* re-allocated, the new values compensate for stepping
							 * within the for loop and may not be valid */
							j--;
							dw = dv->dw + j;

						}
						else { /* all freed */
							break;
						}
					}
				}
			}
		}
	}

#   undef REMOVE_EDGE_TAG
#   undef IS_REMOVED_EDGE
#   undef REMOVE_LOOP_TAG
#   undef REMOVE_POLY_TAG

	if (mesh) {
		if (free_flag.faces) {
			BKE_mesh_strip_loose_faces(mesh);
		}

		if (free_flag.polyloops) {
			BKE_mesh_strip_loose_polysloops(mesh);
		}

		if (free_flag.edges) {
			BKE_mesh_strip_loose_edges(mesh);
		}

		if (recalc_flag.edges) {
			BKE_mesh_calc_edges(mesh, true, false);
		}
	}

	if (mesh && mesh->mselect) {
		MSelect *msel;

		for (i = 0, msel = mesh->mselect; i < mesh->totselect; i++, msel++) {
			int tot_elem = 0;

			if (msel->index < 0) {
				PRINT_ERR("\tMesh select element %u type %d index is negative, "
				          "resetting selection stack.\n", i, msel->type);
				free_flag.mselect = do_fixes;
				break;
			}

			switch (msel->type) {
				case ME_VSEL:
					tot_elem = mesh->totvert;
					break;
				case ME_ESEL:
					tot_elem = mesh->totedge;
					break;
				case ME_FSEL:
					tot_elem = mesh->totface;
					break;
			}

			if (msel->index > tot_elem) {
				PRINT_ERR("\tMesh select element %u type %d index %d is larger than data array size %d, "
				          "resetting selection stack.\n", i, msel->type, msel->index, tot_elem);

				free_flag.mselect = do_fixes;
				break;
			}
		}

		if (free_flag.mselect) {
			MEM_freeN(mesh->mselect);
			mesh->mselect = NULL;
			mesh->totselect = 0;
		}
	}

	PRINT_MSG("%s: finished\n\n", __func__);

	*r_changed = (fix_flag.as_flag || free_flag.as_flag || recalc_flag.as_flag);

	if (do_fixes == false) {
		BLI_assert(*r_changed == false);
	}

	return is_valid;
}
Exemplo n.º 5
0
// the generic DSA mechanism assumes that the data to be signed has already
// been hashed by SHA-1.  so the input data length must be 20 bytes
//
CK_RV do_SignDSA( void )
{
	CK_BYTE             data1[20];
	CK_BYTE             signature[256];
	CK_SLOT_ID          slot_id;
	CK_SESSION_HANDLE   session;
	CK_MECHANISM        mech;
	CK_OBJECT_HANDLE    publ_key, priv_key;
	CK_FLAGS            flags;
	CK_BYTE             user_pin[PKCS11_MAX_PIN_LEN];
	CK_ULONG            user_pin_len;
	CK_ULONG            i;
	CK_ULONG            len1, sig_len;
	CK_RV               rc, loc_rc;

	CK_ATTRIBUTE  publ_tmpl[] =
	{
		{CKA_PRIME,    DSA_PUBL_PRIME,    sizeof(DSA_PUBL_PRIME)    },
		{CKA_SUBPRIME, DSA_PUBL_SUBPRIME, sizeof(DSA_PUBL_SUBPRIME) },
		{CKA_BASE,     DSA_PUBL_BASE,     sizeof(DSA_PUBL_BASE)     }
	};

	printf("do_SignDSA...\n");

	slot_id = SLOT_ID;
	flags = CKF_SERIAL_SESSION | CKF_RW_SESSION;
	rc = funcs->C_OpenSession( slot_id, flags, NULL, NULL, &session );
	if (rc != CKR_OK) {
		show_error("   C_OpenSession #1", rc );
		goto session_close;
	}


	if (get_user_pin(user_pin))
		return CKR_FUNCTION_FAILED;
	user_pin_len = (CK_ULONG)strlen((char *)user_pin);

	rc = funcs->C_Login( session, CKU_USER, user_pin, user_pin_len );
	if (rc != CKR_OK) {
		show_error("   C_Login #1", rc );
		goto session_close;
	}

	mech.mechanism      = CKM_DSA_KEY_PAIR_GEN;
	mech.ulParameterLen = 0;
	mech.pParameter     = NULL;

	rc = funcs->C_GenerateKeyPair( session,   &mech,
			publ_tmpl,  3,
			NULL,       0,
			&publ_key, &priv_key );
	if (rc != CKR_OK) {
		show_error("   C_GenerateKeyPair #1", rc );
		goto session_close;
	}

	// now, encrypt some data
	//
	len1 = sizeof(data1);
	sig_len = sizeof(signature);

	for (i=0; i < len1; i++)
		data1[i] = i % 255;

	mech.mechanism      = CKM_DSA;
	mech.ulParameterLen = 0;
	mech.pParameter     = NULL;

	rc = funcs->C_SignInit( session, &mech, priv_key );
	if (rc != CKR_OK) {
		show_error("   C_SignInit #1", rc );
		goto session_close;
	}

	rc = funcs->C_Sign( session, data1, len1, signature, &sig_len );
	if (rc != CKR_OK) {
		show_error("   C_Sign #1", rc );
		goto session_close;
	}

	// now, verify the signature
	//
	rc = funcs->C_VerifyInit( session, &mech, publ_key );
	if (rc != CKR_OK) {
		show_error("   C_VerifyInit #1", rc );
		goto session_close;
	}

	rc = funcs->C_Verify( session, data1, len1, signature, sig_len );
	if (rc != CKR_OK) {
		show_error("   C_Verify #1", rc );
		goto session_close;
	}

	// now, corrupt the signature and try to re-verify.
	//
	memcpy( signature, "ABCDEFGHIJKLMNOPQRSTUV", 26 );

	rc = funcs->C_VerifyInit( session, &mech, publ_key );
	if (rc != CKR_OK) {
		show_error("   C_VerifyInit #2", rc );
		goto session_close;
	}

	rc = funcs->C_Verify( session, data1, len1, signature, sig_len );
	if (rc != CKR_SIGNATURE_INVALID) {
		show_error("   C_Verify #2", rc );
		PRINT_ERR("   Expected CKR_SIGNATURE_INVALID\n");
		goto session_close;
	} else
		rc = CKR_OK;

	printf("Looks okay...\n");

session_close:

	/* Close the session */
	if( (loc_rc = funcs->C_CloseSession(session)) != CKR_OK )
		show_error("C_CloseSession", loc_rc);
	
	return rc;
}
Exemplo n.º 6
0
// Simple event sanity check. Test root dataset for matching event and track sizes
  int
EventReader::eventSanityCheck (void)
{
  size_t nTracks, nElements;

  if (!mLocX || !mLocY || !mErr_locX || !mErr_locY || !mCov_locXY || !mDetType
      || !mBec || !mRefLocX || !mRefLocY || !mRefPhi || !mRefTheta || !mRefQoverP
      || !mJacobi || !mD0 || !mZ0 ||!mPhi || !mTheta || !mQoverP) {

    PRINT_ERR ("Branch vector is null!");
    return -1;
  }
#if HAS_COMPETING_ROTS
  // !mCompetingRotIds ||
  if (!mRotLocX || !mRotLocY || !mRotIds || !mRotProbs) {

    PRINT_ERR("Branch vector of rots is null!");
    return -1;
  }
#endif
  for (size_t i = 0; i < mJacobi->size ( ); ++i) {
    if (!mJacobi->at (i)) {
      PRINT_ERR ("Jacobi matrix branch is null!");
      return -1;
    }
  }

  // Sanity check: If the vector size is not equal for all attributes, the data file
  // cannot be a valid data set.
  nTracks = mLocX->size ( );

  if (mLocY->size ( ) != nTracks || mErr_locX->size ( ) != nTracks
      || mErr_locY->size ( )  != nTracks || mCov_locXY->size ( ) != nTracks
      || mDetType->size ( )   != nTracks || mBec->size ( )       != nTracks
      || mRefLocX->size ( )   != nTracks || mRefLocY->size ( )   != nTracks
      || mRefPhi->size ( )    != nTracks || mRefTheta->size ( )  != nTracks
      || mRefQoverP->size ( ) != nTracks || mPhi->size ( )       != nTracks
      || mD0->size ( )        != nTracks || mZ0->size ( )        != nTracks
      || mTheta->size ( )     != nTracks || mQoverP->size ( )    != nTracks) {

    PRINT_ERR ("Number of tracks is not equal for all attributes!");
    return -1;
  }

  for (size_t i = 0; i < mJacobi->size ( ); ++i) {
    if (mJacobi->at (i)->size ( ) != nTracks) {
      PRINT_ERR ("Number of tracks is not equal for all attributes!");
      return -1;
    }
  }

  for (size_t track = 0; track < nTracks; ++track) {
    nElements = (*mLocX)[track].size ( );

    if ((*mLocY)[track].size ( ) != nElements
	|| (*mErr_locX)[track].size ( )  != nElements
	|| (*mErr_locY)[track].size ( )  != nElements
	|| (*mCov_locXY)[track].size ( ) != nElements
	|| (*mDetType)[track].size ( )   != nElements
	|| (*mBec)[track].size ( )       != nElements
	|| (*mRefLocX)[track].size ( )   != nElements
	|| (*mRefLocY)[track].size ( )   != nElements
	|| (*mRefPhi)[track].size ( )    != nElements
	|| (*mRefTheta)[track].size ( )  != nElements
	|| (*mRefQoverP)[track].size ( ) != nElements) {

      PRINT_ERR ("Hit count is not equal for all attributes!");
      return -1;
    }

    for (size_t i = 0; i < mJacobi->size ( ); ++i) {
      if (mJacobi->at (i)->at (track).size ( ) != nElements) {
	PRINT_ERR ("Number of Hits is not equal for all attributes!");
	return -1;
      }
    }
  }
#if HAS_COMPETING_ROTS
  for (size_t track = 0; track < nTracks; ++track) {
    nElements = (*mLocX)[track].size();
    //
    for (size_t cRot = 0; cRot < nElements; ++cRot) {
      size_t nRots = (*mRotLocX)[track][cRot].size();
      if (nRots != (*mRotIds)[track][cRot].size()
	 ) {
	//
	PRINT_ERR("Hit count is not equal for all attributes!");
	return -1;
      }

    }
  }
#endif
  return 0;
}
int bcm_sdiowl_init(int onoff)
{
	int rc;
	struct sdio_wifi_dev *dev = &gDev;
#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT
	int wait_cnt;
	struct mmc_card *card;
#endif

	printk(KERN_ERR "%s:ENTRY\n", __func__);


/* Set the Pull of Sdio Lines first */
	SdioPinCfgs.name = PN_MMC1CK;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.input_dis = 0;
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 0;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);

	SdioPinCfgs.name = PN_MMC1CMD;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 1;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT0;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 1;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);

	SdioPinCfgs.name = PN_MMC1DAT1;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 1;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT2;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 1;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT3;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 1;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT4;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 1;
	SdioPinCfgs.reg.b.pull_up = 0;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);
/*
	SdioPinCfgs.name = PN_LCDTE;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn = 0;
	SdioPinCfgs.reg.b.pull_up = 0;
	SdioPinCfgs.reg.b.drv_sth = 3;
	pinmux_set_pin_config(&SdioPinCfgs);
*/


/* ----------------------------------- */



	/* check if the SDIO device is already up */
	rc = sdio_dev_is_initialized(SDIO_DEV_TYPE_WIFI);
	if (rc <= 0) {
		PRINT_ERR("sdio interface is not initialized or err=%d\n", rc);
		return rc;
	}
	printk(KERN_ERR "%s:GET_GPIO INFO\n", __func__);

	dev->wifi_gpio = sdio_get_wifi_gpio(SDIO_DEV_TYPE_WIFI);
#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT

	if (dev->wifi_gpio == NULL) {
		PRINT_ERR("wifi gpio hardware config is missing\n");
		return -EFAULT;
	}
#endif

#ifdef CONFIG_BRCM_UNIFIED_DHD_SUPPORT
#if defined(CONFIG_MACH_HAWAII_RAY) || defined(CONFIG_MACH_HAWAII_STONE) \
	|| defined(CONFIG_MACH_HAWAII_GARNET) \
	|| defined(CONFIG_MACH_HAWAII_SS_EVAL_REV00) \
	|| defined(CONFIG_MACH_HAWAII_SS_LOGAN_REV00) \
	|| defined(CONFIG_MACH_HAWAII_SS_LOGAN_REV01)
	dev->wifi_gpio->reset = 3;
	dev->wifi_gpio->reg = -1;
	dev->wifi_gpio->host_wake = 74;
	dev->wifi_gpio->shutdown = -1;
#endif
#endif

	/* reserve GPIOs */
	rc = wifi_gpio_request(dev->wifi_gpio);
	if (rc < 0) {
		PRINT_ERR("unable to reserve certain gpio pins\n");
		return rc;
	}

	/* reset the wifi chip */
	if (onoff)
		__wifi_reset(dev->wifi_gpio->reset, 1);
	else
		__wifi_reset(dev->wifi_gpio->reset, 0);

	printk(KERN_ERR "%s: WLAN_REG_ON(GPIO%d) : value(%d)\n",
		__func__, dev->wifi_gpio->reset,
		gpio_get_value(dev->wifi_gpio->reset));

	printk(KERN_ERR "%s:GPIO TOGGLED AND EXIT\n", __func__);

#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT

	/* now, emulate the card insertion */
	rc = sdio_card_emulate(SDIO_DEV_TYPE_WIFI, 1);
	if (rc < 0) {
		PRINT_ERR("sdio_card_emulate failed\n");
		goto err_free_gpio;
	}
#define WAIT_CNT 10
	/* need to wait for the mmc device population to finish */
	wait_cnt = 0;
	while (wait_cnt++ < WAIT_CNT) {
		card = sdio_get_mmc_card(SDIO_DEV_TYPE_WIFI);
		if (card) {
			atomic_set(&dev->dev_is_ready, 1);
			return 0;
		}
		msleep(100);
	}
	PRINT_ERR("timeout while populating sdio wifi device\n");
	rc = -EIO;
	sdio_card_emulate(SDIO_DEV_TYPE_WIFI, 0);

err_free_gpio:
	wifi_gpio_free(dev->wifi_gpio);
#endif /* CONFIG_BRCM_UNIFIED_DHD_SUPPORT */
	return rc;
}
Exemplo n.º 8
0
Arquivo: pftpd.c Projeto: neeohw/pftp
int main( int argc, char *argv[]) {
    int c = 0;
    int port = 0;
    int run_state = STATE_WAIT_CMD;
    char network[128];
    char *iface = NULL;
    char *mcast_addr = NULL;

    network[0] = '\0';

    pgm_error_t* pgm_err = NULL;
    pgm_sock_t *pgm_sock = NULL;

    signal(SIGINT, handle_sigint);

    while((c = getopt(argc, argv, "hm:i:p:")) != -1) {
        switch (c) {
        case 'm':
            mcast_addr = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'p':
            port = atoi(optarg);
            break;
        case 'h':
        case '?':
            print_usage();
            break;
        default:
            print_usage();
            break;
        }
    }

#ifdef UDPTEST
    int sockfd = 0;
    struct sockaddr_in servaddr;
    struct ip_mreqn mreq;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = port ? htons(port) : htons(PFTP_UDP_PORT);

    if (0 != bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) ) {
        PRINT_ERR("Couldn't bind socket!");
        return -1;
    }

    memset(&mreq, 0, sizeof(mreq));
    char *ifaddr = NULL;
    if (iface) {
        ifaddr = pftp_inet_iftoa(iface);
    } else {
        ifaddr = pftp_inet_iftoa("eth0");
    }

    mreq.imr_address.s_addr = inet_addr(ifaddr);
    mreq.imr_ifindex = 0;
    if (ifaddr) free(ifaddr);

    if (mcast_addr) {
        mreq.imr_multiaddr.s_addr = inet_addr(mcast_addr);
    } else {
        mreq.imr_multiaddr.s_addr = inet_addr(PFTP_DEFAULT_MCAST_ADDR);
    }

    if (0 != setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) {
        PRINT_ERR("Couldn't join multicast group!: %s" ,strerror(errno));
    }

#else
    if (iface) {
        char *ifaddr = pftp_inet_iftoa(iface);
        if (strlen(ifaddr) > 0) {
            strncat(network, ifaddr, 128);
            strncat(network, ";", 128);
        } else {
            free(ifaddr);
            return -1;
        }
        free(ifaddr);
    }

    if (mcast_addr) {
        strncat(network, mcast_addr, 128);
    } else {
        strncat(network, PFTP_DEFAULT_MCAST_ADDR, 128);
    }

    if (0 != pftp_create(0, network, port, &pgm_sock)) {
        return -1;
    }
#endif

    PRINT_DBG("Running receive loop");
    int fds = 0;
    fd_set readfds;
    int file_desc = -1;
    int total_bytes = 0;
    void *cmd_info = NULL;

    m_run_receive_loop = 1;

    while (m_run_receive_loop) {

        char recv_buf[PGMBUF_SIZE];
        memset(&recv_buf, 0, PGMBUF_SIZE);
        size_t bytes_read = 0;

#ifdef UDPTEST
        fds = sockfd + 1;

        bytes_read = recv(sockfd, recv_buf, PGMBUF_SIZE, MSG_DONTWAIT);

        switch (bytes_read) {
        case -1:
            if (errno == EWOULDBLOCK || errno == EAGAIN) {
                FD_ZERO(&readfds);
                FD_SET(sockfd, &readfds);
                select(fds, &readfds, NULL, NULL, NULL);
            }
            break;
        default:
        {
#else
        struct timeval tv;

        struct pgm_sockaddr_t from;
        socklen_t from_sz = sizeof(from);
        const int pgm_status = pgm_recvfrom(pgm_sock, recv_buf, PGMBUF_SIZE, MSG_DONTWAIT, &bytes_read, &from, &from_sz, &pgm_err);

        //PRINT_DBG("pgm_status: %d", pgm_status);
        switch (pgm_status) {

        case PGM_IO_STATUS_NORMAL :
        {
#endif
            int cmd_parsed = pftp_parse_cmd(recv_buf, &cmd_info);

            switch(cmd_parsed) {

            case PFTP_CMD_UNKNOWN :
                if (  run_state == STATE_FILE_TRANSFER
                   && file_desc > 0 ) {
                    write(file_desc, recv_buf, bytes_read);
                    total_bytes += bytes_read;
                    if (total_bytes >= ((struct pftp_send_file_cmd*)cmd_info)->fsize) {
                        PRINT_DBG("File %s received.", ((struct pftp_send_file_cmd*)cmd_info)->fname);
                        close(file_desc);
                        total_bytes = 0;
                        pftp_free_cmd(cmd_info);
                        run_state = STATE_WAIT_CMD;
                    }
                }
                break;

            case PFTP_CMD_SEND_FILE_PARSED :
            {
                struct pftp_send_file_cmd *sf_cmd = (struct pftp_send_file_cmd *)cmd_info;
                file_desc = open(sf_cmd->fname, O_CREAT | O_WRONLY, S_IRWXU);
                if (file_desc < 0) {
                    PRINT_ERR("Couldn't open file for writing! %s", strerror(errno));
                    pftp_free_cmd(cmd_info);
                    run_state = STATE_WAIT_CMD;
                } else {
                    run_state = STATE_FILE_TRANSFER;
                }

            } break;

            default :
                pftp_free_cmd(cmd_info);
                break;
            }

#ifdef UDPTEST
        } break;
        }
#else
        } break;
        case PGM_IO_STATUS_TIMER_PENDING:
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_TIME_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            goto block;
        }
        case PGM_IO_STATUS_RATE_LIMITED:
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            /* No accidental fallthrough! */
        }
        case PGM_IO_STATUS_WOULD_BLOCK:
block:
            FD_ZERO(&readfds);
            pgm_select_info(pgm_sock, &readfds, NULL, &fds);
            fds = select(fds, &readfds, NULL, NULL, pgm_status == PGM_IO_STATUS_WOULD_BLOCK ? NULL : &tv);
            break;
        case PGM_IO_STATUS_RESET:
            if (pgm_err) {
                fprintf(stderr, "%s\n", pgm_err->message);
                pgm_error_free(pgm_err);
                pgm_err = NULL;
            }
            close(file_desc);
            total_bytes = 0;
            run_state = STATE_WAIT_CMD;
            break;
        default :
            if (pgm_err) {
                fprintf(stderr, "%s\n", pgm_err->message);
                pgm_error_free(pgm_err);
                pgm_err = NULL;
            }
            if (pgm_status == PGM_IO_STATUS_ERROR) {
                m_run_receive_loop = 0;
            } else {
                PRINT_ERR("Unknown status!");
                m_run_receive_loop = 0;
            }
            break;
        }
#endif
    }

    if (file_desc > 0)
        close(file_desc);
    PRINT_DBG("Receive loop finished");

#ifdef UDPTEST
    if (sockfd > 0)
        close(sockfd);
#else
    if (pgm_sock) {
        pftp_stop(pgm_sock);
    }
#endif

    return 0;
}
/*
 * parse one kernel parameter in the form keyword=value
 */
static int parse_parameter(char *parameter)
{
	char *token;
	char *end_ptr;

	token = strtok(parameter, "=");
	if (token == NULL)
		return 0;

	if (strcmp(token, PARM_DIR) == 0) {
		/* Dump Dir */
		g.parm_dir = strtok(NULL, "=");
		if (g.parm_dir == NULL) {
			PRINT_WARN("No value for '%s' parameter specified\n",
				    PARM_DIR);
			PRINT_WARN("Using default: %s\n", PARM_DIR_DFLT);
			g.parm_dir = PARM_DIR_DFLT;
		}
	} else if (strcmp(token, PARM_PART) == 0) {
		/* Dump Partition */
		g.parm_part = strtok(NULL, "=");
		if (g.parm_part == NULL) {
			PRINT_ERR("No value for '%s' parameter "
				  "specified\n", PARM_PART);
			return -1;
		}
	} else if (strcmp(token, PARM_MEM) == 0) {
		/* Dump mem */
		char *mem_str = strtok(NULL, "=");
		if (mem_str == NULL) {
			PRINT_ERR("No value for '%s' parameter "
				  "specified\n", PARM_MEM);
			return -1;
		}
		g.parm_mem = strtoll(mem_str, &end_ptr, 0);
		if (*end_ptr != 0) {
			PRINT_ERR("Invalid value for '%s' parameter "
				  "specified\n", PARM_MEM);
			return -1;
		}
	} else if (strcmp(token, PARM_COMP) == 0) {
		/* Dump Compression */
		g.parm_compress = strtok(NULL, "=");
		if (g.parm_compress == NULL) {
			PRINT_WARN("No value for '%s' parameter "
				   "specified\n", PARM_COMP);
			PRINT_WARN("Using default: %s\n", PARM_COMP_DFLT);
			g.parm_compress = PARM_COMP_DFLT;
		} else if ((strcmp(g.parm_compress, PARM_COMP_GZIP) != 0) &&
			   (strcmp(g.parm_compress, PARM_COMP_NONE) != 0)) {
			PRINT_WARN("Unknown dump compression '%s' "
				   "specified!\n", g.parm_compress);
			PRINT_WARN("Using default: %s\n", PARM_COMP_DFLT);
			g.parm_compress = PARM_COMP_DFLT;
		}
	} else if (strcmp(token, PARM_DEBUG) == 0) {
		/* Dump Debug */
		char *s = strtok(NULL, "=");
		if (s == NULL) {
			PRINT_WARN("No value for '%s' parameter "
				"specified\n", PARM_DEBUG);
			PRINT_WARN("Using default: %d\n", PARM_DEBUG_DFLT);
		} else {
			g.parm_debug = atoi(s);
			if ((g.parm_debug < PARM_DEBUG_MIN) ||
			    (g.parm_debug > PARM_DEBUG_MAX)) {
				PRINT_WARN("Invalid value (%i) for %s "
				"parameter specified (allowed range is "
				"%i - %i)\n", g.parm_debug, PARM_DEBUG,
				PARM_DEBUG_MIN, PARM_DEBUG_MAX);
				PRINT_WARN("Using default: %i\n",
				PARM_DEBUG_DFLT);
				g.parm_debug = PARM_DEBUG_DFLT;
			}
		}
	} else if (strcmp(token, PARM_MODE) == 0) {
		/* Dump Mode */
		char *s = strtok(NULL, "=");
		if (s == NULL) {
			PRINT_WARN("No value for '%s' parameter "
				"specified\n", PARM_MODE);
			PRINT_WARN("Using default: %s\n", PARM_MODE_DFLT);
		} else if (strcmp(s, PARM_MODE_INTERACT) == 0) {
			g.parm_mode = PARM_MODE_INTERACT_NUM;
		} else if (strcmp(s, PARM_MODE_AUTO) == 0) {
			g.parm_mode = PARM_MODE_AUTO_NUM;
		} else {
			PRINT_WARN("Unknown dump mode: %s\n", s);
			PRINT_WARN("Using default: %s\n", PARM_MODE_DFLT);
		}
	}
	return 0;
}
/*
 * This function performs a compression and decompress operation.
 */
static CpaStatus
compPerformOp(CpaInstanceHandle dcInstHandle, CpaDcSessionHandle sessionHdl,
        CpaDcSessionSetupData sd)
{
    CpaStatus status = CPA_STATUS_SUCCESS;
    CpaBufferList bufferListSrcArray[NUM_SAMPLE_DATA_BUFFERS];
    CpaBufferList bufferListDstArray[NUM_SAMPLE_DATA_BUFFERS];
    CpaBufferList bufferListDstArray2[NUM_SAMPLE_DATA_BUFFERS];
    Cpa32U bufferSize = SAMPLE_MAX_BUFF;
    Cpa32U numBuffers = NUM_SAMPLE_DATA_BUFFERS;
    Cpa32U bufferNum = 0;
    Cpa32U bufferMetaSize = 0;
    CpaDcFlush flushFlag = CPA_DC_FLUSH_FINAL;
    CpaDcRqResults dcResults;
    Cpa32U dataConsumed = 0;
    Cpa32U dataProduced = 0;

    struct COMPLETION_STRUCT complete;


    status = cpaDcBufferListGetMetaSize( dcInstHandle,
            SINGLE_BUFFER_PER_BUFFERLIST, &bufferMetaSize);

    for(bufferNum = 0; bufferNum < numBuffers; bufferNum++)
    {
        if (CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListSrcArray[bufferNum].pPrivateMetaData,
                    bufferMetaSize);
            bufferListSrcArray[bufferNum].numBuffers = 1;
        }
        if (CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListDstArray[bufferNum].pPrivateMetaData,
                    bufferMetaSize);
            bufferListDstArray[bufferNum].numBuffers = 1;
        }
        if(CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListDstArray2[bufferNum].pPrivateMetaData,
                    bufferMetaSize);
            bufferListDstArray2[bufferNum].numBuffers = 1;
        }

        if(CPA_STATUS_SUCCESS == status)
        {
            status = OS_MALLOC(
                    &bufferListSrcArray[bufferNum].pBuffers,
                    sizeof(CpaFlatBuffer));
        }
        if(CPA_STATUS_SUCCESS == status)
        {
            status = OS_MALLOC(
                    &bufferListDstArray[bufferNum].pBuffers,
                    sizeof(CpaFlatBuffer));
        }
        if(CPA_STATUS_SUCCESS == status)
        {
            status = OS_MALLOC(
                    &bufferListDstArray2[bufferNum].pBuffers,
                    sizeof(CpaFlatBuffer));
        }

        if(CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListSrcArray[bufferNum].pBuffers->pData,
                    bufferSize);
            bufferListSrcArray[bufferNum].pBuffers->dataLenInBytes = bufferSize;
        }
        if(CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListDstArray[bufferNum].pBuffers->pData,
                    bufferSize);
            bufferListDstArray[bufferNum].pBuffers->dataLenInBytes = bufferSize;
        }
        if(CPA_STATUS_SUCCESS == status)
        {
            status = PHYS_CONTIG_ALLOC(
                    &bufferListDstArray2[bufferNum].pBuffers->pData,
                    bufferSize);
            bufferListDstArray2[bufferNum].pBuffers->dataLenInBytes = bufferSize;
        }
        memcpy(bufferListSrcArray[bufferNum].pBuffers->pData,
                sampleData+(bufferNum*bufferSize), bufferSize);
    }
    if(CPA_STATUS_SUCCESS == status)
    {
        //<snippet name="initChecksum">
        if(sd.checksum == CPA_DC_ADLER32)
        {
            /* Initialize checksum to 1 for Adler32 */
            dcResults.checksum = 1;
        }
        else
        {
            /* Initialize checksum to 0 for CRC32 */
            dcResults.checksum = 0;
        }
        //</snippet>

        for(bufferNum = 0; bufferNum < numBuffers; bufferNum++)
        {

            COMPLETION_INIT(&complete);

            PRINT_DBG("cpaDcCompressData\n");
            status = cpaDcCompressData(dcInstHandle,
                    sessionHdl,
                    &bufferListSrcArray[bufferNum], /* source buffer list */
                    &bufferListDstArray[bufferNum], /* destination buffer list */
                    &dcResults,                     /* contains initialized checksum for first request or
                                                     * checksum from previous request */
                    flushFlag,                      /* stateless session */
                    (void *)&complete);
            if (CPA_STATUS_SUCCESS != status)
            {
                PRINT_ERR("cpaDcCompressData failed. (status = %d)\n", status);
                break;
            }
            /*
             * We now wait until the completion of the operation.  This uses a macro
             * which can be defined differently for different OSes.
             */
            if (CPA_STATUS_SUCCESS == status)
            {
                if (!COMPLETION_WAIT(&complete, TIMEOUT_MS))
                {
                    PRINT_ERR("timeout or interruption in cpaDcCompressData\n");
                    status = CPA_STATUS_FAIL;
                }
            }

            /*
             * We now check the results
             */
            if(dcResults.status != CPA_DC_OK)
            {
                PRINT_ERR("Results status not as expected (status = %d)\n",
                        dcResults.status);
                status = CPA_STATUS_FAIL;
                break;
            }

            if(dcResults.consumed !=
                    bufferListSrcArray[bufferNum].pBuffers->dataLenInBytes)
            {
                PRINT_ERR("Not all data consumed !\n");
                status = CPA_STATUS_FAIL;
                break;
            }

            dataConsumed += dcResults.consumed;
            dataProduced += dcResults.produced;
            bufferListDstArray[bufferNum].pBuffers->dataLenInBytes = dcResults.produced;

        } /* End for numBuffers */
    }

    if(CPA_STATUS_SUCCESS == status)
    {
        PRINT_DBG("Data consumed %d\n", dataConsumed);
        PRINT_DBG("Data produced %d\n", dataProduced);
        PRINT_DBG("Checksum 0x%x\n", dcResults.checksum);
        /* Reset counters and checksum */
        dataConsumed = 0;
        dataProduced = 0;
        memset(&dcResults, 0, sizeof(CpaDcRqResults));
    }

    if(CPA_STATUS_SUCCESS == status)
    {

        if(sd.checksum == CPA_DC_ADLER32)
        {
            /* Initialize checksum to 1 for Adler32 */
            dcResults.checksum = 1;
        }
        else
        {
            /* Initialize checksum to 0 for CRC32 */
            dcResults.checksum = 0;
        }
        for(bufferNum = 0; bufferNum < numBuffers; bufferNum++)
        {

            COMPLETION_INIT(&complete);

            PRINT_DBG("cpaDcDecompressData\n");
            status = cpaDcDecompressData(dcInstHandle,
                    sessionHdl,
                    &bufferListDstArray[bufferNum], /* source buffer list */
                    &bufferListDstArray2[bufferNum],/* destination buffer list */
                    &dcResults,                     /* contains initialized checksum for first request or
                                                     * checksum from previous request */
                    flushFlag,                      /* stateless session */
                    (void *)&complete);

            if (CPA_STATUS_SUCCESS != status)
            {
                PRINT_ERR("cpaDcCompressData failed. (status = %d)\n", status);
                break;
            }

            /*
             * We now wait until the completion of the operation.  This uses a macro
             * which can be defined differently for different OSes.
             */
            if (CPA_STATUS_SUCCESS == status)
            {
                if (!COMPLETION_WAIT(&complete, TIMEOUT_MS))
                {
                    PRINT_ERR("timeout or interruption in cpaDcDecompressData\n");
                    status = CPA_STATUS_FAIL;
                }
            }

            /*
             * We now check the results
             */
            if(dcResults.status != CPA_DC_OK)
            {
                PRINT_ERR("Results status not as expected (status = %d)\n",
                        dcResults.status);
                status = CPA_STATUS_FAIL;
                break;
            }

            if(dcResults.consumed !=
                    bufferListDstArray[bufferNum].pBuffers->dataLenInBytes)
            {
                PRINT_ERR("Not all data consumed !\n");
                status = CPA_STATUS_FAIL;
                break;
            }
            dataConsumed += dcResults.consumed;
            dataProduced += dcResults.produced;
        }
    }

    if(CPA_STATUS_SUCCESS == status)
    {
        PRINT_DBG("Data consumed %d\n", dataConsumed);
        PRINT_DBG("Data produced %d\n", dataProduced);
        PRINT_DBG("Checksum 0x%x\n", dcResults.checksum);
    }
    for(bufferNum = 0; bufferNum < numBuffers; bufferNum++)
    {
        PHYS_CONTIG_FREE(bufferListSrcArray[bufferNum].pPrivateMetaData);
        PHYS_CONTIG_FREE(bufferListDstArray[bufferNum].pPrivateMetaData);
        PHYS_CONTIG_FREE(bufferListDstArray2[bufferNum].pPrivateMetaData);

        PHYS_CONTIG_FREE(bufferListSrcArray[bufferNum].pBuffers->pData);
        PHYS_CONTIG_FREE(bufferListDstArray[bufferNum].pBuffers->pData);
        PHYS_CONTIG_FREE(bufferListDstArray2[bufferNum].pBuffers->pData);

        OS_FREE(bufferListSrcArray[bufferNum].pBuffers);
        OS_FREE(bufferListDstArray[bufferNum].pBuffers);
        OS_FREE(bufferListDstArray2[bufferNum].pBuffers);
    }

    COMPLETION_DESTROY(&complete);
    return status;
}
/*
 * This is the main entry point for the sample data compression code.
 * demonstrates the sequence of calls to be made to the API in order
 * to create a session, perform one or more stateless compression operations,
 * and then tear down the session.
 */
CpaStatus
dcStatelessSample(void)
{
    CpaStatus status = CPA_STATUS_SUCCESS;
    CpaDcInstanceCapabilities cap = {0};
    CpaBufferList **bufferInterArray = NULL;
    Cpa16U numInterBuffLists = 0;
    Cpa16U bufferNum = 0;
    Cpa32U buffMetaSize = 0;

    Cpa32U sess_size = 0;
    Cpa32U ctx_size = 0;
    CpaDcSessionHandle sessionHdl = NULL;
    CpaInstanceHandle dcInstHandle = NULL;
    CpaDcSessionSetupData sd = {0};
    CpaDcStats dcStats = {0};

    /*
     * In this simplified version of instance discovery, we discover
     * exactly one instance of a data compression service.
     */
    sampleDcGetInstance(&dcInstHandle);
    if (dcInstHandle == NULL)
    {
        return CPA_STATUS_FAIL;
    }

    /* Query Capabilities */
    PRINT_DBG("cpaDcQueryCapabilities\n");
    status = cpaDcQueryCapabilities(dcInstHandle, &cap);
    if(status != CPA_STATUS_SUCCESS)
    {
       return status;
    }

    if( !cap.statelessDeflateCompression ||
         !cap.statelessDeflateDecompression ||
         !cap.checksumAdler32 ||
         !cap.dynamicHuffman )
    {
        PRINT_DBG("Error: Unsupported functionality\n");
        return CPA_STATUS_FAIL;
    }

    if( cap.dynamicHuffmanBufferReq )
    {
        status = cpaDcBufferListGetMetaSize(dcInstHandle,
                1, &buffMetaSize);

        if(CPA_STATUS_SUCCESS == status)
        {
            status = cpaDcGetNumIntermediateBuffers(dcInstHandle,
                    &numInterBuffLists);
        }
        if(CPA_STATUS_SUCCESS == status && 0 != numInterBuffLists)
        {
            status = PHYS_CONTIG_ALLOC(&bufferInterArray,
                    numInterBuffLists*sizeof(CpaBufferList*));

        }
        for(bufferNum = 0; bufferNum < numInterBuffLists; bufferNum++)
        {
            if(CPA_STATUS_SUCCESS == status)
            {
                status = PHYS_CONTIG_ALLOC(
                        &bufferInterArray[bufferNum],sizeof(CpaBufferList));
            }
            if(CPA_STATUS_SUCCESS == status)
            {
                status = PHYS_CONTIG_ALLOC(
                        &bufferInterArray[bufferNum]->pPrivateMetaData,
                         buffMetaSize);
            }
            if(CPA_STATUS_SUCCESS == status)
            {
                status = PHYS_CONTIG_ALLOC(
                        &bufferInterArray[bufferNum]->pBuffers,
                        sizeof(CpaFlatBuffer));
            }

            if(CPA_STATUS_SUCCESS == status)
            {
                /* Implementation requires an intermediate buffer approximately
                   twice the size of the output buffer */
                status = PHYS_CONTIG_ALLOC(
                        &bufferInterArray[bufferNum]->pBuffers->pData,
                        2*SAMPLE_MAX_BUFF);
                bufferInterArray[bufferNum]->numBuffers = 1;
                bufferInterArray[bufferNum]->pBuffers->dataLenInBytes =
                        2*SAMPLE_MAX_BUFF;
            }

        } /* End numInterBuffLists */
    }
    if(CPA_STATUS_SUCCESS == status)
    {
       /*
        * Set the address translation function for the instance
        */
       status = cpaDcSetAddressTranslation(dcInstHandle, sampleVirtToPhys);
    }
    if(CPA_STATUS_SUCCESS == status)
    {
       /* Start DataCompression component */
       PRINT_DBG("cpaDcStartInstance\n");
       status = cpaDcStartInstance(dcInstHandle, numInterBuffLists,
               bufferInterArray);
    }
    if (CPA_STATUS_SUCCESS == status)
    {
       /*
        * If the instance is polled start the polling thread. Note that
        * how the polling is done is implementation-dependant.
        */
       sampleDcStartPolling(dcInstHandle);
       /*
        * We now populate the fields of the session operational data and create
        * the session.  Note that the size required to store a session is
        * implementation-dependent, so we query the API first to determine how
        * much memory to allocate, and then allocate that memory.
        */
        sd.compLevel = CPA_DC_L4;
        sd.compType = CPA_DC_DEFLATE;
        sd.huffType = CPA_DC_HT_FULL_DYNAMIC;
        /* If the implementation supports it, the session will be configured
         * to select static Huffman encoding over dynamic Huffman as
         * the static encoding will provide better compressibility.
         */
        if(cap.autoSelectBestHuffmanTree)
        {
           sd.autoSelectBestHuffmanTree = CPA_TRUE;
        }
        else
        {
           sd.autoSelectBestHuffmanTree = CPA_FALSE;
        }
        sd.sessDirection = CPA_DC_DIR_COMBINED;
        sd.sessState = CPA_DC_STATELESS;
#if ( CPA_DC_API_VERSION_NUM_MAJOR == 1 && CPA_DC_API_VERSION_NUM_MINOR < 6 )
        sd.deflateWindowSize = 7;
#endif
        sd.checksum = CPA_DC_CRC32;

        /* Determine size of session context to allocate */
        PRINT_DBG("cpaDcGetSessionSize\n");
        status = cpaDcGetSessionSize(dcInstHandle,
                    &sd, &sess_size, &ctx_size);
    }

    if (CPA_STATUS_SUCCESS == status)
    {
        /* Allocate session memory */
        status = PHYS_CONTIG_ALLOC(&sessionHdl, sess_size);
    }

    /* Initialize the Stateless session */
    if (CPA_STATUS_SUCCESS == status)
    {
        PRINT_DBG("cpaDcInitSession\n");
        status = cpaDcInitSession(dcInstHandle,
                            sessionHdl, /* session memory */
                            &sd,  /* session setup data */
                            NULL, /* pContexBuffer not required for stateless operations */
                            dcCallback); /* callback function */
    }

    if (CPA_STATUS_SUCCESS == status)
    {
        CpaStatus sessionStatus = CPA_STATUS_SUCCESS;

        /* Perform Compression operation */
        status = compPerformOp(dcInstHandle, sessionHdl, sd);

        /*
         * In a typical usage, the session might be used to compression
         * multiple buffers.  In this example however, we can now
         * tear down the session.
         */
        PRINT_DBG("cpaDcRemoveSession\n");
        sessionStatus = cpaDcRemoveSession(
                dcInstHandle, sessionHdl);

        /* Maintain status of remove session only when status of all operations
         * before it are successful. */
        if (CPA_STATUS_SUCCESS == status)
        {
            status = sessionStatus;
        }
    }

    if (CPA_STATUS_SUCCESS == status)
    {
        /*
         * We can now query the statistics on the instance.
         *
         * Note that some implementations may also make the stats
         * available through other mechanisms, e.g. in the /proc
         * virtual filesystem.
         */
        status = cpaDcGetStats(dcInstHandle, &dcStats);

        if (CPA_STATUS_SUCCESS != status)
        {
            PRINT_ERR("cpaDcGetStats failed, status = %d\n", status);
        }
        else
        {
            PRINT_DBG("Number of compression operations completed: %llu\n",
                        (unsigned long long)dcStats.numCompCompleted);
            PRINT_DBG("Number of decompression operations completed: %llu\n",
                    (unsigned long long)dcStats.numDecompCompleted);
        }
    }

    /*
     * Free up memory, stop the instance, etc.
     */

    /* Stop the polling thread */
    sampleDcStopPolling();

    PRINT_DBG("cpaDcStopInstance\n");
    cpaDcStopInstance(dcInstHandle);

    /* Free session Context */
    PHYS_CONTIG_FREE(sessionHdl);

    /* Free intermediate buffer */
    if(bufferInterArray != NULL)
    {
        for(bufferNum = 0; bufferNum < numInterBuffLists; bufferNum++)
        {
            PHYS_CONTIG_FREE(bufferInterArray[bufferNum]->pBuffers->pData);
            PHYS_CONTIG_FREE(bufferInterArray[bufferNum]->pBuffers);
            PHYS_CONTIG_FREE(bufferInterArray[bufferNum]->pPrivateMetaData);
            PHYS_CONTIG_FREE(bufferInterArray[bufferNum]);
        }
        PHYS_CONTIG_FREE(bufferInterArray);
    }
    if (CPA_STATUS_SUCCESS == status)
    {
        PRINT_DBG("Sample code ran successfully\n");
    }
    else
    {
        PRINT_DBG("Sample code failed with status of %d\n", status);
    }

    return status;
}
Exemplo n.º 12
0
Food* IngridientWindow::createNewFood(void) {
    bool isKg = !ui->comboBox_1->currentText().toStdString().compare("kg");

    PRINT_DEBUG("Creating new food");

    QString name = ui->lineEdit_1->text();
    QString mass = ui->lineEdit_2->text();
    QString price = ui->lineEdit_4->text();
    QString fats = ui->lineEdit_3->text();
    QString proteins = ui->lineEdit_5->text();
    QString carbohydrates = ui->lineEdit_6->text();
    QString calories = ui->lineEdit_7->text();

    if ( name.isEmpty() ) {
        PRINT_ERR("Food name could not be empty");

        throw EmptyIngridientNameException();
    }

    if ( mass.isEmpty() && !isKg ) {
        PRINT_ERR("Food mass could not be empty");

        throw EmptyIngridientMassException();
    }

    if ( price.isEmpty() ) {
        PRINT_ERR("Food price could not be empty");

        throw EmptyIngridientPriceException();
    }

    if ( fats.isEmpty() ) {
        PRINT_ERR("Food fats could not be empty");

        throw EmptyIngridientFatsException();
    }

    if ( proteins.isEmpty() ) {
        PRINT_ERR("Food proteins could not be empty");

        throw EmptyIngridientProteinsException();
    }

    if ( carbohydrates.isEmpty() ) {
        PRINT_ERR("Food carbohydrates could not be empty");

        throw EmptyIngridientCarbohydratesException();
    }

    if ( calories.isEmpty() ) {
        PRINT_ERR("Food calories could not be empty");

        throw EmptyIngridientCaloriesException();
    }

    return new Food(name.toStdString(), isKg ? 1 : QStringToMass(mass),
                    QStringToPrice(price), static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex()),
                    QStringToFats(fats),
                    QStringToProteins(proteins),
                    QStringToCarbohydrates(carbohydrates),
                    QStringToCalories(calories));
}
Exemplo n.º 13
0
/**
 *****************************************************************************
 * @ingroup dsaPerformance
 *      setupDsaTest
 *
 * @description
 *     This function setups up a DSA thread. Once called the user then calls the
 *      createThreads function which replicates this setup in threads across
 *      several cores, each using a separate acceleration engine instances
 *
 *****************************************************************************/
CpaStatus setupDsaTest(Cpa32U pLenInBits, Cpa32U qLenInBits,
        sync_mode_t syncMode, Cpa32U numBuffers, Cpa32U numLoops)
{
    /*setup is a multi-dimensional array that stores the setup for all thread
     * variations in an array of characters. We store our test setup at the
     * start of the second array ie index 0, [][0].
     * There may be multi thread types(setups) running as counted by
     * testTypeCount_g */

    /*as setup is a multi-dimensional char array we need to cast it to the
     * symmetric structure */
    dsa_test_params_t* dsaSetup = NULL;

    if(testTypeCount_g >= MAX_THREAD_VARIATION)
    {
        PRINT_ERR("Maximum Supported Thread Variation has been exceeded\n");
        PRINT_ERR("Number of Thread Variations created: %d",
                testTypeCount_g);
        PRINT_ERR(" Max is %d\n", MAX_THREAD_VARIATION);
        return CPA_STATUS_FAIL;
    }

    /*start crypto service if not already started */
    if(CPA_STATUS_SUCCESS != startCyServices())
    {
        PRINT_ERR("Error starting Crypto Services\n");
        return CPA_STATUS_FAIL;
    }
    if(!poll_inline_g)
    {
        /* start polling threads if polling is enabled in the configuration file */
        if(CPA_STATUS_SUCCESS != cyCreatePollingThreadsIfPollingIsEnabled())
        {
            PRINT_ERR("Error creating polling threads\n");
            return CPA_STATUS_FAIL;
        }
    }

    testSetupData_g[testTypeCount_g].performance_function =
        (performance_func_t)dsaPerformance;
    testSetupData_g[testTypeCount_g].packetSize=
        pLenInBits/NUM_BITS_IN_BYTE;
    dsaSetup =
        (dsa_test_params_t*)&thread_setup_g[testTypeCount_g][0];
    /*then we store the test setup in the above location */
    if(MODULUS_1024_BIT == pLenInBits && EXPONENT_160_BIT == qLenInBits)
    {
        dsaSetup->hashAlg = CPA_CY_SYM_HASH_SHA1;
    }
    else if(MODULUS_2048_BIT == pLenInBits && EXPONENT_224_BIT == qLenInBits)
    {
        dsaSetup->hashAlg = CPA_CY_SYM_HASH_SHA224;
    }
    else if(MODULUS_2048_BIT == pLenInBits && EXPONENT_256_BIT == qLenInBits)
    {
        dsaSetup->hashAlg = CPA_CY_SYM_HASH_SHA256;
    }
    else if(MODULUS_3072_BIT == pLenInBits && EXPONENT_256_BIT == qLenInBits)
    {
        dsaSetup->hashAlg = CPA_CY_SYM_HASH_SHA256;
    }
    else
    {
        PRINT_ERR("pLen & qLen combination not supported, must be 1024/160 ");
        PRINT("2048/224, 2048/256 or 3072/256\n");
        return CPA_STATUS_FAIL;
    }
    dsaSetup->pLenInBytes = pLenInBits/NUM_BITS_IN_BYTE;
    dsaSetup->qLenInBytes = qLenInBits/NUM_BITS_IN_BYTE;
    dsaSetup->syncMode = syncMode;
    dsaSetup->numBuffers = numBuffers;
    dsaSetup->numLoops = numLoops;

    return CPA_STATUS_SUCCESS;
}
Exemplo n.º 14
0
/**
 *****************************************************************************
 * @ingroup dsaPerformance
 *      dsaPerformance
 *
 * @description
 *     This function is called by the framework to execute the dsaPerform
 *     thread
 *
 *****************************************************************************/
void dsaPerformance(single_thread_test_data_t* testSetup)
{
    dsa_test_params_t dsaSetup;
    Cpa16U numInstances = 0;
    CpaInstanceHandle *cyInstances = NULL;
    CpaStatus status = CPA_STATUS_FAIL;
    dsa_test_params_t* params = (dsa_test_params_t*)testSetup->setupPtr;
    CpaInstanceInfo2 instanceInfo = {0};

    /*this barrier is to halt this thread when run in user space context, the
     * startThreads function releases this barrier, in kernel space it does
     * nothing, but kernel space threads do not start until we call startThreads
     * anyway */
    startBarrier();
    /*give our thread a unique memory location to store performance stats */
    dsaSetup.threadID = testSetup->threadID;
    dsaSetup.performanceStats = testSetup->performanceStats;
    dsaSetup.hashAlg= params->hashAlg;
    dsaSetup.pLenInBytes= params->pLenInBytes;
    dsaSetup.qLenInBytes= params->qLenInBytes;
    dsaSetup.numBuffers = params->numBuffers;
    dsaSetup.numLoops = params->numLoops;
    dsaSetup.syncMode = params->syncMode;
    /*get the instance handles so that we can start our thread on the selected
     * instance */
    status = cpaCyGetNumInstances(&numInstances);
    if(CPA_STATUS_SUCCESS != status || numInstances == 0)
    {
        PRINT_ERR("Could not get any instances\n");
        PRINT_ERR("DSA Thread FAILED\n");
        dsaSetup.performanceStats->threadReturnStatus = CPA_STATUS_FAIL;
        sampleCodeThreadExit();
    }
    cyInstances = qaeMemAlloc(sizeof(CpaInstanceHandle) * numInstances);
    if(NULL == cyInstances)
    {
        PRINT_ERR("Could not allocate memory for logical instances\n");
        dsaSetup.performanceStats->threadReturnStatus = CPA_STATUS_FAIL;
        sampleCodeThreadExit();
    }
    cpaCyGetInstances(numInstances, cyInstances);
    /* give our thread a logical crypto instance to use
     * use % to wrap around the max number of instances */
    dsaSetup.cyInstanceHandle =
        cyInstances[(testSetup->logicalQaInstance)%numInstances];

    status = cpaCyInstanceGetInfo2(dsaSetup.cyInstanceHandle,
                &instanceInfo);
    if(CPA_STATUS_SUCCESS != status)
    {
        PRINT_ERR("%s::%d cpaCyInstanceGetInfo2 failed", __func__,__LINE__);
        qaeMemFree((void**)&cyInstances);
        dsaSetup.performanceStats->threadReturnStatus = CPA_STATUS_FAIL;
        sampleCodeThreadExit();
    }
    if(instanceInfo.physInstId.packageId > packageIdCount_g)
    {
        packageIdCount_g = instanceInfo.physInstId.packageId;
    }

    /*launch function that does all the work */
    status = dsaPerform(&dsaSetup);
    if(CPA_STATUS_SUCCESS != status)
    {
        PRINT("DSA Thread %u FAILED\n", testSetup->threadID);
        dsaSetup.performanceStats->threadReturnStatus = CPA_STATUS_FAIL;
    }
    else
    {
		/*set the print function that can be used to print stats at the end of
         * the test */
        testSetup->statsPrintFunc=(stats_print_func_t)dsaPrintStats;
    }
    qaeMemFree((void**)&cyInstances);
    sampleCodeThreadExit();
}
Exemplo n.º 15
0
int main(int narg, char *argp[])
{
    int optc;

    struct styrerapp styrerobj;
    memset(&styrerobj, 0, sizeof(styrerobj)); 

	char *get_livedata  = NULL;
	enum endata_type get_endata = ENDATA_NONE;
	int do_waitsec = 0;

    while ((optc = getopt(narg, argp, "w::i:l::e::s::d::h")) > 0) {
		switch (optc){ 
		  case 'w':
			if(optarg)
				do_waitsec = atoi(optarg);
			else 
				do_waitsec = 60*10;
			break;
		  case 'c':
			styrerobj.cmdname_control = strdup(optarg);
			break;
		  case 'i':
			styrerobj.inst_id = atoi(optarg);
			break;
		  case 'l':
			if(optarg)
				get_livedata =strdup(optarg);
			else
				get_livedata = "*.*";
			break;
		  case 'e': // test endata interface 
			if(optarg)
				get_endata = atoi(optarg);
			else
				get_endata = ENDATA_ALL;
			break;
		  case 's': // Run schedule planner
			if(optarg){
				styrerobj.schedule_type = strdup(optarg);
			} else {
				styrerobj.schedule_type = strdup(DEFAULT_SCH_PLANNER);
			}
			break;
		  case 'd':
			if(optarg)
				styrerobj.dbglev = atoi(optarg);
			else
				styrerobj.dbglev = 1;
			break;
		  default: /* also h */
			fprintf(stderr, "%s", HelpText);
			exit(0);
			break;
		}
    }

	/* init defaults */

	if(!styrerobj.cmdname_modesch)
		styrerobj.cmdname_modesch = strdup(DEFAULT_CMD_MDSCH);

	if(!styrerobj.cmdname_control){
		styrerobj.cmdname_control = strdup(DEFAULT_CMD_CNTL);
	}

	if(!styrerobj.inst_id){
		styrerobj.inst_id = enstyrerapp_get_inst_id(styrerobj.dbglev);
	}

	/* Do wait to balance load */
	if(do_waitsec)
		enstyrapp_wait_rand(styrerobj.inst_id, do_waitsec);

	/* run test functions if requested */
	if(get_endata != ENDATA_NONE){
		return enapptest_endata(styrerobj.inst_id, styrerobj.dbglev);
	}
	
	if(get_livedata)
		return enapptest_contlive(get_livedata, styrerobj.dbglev);
	
	/* init logdb */
    if((styrerobj.logdb = logdb_open(NULL,  DEFAULT_TIMEOUT, styrerobj.dbglev))==NULL){
		PRINT_ERR("Error opening logdb\n");
		return -1;
    }
	
    PRINT_DBG(styrerobj.dbglev, "logdb opened\n");
    
	/* init commands in cmddb */
	if(cmddb_db_open(NULL, styrerobj.dbglev)<0){
		fprintf(stderr, "error opening cmddb\n");
		return -1;
    }

    PRINT_DBG(styrerobj.dbglev, "cmddb opened\n");
	
    styrerobj.descs = cmddb_desc_add(styrerobj.descs, 
									 cmdvar_initdef(styrerobj.cmdname_modesch, DEFAULT_SCH_PLANNER, &styrerobj.cmdtype));
    
	PRINT_DBG(styrerobj.dbglev, "cmddb descriptor created: %p\n", styrerobj.descs);

	cmddb_exec_list(styrerobj.descs, &styrerobj, time(NULL));

	if(!styrerobj.schedule_type)
		styrerobj.schedule_type = timevar_readcp(&styrerobj.cmdtype);

	PRINT_DBG(styrerobj.dbglev, "schedule mode '%s'\n", styrerobj.schedule_type);

	/* run scheduling */
	encontrol_simp_calc(styrerobj.inst_id      , styrerobj.logdb, 
						styrerobj.schedule_type, styrerobj.dbglev );
	
	/* deinit */
    cmddb_desc_delete(styrerobj.descs);
    logdb_close(styrerobj.logdb);
    cmddb_db_close();

	free(styrerobj.cmdname_modesch);
	free(styrerobj.schedule_type);
	free(styrerobj.cmdname_control);
	
    return 0;
}
Exemplo n.º 16
0
int asocket_con_rcv(struct asocket_con* sk_con, struct skcmd **rx_msg)
{
    int rx_len = 0;
    char *rx_buf = malloc(SOCKET_TC_BUF_LEN);
    int retval = 0;
    char errmsg[128];
     
    assert(rx_buf);
    //asocket_cmd_init(rx_msg, NULL);

//    fprintf(stderr, "waiting\n");

    while(1){
        retval = recv(sk_con->fd, rx_buf+rx_len, (SOCKET_TC_BUF_LEN-1)-rx_len, 0);

	if(retval < 0)
		goto out;

	rx_len += retval;
    
        rx_buf[rx_len] = '\0';

        PRINT_DBG(sk_con->dbglev, "rx_len %d \"%s\"\n", rx_len, rx_buf);

        
        if(rx_len == 0){
	    PRINT_DBG(sk_con->dbglev, "EOF\n");
            sk_con->run = 0;
            goto out;
        } else if(rx_len <= 0){
            switch(errno){
              case EAGAIN: /* timeout */
/*                 if((retval = asocket_con_snd_vp(sk_con, "Alive",0))<0){ */
/*                     fprintf(stderr, "snd ret: %d\n", retval); */
/*                     sk_con->run = 0; */
/*                     goto out; */
/*                 } */
                rx_len = 0;
                continue;
              default:
                PRINT_ERR( "Socket returned: %d , %s (%d)\n", rx_len, strerror(errno), errno);
                break;
            }
            retval = -errno;
            sk_con->run = 0;
            goto out;
        } /* else { */
/*             break; */
/*         } */
//        fprintf(stderr, "cmd_len %d\n");

        retval = asocket_cmd_read(rx_msg, rx_buf, rx_len, errmsg);
        
        if(retval > 0){ 
            break;
        } else if(retval < 0){
            asocket_con_snd_nack(sk_con,errmsg);
            retval = 0;
            goto out;
        } 
    }

    PRINT_DBG(sk_con->dbglev, "cmd_read %d\n", retval);
     
  out:
    free(rx_buf);

    return retval;
}
Exemplo n.º 17
0
// Setup branch addresses for each track attribute
  int
EventReader::loadBranches (TTree *tree, const char* prefix)
{
  const std::string bNamePrefix = prefix;

  std::string bName;

  bName = bNamePrefix + kLocX;
  if (tree->SetBranchAddress (bName.c_str ( ), &mLocX) != 0) {
    PRINT_ERR ("SetBranchAddress failed for locX");
    return -1;
  }

  bName = bNamePrefix + kLocY;
  if (tree->SetBranchAddress (bName.c_str ( ), &mLocY) != 0) {
    PRINT_ERR ("SetBranchAddress failed for locY");
    return -1;
  }

  bName = bNamePrefix + kErrLocX;
  if (tree->SetBranchAddress (bName.c_str ( ), &mErr_locX) != 0) {
    PRINT_ERR ("SetBranchAddress failed for err_locX");
    return -1;
  }

  bName = bNamePrefix + kErrLocY;
  if (tree->SetBranchAddress (bName.c_str ( ), &mErr_locY) != 0) {
    PRINT_ERR ("SetBranchAddress failed for err_locY");
    return -1;
  }

  bName = bNamePrefix + kCovLocXY;
  if (tree->SetBranchAddress(bName.c_str(), &mCov_locXY) != 0) {
    PRINT_ERR("SetBranchAddress failed for cov_locXY");
    return -1;
  }
#if HAS_MATERIAL_EFFECTS
  bName = bNamePrefix + kSigmaDeltaPhiScat;
  if (tree->SetBranchAddress(bName.c_str(), &mSigmaDeltaPhi) != 0) {
    PRINT_ERR("SetBranchAddress failed for SigmaDeltaPhiScat");
    return -1;
  }
  bName = bNamePrefix + kSigmaDeltaThetaScat;
  if (tree->SetBranchAddress(bName.c_str(), &mSigmaDeltaTheta) != 0) {
    PRINT_ERR("SetBranchAddress failed for SigmaDeltaThetaScat");
    return -1;
  }
  bName = bNamePrefix + kSigmaDeltaEloss;
  if (tree->SetBranchAddress(bName.c_str(), &mSigmaDeltaE) != 0) {
    PRINT_ERR("SetBranchAddress failed for SigmaDeltaEloss");
    return -1;
  }
#endif // #if HAS_MATERIAL_EFFECTS

  bName = bNamePrefix + kDetType;
  if (tree->SetBranchAddress (bName.c_str ( ), &mDetType) != 0) {
    PRINT_ERR ("SetBranchAddress failed for detType");
    return -1;
  }

  bName = bNamePrefix + kBEC;
  if (tree->SetBranchAddress (bName.c_str ( ), &mBec) != 0) {
    PRINT_ERR ("SetBranchAddress failed for bec");
    return -1;
  }

  bName = bNamePrefix + kRefLocX;
  if (tree->SetBranchAddress (bName.c_str ( ), &mRefLocX) != 0) {
    PRINT_ERR ("SetBranchAddress failed for refLocX");
    return -1;
  }

  bName = bNamePrefix + kRefLocY;
  if (tree->SetBranchAddress (bName.c_str ( ), &mRefLocY) != 0) {
    PRINT_ERR ("SetBranchAddress failed for refLocY");
    return -1;
  }

  bName = bNamePrefix + kRefPhi;
  if (tree->SetBranchAddress (bName.c_str ( ), &mRefPhi) != 0) {
    PRINT_ERR ("SetBranchAddress failed for refPhi");
    return -1;
  }

  bName = bNamePrefix + kRefTheta;
  if (tree->SetBranchAddress (bName.c_str ( ), &mRefTheta) != 0) {
    PRINT_ERR ("SetBranchAddress failed for refTheta");
    return -1;
  }

  bName = bNamePrefix + kRefQoverP;
  if (tree->SetBranchAddress (bName.c_str ( ), &mRefQoverP)
      != 0) {
    PRINT_ERR ("SetBranchAddress failed for refQoverP");
    return -1;
  }

  bName = bNamePrefix + kQoverP;
  if (tree->SetBranchAddress (bName.c_str ( ), &mQoverP) != 0) {
    PRINT_ERR ("SetBranchAddress failed for qoverp");
    return -1;
  }

  bName = bNamePrefix + kD0;
  if (tree->SetBranchAddress (bName.c_str ( ), &mD0) != 0) {
    PRINT_ERR ("SetBranchAddress failed for d0");
    return -1;
  }

  bName = bNamePrefix + kZ0;
  if (tree->SetBranchAddress (bName.c_str ( ), &mZ0) != 0) {
    PRINT_ERR ("SetBranchAddress failed for z0");
    return -1;
  }

  bName = bNamePrefix + kPhi;
  if (tree->SetBranchAddress (bName.c_str ( ), &mPhi) != 0) {
    PRINT_ERR ("SetBranchAddress failed for phi");
    return -1;
  }

  bName = bNamePrefix + kTheta;
  if (tree->SetBranchAddress (bName.c_str ( ), &mTheta) != 0) {
    PRINT_ERR ("SetBranchAddress failed for theta");
    return -1;
  }

  // Jacobian Matrix elements row 0
  bName = bNamePrefix + kTransportJac00;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (0))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac00");
    return -1;
  }

  bName = bNamePrefix + kTransportJac01;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (1))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac01");
    return -1;
  }

  bName = bNamePrefix + kTransportJac02;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (2))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac02");
    return -1;
  }

  bName = bNamePrefix + kTransportJac03;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (3))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac03");
    return -1;
  }

  bName = bNamePrefix + kTransportJac04;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (4))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac04");
    return -1;
  }

  // Jacobian Matrix elements row 1
  bName = bNamePrefix + kTransportJac10;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (5))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac10");
    return -1;
  }

  bName = bNamePrefix + kTransportJac11;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (6))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac11");
    return -1;
  }

  bName = bNamePrefix + kTransportJac12;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (7))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac12");
    return -1;
  }

  bName = bNamePrefix + kTransportJac13;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (8))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac13");
    return -1;
  }

  bName = bNamePrefix + kTransportJac14;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (9))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac14");
    return -1;
  }

  // Jacobian Matrix elements row 2
  bName = bNamePrefix + kTransportJac20;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (10))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac20");
    return -1;
  }

  bName = bNamePrefix + kTransportJac21;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (11))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac21");
    return -1;
  }

  bName = bNamePrefix + kTransportJac22;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (12))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac22");
    return -1;
  }

  bName = bNamePrefix + kTransportJac23;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (13))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac23");
    return -1;
  }

  bName = bNamePrefix + kTransportJac24;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (14))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac24");
    return -1;
  }

  // Jacobian Matrix elements row 3
  bName = bNamePrefix + kTransportJac30;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (15))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac30");
    return -1;
  }

  bName = bNamePrefix + kTransportJac31;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (16))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac31");
    return -1;
  }

  bName = bNamePrefix + kTransportJac32;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (17))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac32");
    return -1;
  }

  bName = bNamePrefix + kTransportJac33;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (18))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac33");
    return -1;
  }

  bName = bNamePrefix + kTransportJac34;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (19))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac34");
    return -1;
  }

  // Jacobian Matrix elements row 4
  bName = bNamePrefix + kTransportJac40;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (20))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac40");
    return -1;
  }

  bName = bNamePrefix + kTransportJac41;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (21))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac41");
    return -1;
  }

  bName = bNamePrefix + kTransportJac42;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (22))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac42");
    return -1;
  }

  bName = bNamePrefix + kTransportJac43;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (23))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac43");
    return -1;
  }

  bName = bNamePrefix + kTransportJac44;
  if (tree->SetBranchAddress (bName.c_str ( ), &(mJacobi->at (24))) != 0) {
    PRINT_ERR ("SetBranchAddress failed for Jac44");
    return -1;
  }

  bName = bNamePrefix + kMci;
  if (tree->SetBranchAddress(bName.c_str(), &(mMCI)) != 0) {
    PRINT_ERR("SetBranchAddress failed for MCI");
    return -1;
  }

  bName = kMcPerigeeOk;
  if (tree->SetBranchAddress(bName.c_str(), &(mMCPerigeeOk)) != 0) {
    PRINT_ERR("SetBranchAddress failed for MCPerigeeOk");
    return -1;
  }

  bName = kTti;
  if (tree->SetBranchAddress(bName.c_str(), &(mTTTI)) != 0) {
    PRINT_ERR("SetBranchAddress failed for TTI");
    return -1;
  }

  bName = kTti;
  if (tree->SetBranchAddress(bName.c_str(), &(mTTTI)) != 0) {
    PRINT_ERR("SetBranchAddress failed for TTI");
    return -1;
  }

  //bName = "truthtrack_" + kQoverP;
  bName = "mc_perigee_" + kQoverP;
  if (tree->SetBranchAddress(bName.c_str(), &mTTQoverP) != 0) {
    PRINT_ERR("SetBranchAddress failed for qoverp");
    return -1;
  }

  //bName = "truthtrack_" + kD0;
  bName = "mc_perigee_" + kD0;
  if (tree->SetBranchAddress(bName.c_str(), &mTTD0) != 0) {
    PRINT_ERR("SetBranchAddress failed for d0");
    return -1;
  }

  //bName = "truthtrack_" + kZ0;
  bName = "mc_perigee_" + kZ0;
  if (tree->SetBranchAddress(bName.c_str(), &mTTZ0) != 0) {
    PRINT_ERR("SetBranchAddress failed for z0");
    return -1;
  }

  //bName = "truthtrack_" + kPhi;
  bName = "mc_perigee_" + kPhi;
  if (tree->SetBranchAddress(bName.c_str(), &mTTPhi) != 0) {
    PRINT_ERR("SetBranchAddress failed for phi");
    return -1;
  }

  //bName = "truthtrack_" + kTheta;
  bName = "mc_perigee_" + kTheta;
  if (tree->SetBranchAddress(bName.c_str(), &mTTTheta) != 0) {
    PRINT_ERR("SetBranchAddress failed for theta");
    return -1;
  }

  //rots
#if HAS_COMPETING_ROTS
  //
  bName = bNamePrefix + kCompetingRotIds;
  //
  if (tree->SetBranchAddress(bName.c_str(), &mCompetingRotIds) != 0) {
    PRINT_ERR("SetBranchAddress failed for mCompetingRotIds");
    return -1;
  }

  bName = bNamePrefix + kRotLocX;

  if (tree->SetBranchAddress(bName.c_str(), &mRotLocX) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotLocX");
    return -1;
  }
  //    std::cout << bName << " " << mRotLocX->size() << std::endl;
  bName = bNamePrefix + kRotLocY;
  if (tree->SetBranchAddress(bName.c_str(), &mRotLocY) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotLocY");
    return -1;
  }

  bName = bNamePrefix + kRotIds;
  if (tree->SetBranchAddress(bName.c_str(), &mRotIds) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotIds");
    return -1;
  }

  bName = bNamePrefix + kRotProbs;
  if (tree->SetBranchAddress(bName.c_str(), &mRotProbs) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotProbs");
    return -1;
  }
  bName = bNamePrefix + kRotCov00;
  if (tree->SetBranchAddress(bName.c_str(), &mRotCov00) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotCov00 = 0;");
    return -1;
  }
  bName = bNamePrefix + kRotCov01;
  if (tree->SetBranchAddress(bName.c_str(), &mRotCov01) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotCov01 = 0;");
    return -1;
  }
  bName = bNamePrefix + kRotCov10;
  if (tree->SetBranchAddress(bName.c_str(), &mRotCov10) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotCov10 = 0;");
    return -1;
  }
  bName = bNamePrefix + kRotCov11;
  if (tree->SetBranchAddress(bName.c_str(), &mRotCov11) != 0) {
    PRINT_ERR("SetBranchAddress failed for mRotCov11 = 0;");
    return -1;
  }
#endif
  //end rots

  return 0;
}
Exemplo n.º 18
0
static int
armadillo_mtd_probe(struct platform_device *pdev)
{
	struct armadillo_flash_private_data *priv = pdev->dev.platform_data;
	struct flash_platform_data *plat = &priv->plat;
	struct resource *res;
	unsigned int region_size;
	struct armadillo_flash_info *info;
	int err;
	int default_parts = 0;

	info = kmalloc(sizeof(struct armadillo_flash_info), GFP_KERNEL);
	if (!info) {
		err = -ENOMEM;
		goto out;
	}

	memset(info, 0, sizeof(struct armadillo_flash_info));

	info->plat = plat;
	if (plat && plat->init) {
		err = plat->init();
		if (err)
			goto no_resource;
	}

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		err = -ENOMEM;
		goto no_resource;
	}
	region_size = res->end - res->start + 1;

	info->res = request_mem_region(res->start, region_size, "mtd");
	if (!info->res) {
		err = -EBUSY;
		goto no_resource;
	}

	/*
	 * look for CFI based flash parts fitted to this board
	 */
	info->map.size		= region_size;
	info->map.bankwidth	= plat->width;
	info->map.phys		= res->start;
	info->map.virt		= (void __iomem *)CS0_BASE_ADDR_VIRT;
	info->map.name		= priv->map_name;
	info->map.set_vpp	= 0;

	simple_map_init(&info->map);

	/*
	 * Also, the CFI layer automatically works out what size
	 * of chips we have, and does the necessary identification
	 * for us automatically.
	 */
	info->mtd = do_map_probe(plat->map_name, &info->map);
	if (!info->mtd) {
		err = -ENXIO;
		goto no_device;
	}

	info->mtd->owner = THIS_MODULE;

	err = parse_mtd_partitions(info->mtd, probes, &info->parts, 0);
	if (err > 0) {
		PRINT_INFO("use cmdline partitions(%d)\n", err);
		err = add_mtd_partitions(info->mtd, info->parts, err);
		if (err) {
			PRINT_ERR("mtd partition registration failed: %d\n",
				  err);
			default_parts = 1;
		}
	} else {
		default_parts = 1;
	}

	if (default_parts) {
		if (priv && priv->update_partitions)
			priv->update_partitions(&info->map, plat);

		PRINT_INFO("use default partitions(%d)\n", plat->nr_parts);
		err = add_mtd_partitions(info->mtd,
					 plat->parts, plat->nr_parts);
		if (err)
			PRINT_ERR("mtd partition registration failed: %d\n",
				  err);
	}

	if (err == 0)
		platform_set_drvdata(pdev, info);

	/*
	 * If we got an error, free all resources.
	 */
	if (err < 0) {
		if (info->mtd) {
			del_mtd_partitions(info->mtd);
			map_destroy(info->mtd);
		}
		if (info->parts)
			kfree(info->parts);

 no_device:
		release_mem_region(res->start, region_size);
 no_resource:
		if (plat && plat->exit)
			plat->exit();
		kfree(info);
	}
 out:
	return err;
}
Exemplo n.º 19
0
// Parse the root file located at path and parse the Ttree treeName.
// prefix identifies the track which is to be used, e.g.
// trk_, trkSiSpSeeded_, pseudoTrk_
  int
EventReader::parse (const char* path, const char* treeName, const char* prefix)
{
  TFile *file;
  TTree *tree;

  // Open data file and read TTree
  file = new TFile (path, "READ", "TrackFitData Access");

  if (!file) {
    std::cerr << "Could not open " << path << std::endl;
    return -1;
  }

  tree = ( TTree* )file->Get (treeName);

  if (!tree) {
    std::cerr << "Could not get tree " << treeName << std::endl;
    delete file;
    return -1;
  }

  // Read events and their tracks. Each data attribute is represented
  // by a branch in the TTree.
  resetAttributeVectors ( );

  if (loadBranches (tree, prefix) == -1) {
    PRINT_ERR ("loadBranches failed!");
    resetAttributeVectors ( );
    delete file;
    return -1;
  }

  mEvents.clear ( );

  // Loop over all events
  for (Long64_t events = 0; events < tree->GetEntriesFast ( ); ++events) {
    Long64_t local_events = tree->LoadTree (events);

    if (local_events < 0) {
      PRINT_ERR ("LoadTree returned value < 0");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    // Load branches into the matching vectors
    if (tree->GetEntry (events) <= 0) {
      PRINT_ERR ("tree->GetEntry failed!");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    if (eventSanityCheck ( ) == -1) {
      PRINT_ERR ("Event sanity check failed!");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    KF_Event_t newEvent;
    Track_t newTrack;
    TrackHit_t trackHit;
#if HAS_COMPETING_ROTS
    for (int i = 0; i < MAXROTS; ++i) {
      trackHit.rotIds[i] = 0;
    }
#endif
    newEvent.clear();

    // Loop over all tracks
    for (unsigned int track = 0; track < mLocX->size ( ); ++track) {
      newTrack.track.clear ( );

      // phi, theta, qoverp are values referring to a complete track
      newTrack.info.d0     = (*mD0)[track];
      newTrack.info.z0     = (*mZ0)[track];
      newTrack.info.phi    = (*mPhi)[track];
      newTrack.info.theta  = (*mTheta)[track];
      newTrack.info.qoverp = (*mQoverP)[track];

      // FIXME: has to check whether MC index is valid!
      //int tti = (*mTTTI)[ (*mMCI)[track] ];
      // FIXME: has to check whether truth track index is valid!
      //std::cout << "Track:" << track <<  " TruthTrackIndex: " << tti <<std::endl;
      newTrack.truthTrackInfo.d0 = -999.;
      newTrack.truthTrackInfo.z0 = -999.;
      newTrack.truthTrackInfo.phi = -999.;
      newTrack.truthTrackInfo.theta = -999.;
      newTrack.truthTrackInfo.qoverp = -999.;
      int mcindex = (*mMCI)[track];
      if (mcindex > -1) {
	if (mMCPerigeeOk->at(mcindex)) {
	  newTrack.truthTrackInfo.d0 = (*mTTD0)[mcindex];
	  newTrack.truthTrackInfo.z0 = (*mTTZ0)[mcindex];
	  newTrack.truthTrackInfo.phi = (*mTTPhi)[mcindex];
	  newTrack.truthTrackInfo.theta = (*mTTTheta)[mcindex];
	  newTrack.truthTrackInfo.qoverp = (*mTTQoverP)[mcindex];
	}
      }
      bool validTrack = true;
      //             std::cout<< "track " << track << std::endl;
      // Loop over all hits
      for (unsigned int hit = 0; hit < (*mLocX)[track].size ( ); ++hit) {
	// No NULL-pointer check, since eventSanityCheck passed
	trackHit.normal[0]  = (*mLocX)[track][hit];
	trackHit.normal[1]  = (*mLocY)[track][hit];
	trackHit.err_locX   = (*mErr_locX)[track][hit];
	trackHit.err_locY   = (*mErr_locY)[track][hit];
	trackHit.cov_locXY  = (*mCov_locXY)[track][hit];
	trackHit.detType    = (*mDetType)[track][hit];
	trackHit.bec        = (*mBec)[track][hit];
	trackHit.ref[0]     = (*mRefLocX)[track][hit];
	trackHit.ref[1]     = (*mRefLocY)[track][hit];
	trackHit.ref[2]     = (*mRefPhi)[track][hit];
	trackHit.ref[3]     = (*mRefTheta)[track][hit];
	trackHit.ref[4]     = (*mRefQoverP)[track][hit];
#if HAS_MATERIAL_EFFECTS
	trackHit.sigmaDeltaThetaSquared = pow(mSigmaDeltaTheta->at(track).at(hit), 2);
	trackHit.sigmaDeltaPhiSquared = pow(mSigmaDeltaPhi->at(track).at(hit), 2);
	//trackHit.sigmaDeltaQoverPSquared = (trackHit.ref[4]*trackHit.ref[4]>0.) ? ( mSigmaDeltaE->at(track).at(hit) * sqrt(PionMassSquared + 1./(trackHit.ref[4]*trackHit.ref[4])) * fabs(pow(trackHit.ref[4],3)) ) : 0.;
	const double qOverPSquared=trackHit.ref[4]*trackHit.ref[4];
	trackHit.sigmaDeltaQoverPSquared = (qOverPSquared>0.) ? ( pow(mSigmaDeltaE->at(track).at(hit),2) * (PionMassSquared + 1./qOverPSquared) * pow(qOverPSquared,3) ) : 0.;
#endif // #if HAS_MATERIAL_EFFECTS
#if HAS_COMPETING_ROTS
	trackHit.competingRotIds = (*mCompetingRotIds)[track][hit];
	//std::cout << "read compRot " << trackHit.competingRotIds << " track " << track << " hit " << hit << std::endl;
	for (unsigned int rot = 0; rot < (*mRotLocX)[track][hit].size(); ++rot) {
	  trackHit.rotLocX[rot] = (*mRotLocX)[track][hit][rot];
	  trackHit.rotLocY[rot] = (*mRotLocY)[track][hit][rot];
	  trackHit.rotIds[rot] = (*mRotIds)[track][hit][rot];
	  trackHit.rotProbs[rot] = (*mRotProbs)[track][hit][rot];

	  trackHit.rotCov[rot][0] = (*mRotCov00)[track][hit][rot];
	  trackHit.rotCov[rot][1] = (*mRotCov01)[track][hit][rot];
	  trackHit.rotCov[rot][2] = (*mRotCov10)[track][hit][rot];
	  trackHit.rotCov[rot][3] = (*mRotCov11)[track][hit][rot];
	  //                    if (DBG_LVL == 0) if ((*mRotLocY)[track][hit].size() > 1) std::cout << rot << "/" << (*mRotLocY)[track][hit].size() - 1 << " id " << trackHit.rotIds[rot] << " locY " << trackHit.rotLocY[rot] << " effY " << trackHit.measurement[1] << " cov " << trackHit.rotCov[rot][1] << std::endl;
	  //                    std::cout << "\trot " << trackHit.rotIds[rot] << std::endl;
	}
#endif
	if (abs(trackHit.normal[1] + 99999.) > 1.E-4) {
	  trackHit.is2Dim = 1;
	} else {
	  trackHit.is2Dim = 0;
	}
	// no measurement at all (pure material surface):
	if (!(fabs(trackHit.normal[0] + 99999.) > 1.E-4)) {
	  trackHit.is2Dim = 3;
	  //                     std::cout<< "mat lay: sigmaDeltaPhi=" << mSigmaDeltaPhi->at(track).at(hit)
	  //                              << " sigmaDeltaTheta=" << mSigmaDeltaTheta->at(track).at(hit)
	  //                              << " sigmaDeltaE=" << mSigmaDeltaE->at(track).at(hit) << std::endl;
	}// else {
	//                     std::cout<< "meas lay: sigmaDeltaPhi=" << mSigmaDeltaPhi->at(track).at(hit)
	//                              << " sigmaDeltaTheta=" << mSigmaDeltaTheta->at(track).at(hit)
	//                              << " sigmaDeltaE=" << mSigmaDeltaE->at(track).at(hit) << std::endl;
	//                 }
	//Check if this track has valid Data
	//if (abs(trackHit.normal[0] + 999.) < 1.E-4 || abs(trackHit.normal[1] + 999.) < 1.E-4 || abs(trackHit.ref[0] + 999.) < 1.E-4 || abs(trackHit.ref[1] + 999.) < 1.E-4) {
	if (abs(trackHit.ref[0] + 999.) < 1.E-4 || abs(trackHit.ref[1] + 999.) < 1.E-4) {
	  validTrack = false;
	  break;
	}            
	// Ignore Detector-Type 3
	if (trackHit.detType == 3) {
	  break;
	}

	if (setJacobiMatrix (trackHit.jacobi, track, hit) == -1) {
	  PRINT_WARN ("Could not set JacobiMatrix for hit!");
	  break;
	}
#if USE_EIGEN_MATRIX_INVERSION
	matrixInverseEigen(trackHit.jacobi, trackHit.jacobiInverse, ORDER, ORDER);
#else
	matrixInverse(trackHit.jacobi, trackHit.jacobiInverse, ORDER, ORDER);
#endif
	newTrack.track.push_back (trackHit);
      }
      //             if(validTrack)
      //             	newEvent.push_back (newTrack);
      if (!validTrack)
	newTrack.track.clear ( );
      newEvent.push_back (newTrack);
      }
      mEvents.push_back (newEvent);
    }

    resetAttributeVectors ( );

    delete file;

    return 0;
  }
Exemplo n.º 20
0
static void
InitWindowComponents(HWND MainWindow, wnd_ctrls *Controls)
{
	HINSTANCE Module = GetModuleHandle(0);

	HWND ComboBox, TextBox, ButtonOK, ButtonCancel, CheckBox;
	ComboBox = CreateWindowA(
		WC_COMBOBOXA, 
		0, 
		WS_CHILD | WS_OVERLAPPED | WS_VSCROLL | CBS_DROPDOWNLIST | CBS_SORT,
		0, 0,
		CW_USEDEFAULT, CW_USEDEFAULT,
		MainWindow,
		0, 
		Module,
		0);

	TextBox = CreateWindowA(
		WC_STATICA,
		"Please choose a window from the list above.",
		WS_CHILD | WS_OVERLAPPED | SS_CENTER | SS_CENTERIMAGE,
		0, 0,
		CW_USEDEFAULT, CW_USEDEFAULT,
		MainWindow,
		0,
		Module,
		0);

	ButtonCancel = CreateWindowA(
		WC_BUTTONA,
		"Cancel",
		WS_TABSTOP | WS_CHILD | WS_OVERLAPPED | BS_DEFPUSHBUTTON,
		0, 0,
		CW_USEDEFAULT, CW_USEDEFAULT,
		MainWindow,
		0, 
		Module, 
		0);

	ButtonOK = CreateWindowA(
		WC_BUTTONA,
		"Adjust window",
		WS_TABSTOP | WS_CHILD | WS_OVERLAPPED | BS_DEFPUSHBUTTON,
		0, 0,
		CW_USEDEFAULT, CW_USEDEFAULT,
		MainWindow,
		0, 
		Module, 
		0);

	CheckBox = CreateWindowA(
		WC_BUTTONA,
		"Load config",
		WS_CHILD | BS_AUTOCHECKBOX,
		0, 0,
		CW_USEDEFAULT, CW_USEDEFAULT,
		MainWindow,
		0,
		Module,
		0);

	Controls->ComboBox = ComboBox;
	Controls->StaticText = TextBox;
	Controls->ButtonOK = ButtonOK;
	Controls->ButtonCancel = ButtonCancel;
	Controls->CheckBox = CheckBox;
	Controls->CurSelection = 0;

	ApplySystemParameters(Controls);

	AllocateWindowDataPool(&Controls->Pool, MAX_WND_ENUM_COUNT);
	enum_data EnumData = {};
	EnumData.ComboBox = ComboBox;
	EnumData.Pool = &Controls->Pool;
	if(!EnumWindows(EnumWindowsProc, (LPARAM)&EnumData)) {
		if(GetLastError() != ENUM_ERR_ABORTED) {
			PRINT_ERR("Could not enumerate windows.\n");
		}
	}

	if(Controls->Pool.DataCount > 0) {
		SetFocus(ComboBox);
	}
	else {
		SetWindowText(TextBox, "No windows found.");
		SetFocus(ButtonOK);
	}

	ApplyGridLayout(Controls, MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT, MARGIN_X, MARGIN_Y);
}
Exemplo n.º 21
0
int main (int argc, char **argv)
{
    uint_t err = 0;
    if (argc < 2) {
        err = 2;
        PRINT_ERR("not enough arguments\n");
        PRINT_MSG("read a wave file as a mono vector\n");
        PRINT_MSG("usage: %s <source_path> [samplerate] [hop_size]\n", argv[0]);
        PRINT_MSG("examples:\n");
        PRINT_MSG(" - read file.wav at original samplerate\n");
        PRINT_MSG("       %s file.wav\n", argv[0]);
        PRINT_MSG(" - read file.wav at 32000Hz\n");
        PRINT_MSG("       %s file.aif 32000\n", argv[0]);
        PRINT_MSG(" - read file.wav at original samplerate with 4096 blocks\n");
        PRINT_MSG("       %s file.wav 0 4096 \n", argv[0]);
        return err;
    }

    uint_t samplerate = 0;
    uint_t hop_size = 256;
    uint_t n_frames = 0, read = 0;
    uint_t old_n_frames_1 = 0, old_n_frames_2 = 0, old_n_frames_3 = 0;
    if ( argc == 3 ) samplerate = atoi(argv[2]);
    if ( argc == 4 ) hop_size = atoi(argv[3]);

    char_t *source_path = argv[1];

    fvec_t *vec = new_fvec(hop_size);

    aubio_source_t* s = new_aubio_source(source_path, samplerate, hop_size);
    if (!s) {
        err = 1;
        goto beach;
    }

    if (samplerate == 0 ) samplerate = aubio_source_get_samplerate(s);

    do {
        aubio_source_do(s, vec, &read);
        //fvec_print (vec);
        n_frames += read;
    } while ( read == hop_size );

    PRINT_MSG("read %.2fs, %d frames at %dHz (%d blocks) from %s\n",
              n_frames * 1. / samplerate,
              n_frames, samplerate,
              n_frames / hop_size, source_path);

    old_n_frames_1 = n_frames;

    aubio_source_seek (s, 0);

    n_frames = 0;
    do {
        aubio_source_do(s, vec, &read);
        //fvec_print (vec);
        n_frames += read;
    } while ( read == hop_size );

    PRINT_MSG("read %.2fs, %d frames at %dHz (%d blocks) from %s\n",
              n_frames * 1. / samplerate,
              n_frames, samplerate,
              n_frames / hop_size, source_path);

    old_n_frames_2 = n_frames;

    aubio_source_seek (s, old_n_frames_1 / 2);

    n_frames = 0;
    do {
        aubio_source_do(s, vec, &read);
        //fvec_print (vec);
        n_frames += read;
    } while ( read == hop_size );

    PRINT_MSG("read %.2fs, %d frames at %dHz (%d blocks) from %s\n",
              n_frames * 1. / samplerate,
              n_frames, samplerate,
              n_frames / hop_size, source_path);

    old_n_frames_3 = n_frames;

    del_aubio_source (s);
beach:
    del_fvec (vec);

    // check that we got exactly the same number of frames
    assert ( old_n_frames_2 == old_n_frames_1 );
    // check that we got about half the frames, with 3 decimals
    assert ( roundf(1.e3 * old_n_frames_1 / old_n_frames_3) / 1.e3 == 2.);
    return err;
}
Exemplo n.º 22
0
static LRESULT CALLBACK 
MainWindowProc(HWND MainWindow, UINT Message, WPARAM wParam, LPARAM lParam)
{
	LRESULT Result = 0;
	switch(Message) {
		case WM_CREATE:
			InitWindowComponents(MainWindow, &Controls);
			break;
		case WM_DESTROY:
			PostQuitMessage(0);
			break;
		case WM_ERASEBKGND:
			// NOTE: Return a non-zero value. Literally.
			Result = !0;
			break;
		case WM_PAINT:
		{
			PAINTSTRUCT PaintStruct;
			HDC DC = BeginPaint(MainWindow, &PaintStruct);
			RECT FillRegion;
			GetClientRect(MainWindow, &FillRegion);
			COLORREF Top = RGB(239, 241, 245);
			COLORREF Bottom = RGB(218, 223, 233);
			DrawGradient(DC, FillRegion, Top, Top, Bottom, Bottom);
			EndPaint(MainWindow, &PaintStruct);
			ReleaseDC(MainWindow, DC);
		} break;
		case WM_COMMAND:
		{
			HWND Ctrl = (HWND)lParam;
			if(HIWORD(wParam) == CBN_SELCHANGE && Ctrl == Controls.ComboBox) {
				DWORD Pos = SendMessageA((HWND)lParam, CB_GETCURSEL, 0, 0);
				window_data *WndData = (window_data*)SendMessageA((HWND)lParam, CB_GETITEMDATA, Pos, 0);
				if(WndData) {
					Controls.CurSelection = WndData;
					HWND Window = WndData->Window;
					WINDOWINFO WindowInfo = {};
					WindowInfo.cbSize = sizeof(WindowInfo);
					if(GetWindowInfo(Window, &WindowInfo)) {
						RECT Rect = WindowInfo.rcWindow;
						LONG Width = Rect.right - Rect.left;
						LONG Height = Rect.bottom - Rect.top;

						// TODO: Display usefull data
						char Buffer[256];
						StringCbPrintfA(Buffer, sizeof(Buffer), "%dx%d starting at (%d,%d)", Width, Height, Rect.left, Rect.top);
						SetWindowTextA(Controls.StaticText, Buffer);
						ShowWindow(Controls.StaticText, TRUE);
					}
					else {
						PRINT_ERR("Could not get window info.\n");
					}
				}
			}
			else if(HIWORD(wParam) == BN_CLICKED) {
				if(Ctrl == Controls.ButtonOK) {
					if(Controls.CurSelection) {
						int UseConfig = SendMessageA(Controls.CheckBox, BM_GETCHECK, 0, 0);
						if(UseConfig == BST_CHECKED) {
							load_file_result LoadResult = LoadWindowSizeFromConfig();
							if(LoadResult.Valid) {
								SetWindowMode(*Controls.CurSelection, LoadResult.Width, LoadResult.Height);
							}
							else {
								int SetToFullscreen = MessageBoxA(MainWindow, "Error loading config.ini.\nSet to fullscreen instead?", 0, MB_YESNO | MB_TASKMODAL);
								if(SetToFullscreen == IDYES) {
									SetFullscreen(*Controls.CurSelection);
								}
							}
						}
						else {
							SetFullscreen(*Controls.CurSelection);
						}
					}
					PostQuitMessage(0);
				}
				else if(Ctrl == Controls.ButtonCancel) {
					PostQuitMessage(0);
				}
				else {
					Result = DefWindowProcA(MainWindow, Message, wParam, lParam);
				}
			}
		} break;
		default:
			Result = DefWindowProcA(MainWindow, Message, wParam, lParam);
	}

	return Result;
}
Exemplo n.º 23
0
void processSamples(int nSamples, IPOD_SAMPLE *samples)
{
#ifdef VERBOSE
	PRINT_ERR("Processing %d samples\n", nSamples);
#endif
	//for each of the samples
	for(int sam = 0; sam < nSamples; sam++)
	{
		int nAPs = samples[sam].nAPs;
#ifdef VERBOSE
        PRINT_ERR("Sample %d contains %d APs\n",sam+1,nAPs);
#endif
		float lat, lon;
		//lat long sample was taken at
		lat = samples[sam].lat;
		lon = samples[sam].lon;
#ifdef VERBOSE
        PRINT_ERR("Latitude: %f Longitude: %f\n",lat,lon);
#endif
		//convenience pointer to beginning of APs
		APINFO *apIter = samples[sam].APs;

		//for each ap
		for(int ap = 0; ap < nAPs; ap++)
		{
			//c++ string for MAC because they're awesome
			std::string macAddress(apIter[ap].mac);
			sample_info s;
			s.latitude = lat;
			s.longitude = lon;
			s.rssi = apIter[ap].rssi;
#ifdef VERBOSE
        PRINT_ERR("MAC Address: %s RSSI: %d \n",macAddress.c_str(),s.rssi);
#endif
			samplesSoFar[macAddress].push_back(s);
		}
	}
	//iterate through the map
	//construct 
	std::map<std::string,std::vector<sample_info> >::iterator it = samplesSoFar.begin();
	for(; it != samplesSoFar.end(); it++)
	{
		//number of processed samples
		int nProc = it->second.size();
		//set a threshold that 10+ samples must be present before trilateration can occur
		if(nProc >= 10)
		{
			std::vector<float> lats;
			std::vector<float> lons;
			std::vector<int32_t> rssis;
			
			std::vector<sample_info>::iterator sInfoIter = it->second.begin();
			for(; sInfoIter != it->second.end(); sInfoIter++)
			{
				lats.push_back(sInfoIter->latitude);
				lons.push_back(sInfoIter->longitude);
				rssis.push_back(sInfoIter->rssi);
			}
			//generate a position for this WAP
			if(generateWAPPosition(lats,lons,rssis,it->first));
				it->second.clear();
		}
	}
}
// ---------------------------------------------------------------------------
//  From class CMMFCodec.
//  This function is used to decode the given source and fill the destination
//  buffer with the decode data.
//  The buffers can be of any size.  Since the buffers can be of any size
//  there is no guarantee that all the source buffer can be processed to fill
//  the destination buffer or that the all the source buffer may be processed
//  before the destination is full.  Therefore the ProcessL needs to return a
//  TCodecProcessResult returing the number of source bytes processed and the
//  number of destination bytes processed along with a process result code
//  defined thus:
//  - EProcessComplete: the codec processed all the source data into the sink
//    buffer
//  - EProcessIncomplete: the codec filled sink buffer before all the source
//    buffer was processed
//  - EDstNotFilled: the codec processed the source buffer but the sink buffer
//    was not filled
//  - EEndOfData: the codec detected the end data - all source data in
//    processed but sink may not be full
//  - EProcessError: the codec process error condition
//
//  The ProcessL should start processing the source buffer from the iPosition
//  data member of the source data and start filling the destination buffer
//  from its iPosition.
//  --------------------------------------------------------------------------
//
TCodecProcessResult CAriHeAacDecMmfCodec::ProcessL( const CMMFBuffer& aSrc,
                                                CMMFBuffer& aDst )
    {
    PRINT_ENTRY;

    if ( !iConfigured )
        {
        PRINT_ERR( "Decoder not yet configured" );
        User::Leave( KErrNotReady );
        }
    // total decoded bytes added to the dst buffer
    TInt totalDstBytesAdded = 0;
    // total src bytes added to the internal src buffer
    TInt totalSrcBytesCopied = 0;
    // temporary variable to use for copying the sorce or destination data
    TInt numberOfBytesCopied = 0;
    TInt dstBufferRemainingBytes = 0;

    /**
     * Process the dst buffer, update the dstBufferPos and check
     * whether dst buffer is NULL or not.
     */
    CMMFDataBuffer* dst = static_cast<CMMFDataBuffer*>( &aDst );
    const TInt dstMaxLen = dst->Data().MaxLength();
    TUint8* dstPtr = const_cast<TUint8*>( dst->Data().Ptr() );
    TInt dstBufferPos = dst->Position();

    /**
     * Process the src buffer, update srcbuffer length, position and
     * flag for last frame. check whether src buffer is NULL or not
     * and check src buffer contains any data
     */
    const CMMFDataBuffer* src = static_cast<const CMMFDataBuffer*>( &aSrc );
    TUint8* srcPtr = const_cast<TUint8*>( src->Data().Ptr() );
    TInt srcBufferLen = src->Data().Length();
    TInt srcBufferPos = src->Position();
    TBool lastFrame = src->LastBuffer();

    PRINT_MSG( LEVEL_HIGH, ( "Src Buffer Pos: %d", srcBufferPos ) );
    PRINT_MSG( LEVEL_HIGH, ( "Dst Buffer Pos: %d", dstBufferPos ) );
    PRINT_MSG( LEVEL_HIGH, ( "Residue in internal output buffer: %d",
           iInternalOutputBufferResidueLen - iInternalOutputBufferPos ) );
    PRINT_MSG( LEVEL_HIGH, ( "Residue in internal input buffer: %d",
                                      iInternalInputBufferResidueLen ) );
    /**
     * if any destination bytes from internal destination buffer is not
     * given to the dst buffer from the previous call, give it to the
     * dst buffer. After this block, it ensures that no bytes are remaining
     * in the internal destination buffer.
     */
    if ( iInternalOutputBufferResidueLen - iInternalOutputBufferPos > 0 )
        {
        numberOfBytesCopied = CopyToDstBuffer( dst, totalDstBytesAdded );

        if ( iInternalOutputBufferResidueLen - iInternalOutputBufferPos > 0 )
            {
            PRINT_EXIT;
            return Result( TCodecProcessResult::EProcessIncomplete,
                            totalSrcBytesCopied, totalDstBytesAdded );
            }
        else
            {
            //Decode NULL frame to handle error concealment
            if ( lastFrame && ( srcBufferLen - srcBufferPos == 0 )&&
            ( iInternalInputBufferResidueLen == 0 && !iLastFrameDecoded ) )
                {
                dstBufferRemainingBytes = dstMaxLen - dstBufferPos -
                                                    totalDstBytesAdded;
                if ( dstBufferRemainingBytes == 0 )
                    {
                    iInternalOutputBufferPos = 0;
                    iInternalOutputBufferResidueLen = 0;
                    totalSrcBytesCopied = 0;
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EProcessIncomplete,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                     }

                TInt dstLen  = iOutFrameSize;
                DecodeLastFrame(dstLen);
                iInternalOutputBufferResidueLen = dstLen;

                numberOfBytesCopied =
                                CopyToDstBuffer( dst, totalDstBytesAdded );
                totalDstBytesAdded += numberOfBytesCopied;
                dstBufferRemainingBytes -= numberOfBytesCopied;

                if ( ( iInternalOutputBufferResidueLen -
                    iInternalOutputBufferPos == 0 ) && iLastFrameDecoded )
                    {
                    totalSrcBytesCopied = 0;
                    iInternalOutputBufferResidueLen = 0;
                    iInternalInputBufferResidueLen = 0;
                    iInternalOutputBufferPos = 0;
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EEndOfData,
                                totalSrcBytesCopied, totalDstBytesAdded );
                    }
                else
                    {
                    totalSrcBytesCopied = 0;
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EProcessIncomplete,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                    }
                }
            iInternalOutputBufferPos = 0;
            iInternalOutputBufferResidueLen = 0;
            }
        }
    else
        {
        if ( lastFrame && ( srcBufferLen - srcBufferPos == 0 )&&
            ( iInternalInputBufferResidueLen == 0 && !iLastFrameDecoded ) )
            {
            TInt dstLen  = iOutFrameSize;
            DecodeLastFrame(dstLen);
            iInternalOutputBufferResidueLen = dstLen;

            numberOfBytesCopied = CopyToDstBuffer( dst, totalDstBytesAdded );
            totalDstBytesAdded += numberOfBytesCopied;
            dstBufferRemainingBytes -= numberOfBytesCopied;

            if ( ( iInternalOutputBufferResidueLen -
                    iInternalOutputBufferPos == 0 ) && iLastFrameDecoded )
                {
                totalSrcBytesCopied = 0;
                iInternalOutputBufferResidueLen = 0;
                iInternalInputBufferResidueLen = 0;
                iInternalOutputBufferPos = 0;
                PRINT_EXIT;
                return Result( TCodecProcessResult::EEndOfData,
                            totalSrcBytesCopied, totalDstBytesAdded );
                }
            else
                {
                totalSrcBytesCopied = 0;
                PRINT_EXIT;
                return Result( TCodecProcessResult::EProcessIncomplete,
                                totalSrcBytesCopied, totalDstBytesAdded );
                }
            }
        }

    /**
     * copy the src buffer data into the internal buffer till internal buffer
     * holds minimum bytes to process i.e KMinBytesInput. After this block,
     * it ensures that internal source buffer holds KMinBytesInput.
     * if it is a last frame, treat remaining residual buffer as internal
     * buffer.
     */
    if ( ( KMinBytesInput - iInternalInputBufferResidueLen > 0 ) &&
                                ( srcBufferLen - srcBufferPos > 0 ) )
        {
        numberOfBytesCopied = CopyFromSrcBuffer( src, totalSrcBytesCopied );
        }

    /**
     * update the internal buffer length.
     */
    if ( ( KMinBytesInput > iInternalInputBufferResidueLen ) &&
                                                        ( !lastFrame ) )
        {
        PRINT_EXIT;
        return Result( TCodecProcessResult::EDstNotFilled,
                srcBufferLen - srcBufferPos, totalDstBytesAdded );
        }

    if ( iLastFrameDecoded && iInternalInputBufferResidueLen == 0 &&
                                    iInternalOutputBufferResidueLen == 0 )
        {
        totalSrcBytesCopied = 0;
        iInternalOutputBufferResidueLen = 0;
        iInternalInputBufferResidueLen = 0;
        iInternalOutputBufferPos = 0;
        PRINT_EXIT;
        return Result( TCodecProcessResult::EEndOfData,
                    totalSrcBytesCopied, totalDstBytesAdded );
        }

    /**
     * process the src buffer till destination buffer or source buffer or
     * both buffers are exhausted.
     */
    do
        {
        TInt srcBufferRemainingBytes = srcBufferLen - srcBufferPos -
                                                        totalSrcBytesCopied;
        dstBufferRemainingBytes = dstMaxLen - dstBufferPos -
                                                        totalDstBytesAdded;
        TInt internalInputBufferPos = 0;

        /**
         * initialize the variables like iSrcUsed and dstLen accordingly.
         * call Decode.
         */
        iSrcUsed = iInternalInputBufferResidueLen - internalInputBufferPos;
        TInt dstLen  = iOutFrameSize;

        TInt error = iCodec->Decode(
                            &iInternalInputBuffer[internalInputBufferPos],
                                iSrcUsed, iInternalOutputBuffer, dstLen );
        if ( error != 0 )
            {
            iInternalInputBufferResidueLen = 0;
            totalSrcBytesCopied = srcBufferLen;
            PRINT_ERR( error );
            return Result(
                    TCodecProcessResult::EProcessError,
                    totalSrcBytesCopied, totalDstBytesAdded + dstBufferPos);
            }
        iFrameNum++;
        PRINT_MSG( LEVEL_HIGH, ( "Frame: %d", iFrameNum ) );
        PRINT_MSG( LEVEL_HIGH, ( "iSrcUsed: %d", iSrcUsed ) );
        PRINT_MSG( LEVEL_HIGH, ( "dstLen: %d", dstLen ) );

        /**
         * Fill Destination Buffer
         */
        iInternalOutputBufferResidueLen = dstLen;
        numberOfBytesCopied = CopyToDstBuffer( dst, totalDstBytesAdded );
        dstBufferRemainingBytes -= numberOfBytesCopied;

        /**
         * Fill Source Buffer
         */
        internalInputBufferPos += iSrcUsed ;
        ShiftData( internalInputBufferPos, 0 );
        numberOfBytesCopied = CopyFromSrcBuffer( src, totalSrcBytesCopied );
        srcBufferRemainingBytes -= numberOfBytesCopied;

        /**
         * check four conditions if else for src and if else for dst
         */
        /**
         * src has available bytes
         */
        if ( srcBufferRemainingBytes > 0  ||
                iInternalInputBufferResidueLen >= KMinBytesInput )
            {
            if ( dstBufferRemainingBytes == 0 )
                {
                PRINT_EXIT;
                return Result(
                        TCodecProcessResult::EProcessIncomplete,
                        totalSrcBytesCopied, totalDstBytesAdded );
                }
            }
        else
            {
            // dst buffer has availabe space for decoded bytes
            if ( dstBufferRemainingBytes > 0 )
                {
                if ( lastFrame )
                    {
                    if ( iInternalInputBufferResidueLen == 0 )
                        {
                        TInt dstLen  = iOutFrameSize;
                        DecodeLastFrame(dstLen);
                        iInternalOutputBufferResidueLen = dstLen;

                        numberOfBytesCopied =
                                CopyToDstBuffer( dst, totalDstBytesAdded );
                        totalDstBytesAdded += numberOfBytesCopied;
                        dstBufferRemainingBytes -= numberOfBytesCopied;

                        if ( ( iInternalOutputBufferResidueLen -
                                iInternalOutputBufferPos == 0 ) &&
                                iLastFrameDecoded )
                            {
                            totalSrcBytesCopied = 0;
                            iInternalOutputBufferResidueLen = 0;
                            iInternalInputBufferResidueLen = 0;
                            iInternalOutputBufferPos = 0;
                            PRINT_EXIT;
                            return Result( TCodecProcessResult::EEndOfData,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                            }
                        else
                            {
                            totalSrcBytesCopied = 0;
                            PRINT_EXIT;
                            return Result(
                                    TCodecProcessResult::EProcessIncomplete,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                            }
                        }
                    }
                else
                    {
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EDstNotFilled,
                            totalSrcBytesCopied, totalDstBytesAdded );
                    }
                }
            else
                {
                if ( iInternalOutputBufferResidueLen -
                                            iInternalOutputBufferPos > 0 )
                    {
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EProcessIncomplete,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                    }
                else
                    {
                    if ( lastFrame )
                        {
                        PRINT_EXIT;
                        return Result(
                                    TCodecProcessResult::EProcessIncomplete,
                                    totalSrcBytesCopied, totalDstBytesAdded );
                        }
                    else
                        {
                        PRINT_EXIT;
                        return Result(
                                TCodecProcessResult::EProcessComplete,
                                totalSrcBytesCopied, totalDstBytesAdded );
                        }
                    }
                }
            }
        }while ( 1 );
    }
int main(int argc, char **argv)
{
	TSS_HKEY hKey, hSRK;
	TSS_HCONTEXT hContext;
	TSS_HTPM hTPM;
	TSS_RESULT result;
	TSS_HPOLICY hPolicy;
	TSS_HPCRS hPcrs;
	UINT32 ulPcrValueLength, subCap, subCapLength;
	UINT32 pulRespDataLength, numPcrs;
	BYTE *pNumPcrs, *rgbPcrValue, *uuidString, *pcrsSelectedValues[24];
	int i, c, *pcrsSelected = NULL, numPcrsSelected = 0;
	TSS_UUID *uuid;
	BYTE wellknown[] = TSS_WELL_KNOWN_SECRET;

	while (1) {
		c = getopt(argc, argv, "p:");
		if (c == -1)
			break;
		switch (c) {
			case 'p':
				numPcrsSelected++;
				pcrsSelected = realloc(pcrsSelected,
						       (sizeof(int) 
							* numPcrsSelected));
				if (pcrsSelected == NULL) {
					PRINT_ERR("Malloc of %zd bytes failed.",
						  (sizeof(int)
						   * numPcrsSelected));
					return -1;
				}
				pcrsSelected[numPcrsSelected - 1] =
					atoi(optarg);
				break;
			default:
				usage(argv[0]);
				break;
		}
	}
	if (numPcrsSelected == 0)
		printf("Warning: Key will not be bound to any PCR's!\n");
	if (numPcrsSelected > 24) {
		PRINT_ERR("Too many PCRs selected! Exiting.");
		return -EINVAL;
	}
        result = Tspi_Context_Create(&hContext);
        if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_Context_Create", result);
                return result;
        }
        result = Tspi_Context_Connect(hContext, NULL);
        if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_Context_Connect", result);
                Tspi_Context_Close(hContext);
                return result;
        }
	result = Tspi_Context_GetTpmObject(hContext, &hTPM);
	if (result != TSS_SUCCESS) {
		PRINT_TSS_ERR("Tspi_Context_GetTpmObject", result);
		Tspi_Context_Close(hContext);
		return result;
	}
	subCap = TSS_TPMCAP_PROP_PCR;
	subCapLength = sizeof(UINT32);
	result = Tspi_TPM_GetCapability(hTPM, TSS_TPMCAP_PROPERTY,
					subCapLength, (BYTE *)&subCap,
					&pulRespDataLength, &pNumPcrs );
	if (result != TSS_SUCCESS) {
		PRINT_TSS_ERR("Tspi_TPM_GetCapability", result);
		Tspi_Context_Close(hContext);
		return result;
	}
	numPcrs = *(UINT32 *)pNumPcrs;
	for (i = 0; i < (int)numPcrsSelected; i++) {
		if (pcrsSelected[i] > (int)numPcrs) {
			fprintf(stderr, "%d: invalid PCR register. PCRs range "
				"from 0 - %u\n", pcrsSelected[i], numPcrs);
			return -1;
		}
	}
	result = Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_PCRS, 0,
					   &hPcrs);
	if (result != TSS_SUCCESS) {
		PRINT_TSS_ERR("Tspi_Context_CreateObject", result);
		return result;
	}
	for (i = 0; i < numPcrsSelected; i++) {
		result = Tspi_TPM_PcrRead(hTPM, pcrsSelected[i],
					  &ulPcrValueLength, &rgbPcrValue);
		if (result != TSS_SUCCESS) {
			PRINT_TSS_ERR("Tspi_TPM_PcrRead", result);
			Tspi_Context_Close(hContext);
			return result;
		}
		result = Tspi_PcrComposite_SetPcrValue(hPcrs, pcrsSelected[i],
						       ulPcrValueLength,
						       rgbPcrValue);
		if (result != TSS_SUCCESS) {
			PRINT_TSS_ERR("Tspi_PcrComposite_SetPcrValue", result );
			Tspi_Context_Close( hContext );
			return result;
		}

		pcrsSelectedValues[i] = rgbPcrValue;
	}
        result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM,
					    SRK_UUID, &hSRK);
        if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_Context_LoadKeyByUUID", result);
                Tspi_Context_Close(hContext);
                return result;
        }
	result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &hPolicy);
        if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_GetPolicyObject", result);
                Tspi_Context_Close(hContext);
                return result;
        }

	result = Tspi_Policy_SetSecret(hPolicy, TSS_SECRET_MODE_SHA1,
				       sizeof(wellknown), wellknown);
        if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_GetPolicyObject", result);
                Tspi_Context_Close(hContext);
                return result;
        }
	result = Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY,
					   (TSS_KEY_TYPE_STORAGE
					    | TSS_KEY_SIZE_2048
					    | TSS_KEY_VOLATILE
					    | TSS_KEY_NO_AUTHORIZATION
					    | TSS_KEY_NOT_MIGRATABLE), &hKey);
	if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_Context_CreateObject", result);
                Tspi_Context_Close(hContext);
                return result;
	}
	result = Tspi_Key_CreateKey(hKey, hSRK, hPcrs);
	if (result != TSS_SUCCESS) {
                PRINT_TSS_ERR("Tspi_Key_CreateKey", result);
                Tspi_Context_Close(hContext);
                return result;
	}
	result = Tspi_TPM_GetRandom(hTPM, (UINT32)16, (BYTE **)&uuid);
	if (result != TSS_SUCCESS) {
		PRINT_TSS_ERR("Tspi_TPM_GetRandom", result);
		Tspi_Context_Close(hContext);
		return result;
	}
	result = Tspi_Context_RegisterKey(hContext, hKey, TSS_PS_TYPE_USER,
					  *uuid, TSS_PS_TYPE_SYSTEM, SRK_UUID);
	if (result != TSS_SUCCESS) {
		PRINT_TSS_ERR("Tspi_Context_RegisterKey", result);
		Tspi_Context_Close(hContext);
		return result;
	}
	printf("Success: Key created bound to:\n");
	for (i = 0; i < numPcrsSelected; i++) {
		uuidString = (unsigned char *) 
			      util_bytes_to_string((char *)
						   pcrsSelectedValues[i], 20);
		if (uuidString == NULL) {
			PRINT_ERR("malloc of 41 bytes failed");
			Tspi_Context_Close(hContext);
			return result;
		}

		printf("PCR %d: %s\n", pcrsSelected[i], uuidString);
		free(uuidString);
		Tspi_Context_FreeMemory(hContext, pcrsSelectedValues[i]);
	}
	uuidString = (BYTE *)util_bytes_to_string((char *)uuid, 16);
	if (uuidString == NULL) {
		PRINT_ERR("malloc of 33 bytes failed");
		Tspi_Context_Close(hContext);
		return result;
	}
	printf("And registered in persistent storage with UUID "
	       "(tspi_uuid parameter): %s\n", uuidString);
	Tspi_Context_FreeMemory(hContext, (BYTE *)uuid);
	free(uuidString);
	Tspi_Context_Close(hContext);
	return 0;
}
// ---------------------------------------------------------------------------
//  From class CMMFCodec.
//  The function Sets codec configuration.
//  The value used for aConfigType must be KUidMmfCodecAudioSettings
//  (defined in include\mmf\plugins\mmfCodecImplementationUIDs.hrh)
// ---------------------------------------------------------------------------
//
void CAriHeAacDecMmfCodec::ConfigureL( TUid /* aConfigType */,
                                    const TDesC8& aParam )
    {
    PRINT_ENTRY;
    TInt paramLen = aParam.Length();
    PRINT_MSG( LEVEL_HIGH, ( "param Len: %d",
                                        paramLen ) );
    if ( paramLen < KMinParamSize )
        {
        PRINT_MSG( LEVEL_HIGH, ( "param Len: %d",
                                    paramLen ) );
        PRINT_ERR( "Incorrect parameter descriptor " );
        User::Leave( KErrArgument );
        }
    if ( !iConfigured )
        {
        RArray<TInt>  configParam = ( RArray<TInt>& )( aParam );
        TInt index = 0;

        index++;
        //configParam[1] holds NoOfChannels
        iFrameInfo.iNoOfChannels = configParam[index++];
        //configParam[2] holds Profile
        iFrameInfo.iProfile = configParam[index++];
        //configParam[3] holds OutFrameSize
        iFrameInfo.iOutFrameSize = configParam[index++];
        //configParam[4] holds NoOfSamples
        iFrameInfo.iNoOfSamples = configParam[index++];
        //configParam[5] holds SamplingFrequency
        iFrameInfo.iSamplingFrequency = configParam[index++];
        //Ignore fields 6,7 & 8
        index++;
        index++;
        index++;
        //configParam[9] holds OutSamplingFrequency
        iFrameInfo.iOutSamplingFrequency = configParam[index++];
        //configParam[10] holds ExtObjectType
        iFrameInfo.iExtObjectType = configParam[index];
        iFrameInfo.iDownSampledMode = 0;

        if ( paramLen > KMinParamSize)
            {
            /**
             * Call Reset only if fields 13,14 and 15 of the
             * Param array are set to zero
             */
            if ( ( configParam[KRenderStatusIndex] == 0 &&
                                    configParam[KMarkPlayStatusIndex] == 0 &&
                                    configParam[KEnableStatusIndex] == 0 ) )
                {
                PRINT_MSG( LEVEL_HIGH, ( "frameInfo->OutFrameSize: %d",
                                            iFrameInfo.iOutFrameSize ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->NoOfSamples: %d",
                                            iFrameInfo.iNoOfSamples ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->SamplingFrequency: %d",
                                            iFrameInfo.iSamplingFrequency ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->NoOfChannels: %d",
                                            iFrameInfo.iNoOfChannels ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->Profile: %d",
                                            iFrameInfo.iProfile ) );
                PRINT_MSG( LEVEL_HIGH,
                                    ( "iFrameInfo->OutSamplingFrequency: %d",
                                        iFrameInfo.iOutSamplingFrequency ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->ExtObjectType: %d",
                                            iFrameInfo.iExtObjectType ) );
                PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->DownSampledMode: %d",
                                            iFrameInfo.iDownSampledMode ) );

                User::LeaveIfError( iCodec->Reset( &iFrameInfo ) );

                iConfigured = ETrue;
                iOutFrameSize = iFrameInfo.iOutFrameSize;
                }
            }
        else
            {
            PRINT_MSG( LEVEL_HIGH, ( "frameInfo->OutFrameSize: %d",
                                               iFrameInfo.iOutFrameSize ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->NoOfSamples: %d",
                                       iFrameInfo.iNoOfSamples ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->SamplingFrequency: %d",
                                       iFrameInfo.iSamplingFrequency ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->NoOfChannels: %d",
                                       iFrameInfo.iNoOfChannels ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->Profile: %d",
                                       iFrameInfo.iProfile ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->OutSamplingFrequency: %d",
                                       iFrameInfo.iOutSamplingFrequency ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->ExtObjectType: %d",
                                       iFrameInfo.iExtObjectType ) );
            PRINT_MSG( LEVEL_HIGH, ( "iFrameInfo->DownSampledMode: %d",
                                       iFrameInfo.iDownSampledMode ) );

            User::LeaveIfError( iCodec->Reset( &iFrameInfo ) );

            iConfigured = ETrue;

            iOutFrameSize = iFrameInfo.iOutFrameSize;
            }
        }
    PRINT_EXIT;
    }
int bcm_sdiowl_init(int onoff)
{
	int rc;
	struct sdio_wifi_dev *dev = &gDev;
#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT
	int wait_cnt;
	struct mmc_card *card;
#endif

	printk(KERN_ERR "%s:ENTRY\n",__FUNCTION__);


//Set the Pull of Sdio Lines first

	SdioPinCfgs.name = PN_MMC1CMD;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=1;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT0;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=1;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);

	SdioPinCfgs.name = PN_MMC1DAT1;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=1;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT2;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=1;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);


	SdioPinCfgs.name = PN_MMC1DAT3;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=1;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);

#if defined(CONFIG_MACH_RHEA_SS_ZANIN) || defined(CONFIG_MACH_RHEA_SS_CORIPLUS)
	SdioPinCfgs.name = PN_GPIO07;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=1;
	SdioPinCfgs.reg.b.pull_up=0;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);
#elif defined(CONFIG_MACH_RHEA_SS_LUCAS)
	SdioPinCfgs.name = PN_UBCTSN;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=1;
	SdioPinCfgs.reg.b.pull_up=0;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs);
#endif

	SdioPinCfgs.name = PN_MMC1RST;
	pinmux_get_pin_config(&SdioPinCfgs);
	SdioPinCfgs.reg.b.pull_dn=0;
	SdioPinCfgs.reg.b.pull_up=0;
	SdioPinCfgs.reg.b.drv_sth=3;
	pinmux_set_pin_config(&SdioPinCfgs); 



//-----------------------------------



	/* check if the SDIO device is already up */
	rc = sdio_dev_is_initialized(SDIO_DEV_TYPE_WIFI);
	if (rc <= 0) {
		PRINT_ERR("sdio interface is not initialized or err=%d\n", rc);
		return rc;  
	}
	printk(KERN_ERR "%s:GET_GPIO INFO\n",__FUNCTION__);

	dev->wifi_gpio = sdio_get_wifi_gpio(SDIO_DEV_TYPE_WIFI);
#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT

	if (dev->wifi_gpio == NULL) {
		PRINT_ERR("wifi gpio hardware config is missing\n");
		return -EFAULT;
	}
#endif 

	/* reserve GPIOs */
	rc = wifi_gpio_request(dev->wifi_gpio);
	if (rc < 0) {
		PRINT_ERR("unable to reserve certain gpio pins\n");
		return rc;
	}

	/* reset the wifi chip */
	if(onoff)
		__wifi_reset(dev->wifi_gpio->reset, 1);
	else
		__wifi_reset(dev->wifi_gpio->reset, 0);

	printk(KERN_ERR "%s: WLAN_REG_ON(GPIO%d) : value(%d)\n",__FUNCTION__, dev->wifi_gpio->reset, gpio_get_value(dev->wifi_gpio->reset));


#ifndef CONFIG_BRCM_UNIFIED_DHD_SUPPORT

	/* now, emulate the card insertion */
	rc = sdio_card_emulate(SDIO_DEV_TYPE_WIFI, 1);
	if (rc < 0) {
		PRINT_ERR("sdio_card_emulate failed\n");
		goto err_free_gpio;
	}
#define WAIT_CNT 10
	/* need to wait for the mmc device population to finish */
	wait_cnt = 0;
	while (wait_cnt++ < WAIT_CNT) {
		card = sdio_get_mmc_card(SDIO_DEV_TYPE_WIFI);
		if (card) {
			atomic_set(&dev->dev_is_ready, 1);
			return 0;
		}
		msleep(100);
	}
	PRINT_ERR("timeout while populating sdio wifi device\n");
	rc = -EIO;
	sdio_card_emulate(SDIO_DEV_TYPE_WIFI, 0);

err_free_gpio:
	wifi_gpio_free(dev->wifi_gpio);
#endif // CONFIG_BRCM_UNIFIED_DHD_SUPPORT
	return rc;
}
Exemplo n.º 28
0
static int sprd_kpled_probe(struct platform_device *dev)
{
        struct sprd_kpled *led;
        int ret;
		struct sprd_kpled_2723_platform_data *pdata = NULL;

	#ifdef CONFIG_OF

        struct device_node *np = dev->dev.of_node;

        if(np) {
                pdata = sprd_kpled_2723_parse_dt(dev);
                if (pdata == NULL) {
                        PRINT_ERR("get dts data failed!\n");
                        return -ENODEV;
                }
        } else {
                PRINT_ERR("dev.of_node is NULL!\n");
                return -ENODEV;
        }
	#else
		pdata = dev->dev.platform_data;
        if (!pdata){
                PRINT_ERR("No kpled_platform data!\n");
                return -ENODEV;
        }
	#endif

        led = kzalloc(sizeof(struct sprd_kpled), GFP_KERNEL);
        if (led == NULL) {
                dev_err(&dev->dev, "No memory for device\n");
                return -ENOMEM;
        }

        led->cdev.brightness_set = sprd_kpled_set;
        //led->cdev.default_trigger = "heartbeat";
        led->cdev.default_trigger = "none";
        led->cdev.name = "keyboard-backlight";
        led->cdev.brightness_get = NULL;
        led->cdev.flags |= LED_CORE_SUSPENDRESUME;
        led->enabled = 0;
		led->brightness_max = pdata->brightness_max;
		led->brightness_min = pdata->brightness_min;
		led->run_mode = pdata->run_mode;
		PRINT_INFO("led->run_mode = %d\n",led->run_mode);
		PRINT_INFO("led->brightness_max = %d\n",led->brightness_max);

        spin_lock_init(&led->value_lock);
        mutex_init(&led->mutex);
        INIT_WORK(&led->work, sprd_kpled_work);
        led->value = LED_OFF;
        platform_set_drvdata(dev, led);

        /* register our new led device */

        ret = led_classdev_register(&dev->dev, &led->cdev);
        if (ret < 0) {
                dev_err(&dev->dev, "led_classdev_register failed\n");
                kfree(led);
                return ret;
        }

#ifdef CONFIG_HAS_EARLYSUSPEND
        led->early_suspend.suspend = sprd_kpled_early_suspend;
        led->early_suspend.resume  = sprd_kpled_late_resume;
        led->early_suspend.level   = EARLY_SUSPEND_LEVEL_BLANK_SCREEN;
        register_early_suspend(&led->early_suspend);
#endif

        sprd_kpled_disable(led);//disabled by default

        return 0;
}
TCodecProcessResult CAriMp3DecMmfCodec::ProcessL( const CMMFBuffer& aSrc,
        CMMFBuffer& aDst )
{
    PRINT_ENTRY;
    // total decoded bytes added to the dst buffer
    TInt totalDstBytesAdded = 0;
    // total src bytes added to the internal src buffer
    TInt totalSrcBytesCopied = 0;
    // temporary variable to use for copying the sorce or destination data
    TInt numberOfBytesCopied;
    // Flag for finding valid sync
    TBool syncFound = EFalse;

    /**
    * Process the dst buffer, update the dstBufferPos and check
    * whether dst buffer is NULL or not.
    */
    CMMFDataBuffer* dst = static_cast<CMMFDataBuffer*>( &aDst );

    const TInt dstMaxLen = dst->Data().MaxLength();
    TUint8* dstPtr = const_cast<TUint8*>( dst->Data().Ptr() );
    TInt dstBufferPos = dst->Position();

    /**
    * Process the src buffer, update srcbuffer length, position and
    * flag for last frame. check whether src buffer is NULL or not
    * and check src buffer contains any data
    */
    const CMMFDataBuffer* src = static_cast<const CMMFDataBuffer*>( &aSrc );

    TUint8* srcPtr = const_cast <TUint8*>( src->Data().Ptr() );
    TInt srcBufferLen = src->Data().Length();
    TInt srcBufferPos = src->Position();
    TBool lastFrame = src->LastBuffer();

    if ( srcBufferLen == 0 && iInternalInputBufferResidueLen == 0 )
    {
        PRINT_ERR( "source buffer length is zero" );
        User::Leave( KErrArgument );
    }

    /**
    * if any destination bytes from internal destination buffer is not
    * given to the dst buffer from the previous call, give it to the
    * dst buffer. After this block, it ensures that no bytes are remaining
    * in the internal destination buffer.
    */
    if ( iInternalOutputBufferResidueLen - iInternalOutputBufferPos > 0 )
    {
        numberOfBytesCopied = CopyToDstBuffer( dst, totalDstBytesAdded );

        if ( iInternalOutputBufferResidueLen - iInternalOutputBufferPos > 0 )
        {
            PRINT_EXIT;
            return Result( TCodecProcessResult::EProcessIncomplete,
                           totalSrcBytesCopied, totalDstBytesAdded );
        }
        else
        {
            if ( ( lastFrame ) && ( srcBufferLen - srcBufferPos == 0 )&&
                    ( iInternalInputBufferResidueLen == 0 ) )
            {
                iInternalOutputBufferResidueLen = 0;
                iInternalInputBufferResidueLen = 0;
                iInternalOutputBufferPos = 0;
                PRINT_EXIT;
                return Result( TCodecProcessResult::EEndOfData,
                               totalSrcBytesCopied, totalDstBytesAdded );
            }
            iInternalOutputBufferPos = 0;
            iInternalOutputBufferResidueLen = 0;
        }
    }

    /**
    * copy the src buffer data into the internal buffer till internal buffer
    * holds minimum bytes to process i.e KMinBytesInput. After this block, it
    * ensures that internal source buffer holds KMinBytesInput.
    * if it is a last frame, treat remaining residual buffer as internal
    * buffer.
    */
    if ( ( KMinBytesInput - iInternalInputBufferResidueLen > 0 )
            && ( srcBufferLen - srcBufferPos > 0 ) )
    {
        numberOfBytesCopied = CopyFromSrcBuffer( src, totalSrcBytesCopied );
    }

    if ( ( KMinBytesInput > iInternalInputBufferResidueLen )
            && ( !lastFrame ) )
    {
        PRINT_EXIT;
        return Result( TCodecProcessResult::EDstNotFilled,
                       srcBufferLen - srcBufferPos, totalDstBytesAdded );
    }

    /**
    * process the src buffer till destination buffer or source buffer
    * or both buffers are exhausted.
    */
    do
    {
        /**
        * call seeksync to find the valid fram start offset i.e syncpos.
        * update internal buffer position to that offset position if it is
        * success.if it is failed then there is no valid frame start in
        * the available buffer. Go for new src buffer. all bytes present
        * in the internal buffer are discarded.
        */
        TInt syncpos;
        TInt srcBufferRemainingBytes = srcBufferLen
                                       - srcBufferPos
                                       - totalSrcBytesCopied;
        TInt dstBufferRemainingBytes = dstMaxLen
                                       - dstBufferPos
                                       - totalDstBytesAdded;
        TInt internalInputBufferPos = 0;

        if ( KErrNone != iCodec->SeekSync(
                    &iInternalInputBuffer[internalInputBufferPos],
                    ( iInternalInputBufferResidueLen - internalInputBufferPos ),
                    syncpos ) )
        {
            TCodecProcessResult result = GetNewData( src, totalSrcBytesCopied,
                                         totalDstBytesAdded );

            if ( result.iStatus == TCodecProcessResult::EDstNotFilled ||
                    result.iStatus == TCodecProcessResult::EEndOfData )
            {
                return result;
            }
        }
        else
        {
            syncFound = ETrue;
            internalInputBufferPos += syncpos;
        }
        /**
        * call GetFrameInfo to find whether valid frame is present in the
        * availabel buffer.if it is success and framelength is 0 then
        * there is no valid frame is present,  discard the present buffer
        * till sync position and add new buffer.
        */
        if ( syncFound )
        {
            TInt frameLen;
            TMp3FrameInfo frameInfo;
            if ( KErrNone != iCodec->GetFrameInfo(
                        &iInternalInputBuffer[internalInputBufferPos],
                        ( iInternalInputBufferResidueLen - internalInputBufferPos ),
                        frameLen, frameInfo ) )
            {
                PRINT_ERR( "Decoder Getframeinfo failed" );
                User::Leave( KErrGeneral );
            }
            if ( frameLen == 0 )
            {
                TCodecProcessResult result = GetNewData( src,
                                             totalSrcBytesCopied, totalDstBytesAdded );

                if ( result.iStatus == TCodecProcessResult::EDstNotFilled ||
                        result.iStatus == TCodecProcessResult::EEndOfData )
                {
                    return result;
                }
            }

            /**
            * if the buffer has less than framelen then fill the internal
            * sorce buffer with KMinBytesInput bytes.
            */
            if ( frameLen   > ( iInternalInputBufferResidueLen
                                - internalInputBufferPos ) )
            {
                if( lastFrame )
                {
                    iInternalInputBufferResidueLen = 0;
                    iInternalOutputBufferResidueLen = 0;
                    iInternalOutputBufferPos = 0;
                    PRINT_EXIT;
                    return Result(
                               TCodecProcessResult::EEndOfData,
                               totalSrcBytesCopied, totalDstBytesAdded );
                }

                ShiftData( internalInputBufferPos, 0 );
                numberOfBytesCopied = CopyFromSrcBuffer( src,
                                      totalSrcBytesCopied );
                internalInputBufferPos = 0;

                if ( iInternalInputBufferResidueLen < KMinBytesInput )
                {
                    PRINT_EXIT;
                    return Result(
                               TCodecProcessResult::EDstNotFilled,
                               totalSrcBytesCopied, totalDstBytesAdded );
                }
            }

            /**
            * initialize the variables like srcUsed and dstLen accordingly.
            * call Decode.
            */

            TInt srcUsed = iInternalInputBufferResidueLen
                           - internalInputBufferPos;
            TInt dstLen  = iOutFrameSize;

            TInt error = iCodec->Decode(
                             &iInternalInputBuffer[internalInputBufferPos],
                             srcUsed, iInternalOutputBuffer, dstLen );

            if ( KErrNone != error )
            {
                iInternalInputBufferResidueLen = 0;
                PRINT_ERR( error );
                return Result(
                           TCodecProcessResult::EProcessError,
                           totalSrcBytesCopied, totalDstBytesAdded );
            }

            /**
            * Fill Destination Buffer
            */

            iInternalOutputBufferResidueLen = dstLen;
            numberOfBytesCopied = CopyToDstBuffer( dst, totalDstBytesAdded );
            dstBufferRemainingBytes -= numberOfBytesCopied;

            /***
            * Fill Sorce Buffer
            */

            internalInputBufferPos += srcUsed ;
            ShiftData( internalInputBufferPos, 0 );
            numberOfBytesCopied = CopyFromSrcBuffer( src,
                                  totalSrcBytesCopied );
            srcBufferRemainingBytes -= numberOfBytesCopied;
            internalInputBufferPos = 0;

            /***
            * check four conditions if else for src and if else for dst
            */

            // src buffer has available bytes to decode
            if ( srcBufferRemainingBytes > 0 )
            {
                if ( dstBufferRemainingBytes == 0 )
                {
                    PRINT_EXIT;
                    return Result( TCodecProcessResult::EProcessIncomplete,
                                   totalSrcBytesCopied, totalDstBytesAdded );
                }
            }

            else
            {
                // dst buffer has availabe space for decoded bytes
                if ( dstBufferRemainingBytes > 0 )
                {
                    // last frame of the input stream
                    if ( lastFrame )
                    {
                        if ( iInternalInputBufferResidueLen == 0 )
                        {
                            PRINT_EXIT;
                            return Result( TCodecProcessResult::EEndOfData,
                                           totalSrcBytesCopied, totalDstBytesAdded );
                        }
                    }
                    else
                    {
                        PRINT_EXIT;
                        return Result( TCodecProcessResult::EDstNotFilled,
                                       totalSrcBytesCopied, totalDstBytesAdded );
                    }
                }
                else
                {
                    /**
                     *internal output buffer has decoded bytes which is not
                     *given to dst buffer.
                     */
                    if ( iInternalOutputBufferResidueLen
                            - iInternalOutputBufferPos > 0 )
                    {
                        PRINT_EXIT;
                        return Result(
                                   TCodecProcessResult::EProcessIncomplete,
                                   totalSrcBytesCopied, totalDstBytesAdded );
                    }
                    // last frame of the input stream
                    else if ( lastFrame )
                    {
                        // if internal buffer has available bytes to decode
                        if ( iInternalInputBufferResidueLen > 0 )
                        {
                            PRINT_EXIT;
                            return Result(
                                       TCodecProcessResult::EProcessIncomplete,
                                       totalSrcBytesCopied, totalDstBytesAdded );
                        }
                        else
                        {
                            iInternalInputBufferResidueLen = 0;
                            PRINT_EXIT;
                            return Result(
                                       TCodecProcessResult::EEndOfData,
                                       totalSrcBytesCopied, totalDstBytesAdded );
                        }
                    }
                    else
                    {
                        PRINT_EXIT;
                        return Result(
                                   TCodecProcessResult::EProcessComplete,
                                   totalSrcBytesCopied, totalDstBytesAdded );
                    }
                }
            }
        }
    } while ( 1 );
}
Exemplo n.º 30
0
Arquivo: pftp.c Projeto: neeohw/pftp
int main( int argc, char *argv[]) {
    int c = 0;
    int ret_val = 0;
    int port = 0;
    char network[128];
    char *file = NULL;
    char *iface = NULL;
    char *mcast_addr = NULL;
    int bfd = 0;
    network[0] = '\0';

#ifdef UDPTEST
    int sockfd = 0;
#else
    pgm_error_t* pgm_err = NULL;
    pgm_sock_t *pgm_sock;
    pthread_t nak_thread;
#endif

    while((c = getopt(argc, argv, ":hm:i:p:f:")) != -1) {
        switch (c) {
        case 'm':
            mcast_addr = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'p':
            port = atoi(optarg);
            break;
        case 'h':
        case '?':
            print_usage();
            break;
        default:
            print_usage();
            break;
        }
    }

    if(optind != argc-1) {
        PRINT_ERR("Please provide the path to a file you want to send!");
        ret_val = -1;
        goto ret_error;
    } else {
        file = argv[optind];
    }

    if (iface) {
        char *ifaddr = pftp_inet_iftoa(iface);
        if (strlen(ifaddr) > 0) {
            strncat(network, ifaddr, 128);
            strncat(network, ";", 128);
        }
    }

    if (mcast_addr) {
        strncat(network, mcast_addr, 128);
    } else {
        strncat(network, PFTP_DEFAULT_MCAST_ADDR, 128);
    }

#ifdef UDPTEST
    struct sockaddr_in servaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(PFTP_DEFAULT_MCAST_ADDR);
    servaddr.sin_port = port ? htons(port) : htons(PFTP_UDP_PORT);
#else

    if (0 != pftp_create(1, network, port, &pgm_sock)) {
        ret_val = -1;
        goto ret_error;
    }

    int pgm_status;

    /* Start NAK receiver thread */
    m_run_receiver = 1;
    pthread_create(&nak_thread, NULL, nak_routine, (void*)pgm_sock);
#endif

    char buf[PGMBUF_SIZE];
    buf[0] = '\0';

    struct stat fstat;
    if (-1 == stat(file, &fstat)) {
        PRINT_ERR("Couldn't stat file: %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }

    char *fname = strrchr(file, '/');
    if (!fname) {
        fname = file;
    } else {
        fname = fname+1;
    }

    memset(buf, 0, PGMBUF_SIZE);
    snprintf(buf, PGMBUF_SIZE, CMD_SEND_FILE" %ld %s", fstat.st_size, fname);
    PRINT_DBG("Sending file with command: %s", buf);

    size_t bytes_written;
    int bytes_read;

#ifdef UDPTEST
    bytes_written = sendto(sockfd, buf, strlen(buf)+1, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
    if (bytes_written != strlen(buf)+1) {
        PRINT_ERR("Couldn't send file transfer command! %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }
#else
    pgm_status = pgm_status = pgm_send(pgm_sock, buf, strlen(buf)+1, &bytes_written);
    if (pgm_status != PGM_IO_STATUS_NORMAL) {
        PRINT_ERR("Couldn't send file transfer command!");
        ret_val = -1;
        goto ret_error;
    }
#endif

    bfd = open(file, O_RDONLY);
    if (bfd < 0) {
        PRINT_ERR("Couldn't open file for reading! %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }

    int fds = 0;
    fd_set writefds;
    fd_set readfds;

    bytes_read = read(bfd, buf, PGMBUF_SIZE);
    while (bytes_read > 0) {

#ifdef UDPTEST

        bytes_written = sendto(sockfd, buf, bytes_read, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));

#else
        struct timeval tv;
        pgm_status = pgm_send(pgm_sock, buf, bytes_read, &bytes_written);

        //PRINT_DBG("pgm_status: %d", pgm_status);

        switch (pgm_status) {

        case PGM_IO_STATUS_NORMAL :
        {
#endif
            if (bytes_written != bytes_read) {
                PRINT_ERR("Error sending file!");
                ret_val = -1;
                goto ret_error;
            }
            bytes_read = read(bfd, buf, PGMBUF_SIZE);

#ifdef UDPTEST
            struct timespec ts = {0, 35000};
            nanosleep(&ts, NULL);
#else
        } break;
        case PGM_IO_STATUS_TIMER_PENDING:
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_TIME_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            goto block;
        }
        case PGM_IO_STATUS_RATE_LIMITED :
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            /* No accidental fallthrough! */
        }
        case PGM_IO_STATUS_CONGESTION :
        case PGM_IO_STATUS_WOULD_BLOCK :
block:
        {
            FD_ZERO(&writefds);
            pgm_select_info(pgm_sock, NULL, &writefds, &fds);
            fds = select(fds, NULL, &writefds, NULL, pgm_status == PGM_IO_STATUS_WOULD_BLOCK ? NULL : &tv);
        } break;
        default:
            PRINT_ERR("Send error!");
            ret_val = -1;
            goto ret_error;
            break;
        }
#endif
    }

#ifndef UDPTEST
    pthread_mutex_lock(&m_pftp_mutex);
    m_run_receiver = 0;
    pthread_mutex_unlock(&m_pftp_mutex);
    pthread_join(nak_thread, NULL);
    pthread_mutex_destroy(&m_pftp_mutex);
#endif

    goto ret_good;

ret_error:
    PRINT_DBG("Exit error");
    goto ret;
ret_good:
    PRINT_DBG("Exit good");
ret:
    if (bfd > 0)
        close(bfd);
#ifdef UDPTEST
    if (sockfd > 0)
        close(sockfd);
#else
    if (pgm_sock) {
        pftp_stop(pgm_sock);
    }
#endif
    return ret_val;
}