static err_t fileMsgRead(size_t* read, void* buf, size_t count, void* file) { file_msg_st* f; // pre ASSERT(memIsValid(file, sizeof(file_msg_st))); ASSERT(memIsValid(buf, count)); ASSERT(memIsValid(read, sizeof(size_t))); // найти сообщение f = (file_msg_st*)file; if (f->i >= 4) return ERR_FILE_READ; if (!_msgs[f->i].valid) return ERR_FILE_NOT_FOUND; // прочитать частично? ASSERT(f->offset <= _msgs[f->i].len); if (count + f->offset > _msgs[f->i].len) { memCopy(buf, _msgs[f->i].buf + f->offset, *read = _msgs[f->i].len - f->offset); ++f->i, f->offset = 0; return ERR_MAX; } // прочитать полностью memCopy(buf, _msgs[f->i].buf + f->offset, *read = count); f->offset += count; // конец сообщения? if (f->offset == _msgs[f->i].len) ++f->i, f->offset = 0; // все нормально return ERR_OK; }
void memStrCat(memChunk *dest, char *string) { memChunk result,*temp; temp = memReserve (dest->size + strlen (string)+1); result.address = dest->address + strlen (dest->address); result.size = dest->size - strlen (dest->address) + 1; memCopy (temp, memString (string)); memCopy (&result, temp); memFree (temp); }
static err_t fileRead(size_t* read, void* buf, size_t count, void* file) { file_st* f = (file_st*)file; u16 len; err_t code; // pre ASSERT(memIsValid(f, sizeof(file_st))); ASSERT(memIsValid(buf, count)); ASSERT(memIsValid(read, sizeof(size_t))); // достигнут конец файла? if (f->frame == 0) { *read = 0; return ERR_MAX; } // достигается конец файла? if (f->frame_offset + count > f->frame_len) { *read = f->frame_len - f->frame_offset; memCopy(buf, f->frame + f->frame_offset, *read); code = ERR_MAX; } // обычное чтение else { *read = count; memCopy(buf, f->frame + f->frame_offset, *read); code = ERR_OK; } // к следующему пакету f->frame += f->frame_len; if (f->frame + 2 >= f->data + f->data_len) { f->frame = 0; f->frame_len = f->frame_offset = 0; } else { u16From(&len, f->frame, 2); f->frame_len = (size_t)len; f->frame += 2; f->frame_offset = 0; // выход за границы? if (f->frame + f->frame_len > f->data + f->data_len) return ERR_BAD_FORMAT; } // все нормально return code; }
/// Forward 5/3 2D DWT. See common rules (above) for more details. /// @param in Expected to be normalized into range [-128, 127]. /// Will not be preserved (will be overwritten). /// @param out output buffer on GPU /// @param sizeX width of input image (in pixels) /// @param sizeY height of input image (in pixels) /// @param levels number of recursive DWT levels /// @backup use to test time //at the end of namespace dwt_cuda (line338) void fdwt53(cl_mem in, cl_mem out, int sizeX, int sizeY, int levels) { // select right width of kernel for the size of the image if(sizeX >= 960) { launchFDWT53Kernel(192, 8, in, out, sizeX, sizeY); } else if (sizeX >= 480) { launchFDWT53Kernel(128, 8, in, out, sizeX, sizeY); } else { launchFDWT53Kernel(64, 8, in, out, sizeX, sizeY); } // if this was not the last level, continue recursively with other levels if (levels > 1) { // copy output's LL band back into input buffer const int llSizeX = (sizeX / 2) + ((sizeX % 2) ? 1 :0); const int llSizeY = (sizeY / 2) + ((sizeY % 2) ? 1 :0); memCopy(in, out, llSizeX, llSizeY); // run remaining levels of FDWT fdwt53(in, out, llSizeX, llSizeY, levels - 1); } }
void sh_poke(char* params){ // poke pointer byte(decimal) int i; for(i=0;i<strLen(params);i++){ if(params[i] == ' ') break; } char substr[i+1]; memCopy(params,substr,i); substr[i] = 0; char* pointer = (char*) ((int*)strToInt(substr)); char substr2[strLen(params)-i]; memCopy(params+i+1,substr2,strLen(params)-i); int value = strToInt(substr2); *pointer = value; }
void memStringRealloc(memChunk *chunk) { memCheckState (); memChunk *temp; temp = memString (chunk->address); //printf("Reallocating chunk size %d to size %d\n",chunk->size,temp->size); memCopy (chunk,temp); memFree (temp); }
err_t dstuStdParams(dstu_params* params, const char* name) { if (!memIsValid(params, sizeof(dstu_params))) return ERR_BAD_INPUT; memSetZero(params, sizeof(dstu_params)); if (strEq(name, _curve163pb_name)) { _LOAD_NAMED_PARAMS(params, curve163pb); memCopy(params->P, _curve163pb_P, sizeof(_curve163pb_P)); return ERR_OK; } if (strEq(name, _curve167pb_name)) { _LOAD_NAMED_PARAMS(params, curve167pb); return ERR_OK; } if (strEq(name, _curve173pb_name)) { _LOAD_NAMED_PARAMS(params, curve173pb); return ERR_OK; } if (strEq(name, _curve179pb_name)) { _LOAD_NAMED_PARAMS(params, curve179pb); return ERR_OK; } if (strEq(name, _curve191pb_name)) { _LOAD_NAMED_PARAMS(params, curve191pb); return ERR_OK; } if (strEq(name, _curve233pb_name)) { _LOAD_NAMED_PARAMS(params, curve233pb); return ERR_OK; } if (strEq(name, _curve257pb_name)) { _LOAD_NAMED_PARAMS(params, curve257pb); return ERR_OK; } if (strEq(name, _curve307pb_name)) { _LOAD_NAMED_PARAMS(params, curve307pb); return ERR_OK; } if (strEq(name, _curve367pb_name)) { _LOAD_NAMED_PARAMS(params, curve367pb); return ERR_OK; } if (strEq(name, _curve431pb_name)) { _LOAD_NAMED_PARAMS(params, curve431pb); return ERR_OK; } return ERR_FILE_NOT_FOUND; }
int main() { time_t start = time(NULL); int dim = L * (nmax + 1); const real epsg = EPSG; const real epsf = EPSF; const real epsx = EPSX; const int maxits = MAXITS; stpscal = 0.5; int info; real* x; int* nbd; real* l; real* u; memAlloc<real>(&x, dim); memAlloc<int>(&nbd, dim); memAlloc<real>(&l, dim); memAlloc<real>(&u, dim); memAllocHost<real>(&f_tb_host, &f_tb_dev, 1); cudaSetDeviceFlags(cudaDeviceMapHost); cublasCreate_v2(&cublasHd); U = 1; J = 0.1; mu = 0.5; initProb(x, nbd, l, u, dim); lbfgsbminimize(dim, 4, x, epsg, epsf, epsx, maxits, nbd, l, u, info); printf("info: %d\n", info); printf("f: %e\n", *f_tb_host); real* x_host = new real[dim]; memCopy(x_host, x, dim * sizeof(real), cudaMemcpyDeviceToHost); printf("x: "); for (int i = 0; i < dim; i++) { printf("%f, ", x_host[i]); } printf("\n"); memFreeHost(f_tb_host); memFree(x); memFree(nbd); memFree(l); memFree(u); cublasDestroy_v2(cublasHd); cudaDeviceReset(); time_t end = time(NULL); printf("Runtime: %ld", end-start); }
void sh_handler(char* command){ int i=0; while(command[i]!=' ' && command[i]!=0) i++; if(i == 0) return; char program[i+1]; memCopy(command,program,i); program[i] = 0; char params[strLen(command)-i]; memCopy(command+i+1,params,strLen(command)-i+1); params[strLen(command)-i-1] = 0; i = 0; while(!strEquals(shCommandList[i],program) && !strEquals(shCommandList[i],"null")) i++; if(!strEquals(shCommandList[i],"null")) (*shFunctionList[i])(params); else { ttprint("Command not found: "); ttprintln(program); } }
void sh_textDump(char* params){ // textDump pointer length int i; for(i=0;i<strLen(params);i++){ if(params[i] == ' ') break; } char substr[i+1]; memCopy(params,substr,i); substr[i] = 0; char* pointer = (char*) ((int*)strToInt(substr)); char substr2[strLen(params)-i]; memCopy(params+i+1,substr2,strLen(params)-i); int length = strToInt(substr2); for(i=0;i<length;i++){ ttprintChar(pointer[i]); } ttprint("\n"); }
void sh_beep(char* params){ //"beep freq duration" int i,freq = 440, dur = 1000; for(i=0;i<strLen(params);i++){ if(params[i] == ' ') break; } char frequency[i+1]; memCopy(params,frequency,i); frequency[i] = 0; freq = strToInt(frequency); if(i != strLen(params)){ char duration[strLen(params)-i]; memCopy(params+i+1,duration,strLen(params)-i); dur = strToInt(duration); } play_sound(freq); sleep(dur); play_sound(0); }
void scroll() { u32 no_rows_shift; u16 blank = 0x20 | (attrib << 8); if(cursor_y >= 25) { no_rows_shift = cursor_y - 25 + 1; memCopy((u8 *)scrn_start, (u8 *)scrn_start + no_rows_shift * 80 * 2, (25 - no_rows_shift) * 80 * 2); memSet16(scrn_start + 24 * 80, blank, 80); cursor_y = 24; } }
void memCopy(void* _dst, const void* _src, uint32_t _size, uint32_t _num, uint32_t _srcPitch, uint32_t _dstPitch) { const uint8_t* src = (const uint8_t*)_src; uint8_t* dst = (uint8_t*)_dst; for (uint32_t ii = 0; ii < _num; ++ii) { memCopy(dst, src, _size); src += _srcPitch; dst += _dstPitch; } }
static err_t bakeTestCertVal(octet* pubkey, const bign_params* params, const octet* data, size_t len) { if (!memIsValid(params, sizeof(bign_params)) || (params->l != 128 && params->l != 192 && params->l != 256) || !memIsNullOrValid(pubkey, params->l / 2)) return ERR_BAD_INPUT; if (!memIsValid(data, len) || len < params->l / 2) return ERR_BAD_CERT; if (pubkey) memCopy(pubkey, data + (len - params->l / 2), params->l / 2); return ERR_OK; }
struct File *readFile(char* params){ char** pointer; int len = getFilePointer(params,pointer); struct File *file; file = (struct File*)malloc(sizeof(struct File)); file->filename = (char*)malloc(strLen(params)); memCopy(params,file->filename,strLen(params)); file->filesize = len; int i; struct StringListNode *line = (struct StringListNode*) malloc(sizeof(struct StringListNode)); file->firstLine = line; line->prev = 0; line->next = 0; int lineStart = 0; // split the file into separate lines for(i = 0; i < len; i++){ if((*pointer)[i] == '\n' || i == len-1){ line->str = (char*) malloc(i-lineStart+2); memCopy((*pointer+lineStart), line->str, i-lineStart+1); (line->str)[i-lineStart+1] = 0; //set up the next line struct StringListNode *tline; tline = (struct StringListNode*) malloc(sizeof(struct StringListNode)); tline->prev = line; line->next = tline; line = tline; lineStart = i+1; } if(i == len-1){ //nix the next line, since there isn't one line = line->prev; free(line->next, sizeof(struct StringListNode)); line->next = 0; } } return file; }
int flattenStringList(struct StringListNode* head, char** str){ int length = 0, index = 0; struct StringListNode *temp = head; while(temp){ length += strLen(temp->str)-1; temp = temp->next; } *str = (char*)malloc(length+1); temp = head; while(temp){ memCopy(temp->str, (*str)+index, strLen(temp->str)-1); index += strLen(temp->str)-1; temp = temp->next; } (*str)[index] = 0; return length; }
/* ******************************************************************************* ����������� � ������������� ��������� �����, ��������� � ��������� bign_key \remark �������� ���� �������� ����� PublicKey ::= BIT STRING ******************************************************************************* */ int bign_o2i_pubkey(bign_key* key, const unsigned char* in, long len) { // ������� �������� if (!key || !in) { BEE2EVPerr(BEE2EVP_F_BIGN_O2I_PUBKEY, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (len != key->params.l / 2) { BEE2EVPerr(BEE2EVP_F_BIGN_O2I_PUBKEY, BEE2EVP_R_INVALID_PUBKEY); return 0; } // ��������� ���� memCopy(key->pubKey, in, len); return 1; }
int main(void) { // //-------------------------------------- //-- 串口初始化 serialDebug.begin(115200); // //-------------------------------------- //-- EEprom 调取参数 if (EEP.data.ver==0 || EEp_init_flag==0) eep.wirte((uint8 *)&EEP_DF, (uint32)&EEP, sizeof(para)); memCopy((char *)¶, (char *)&EEP, sizeof(para)); // //-------------------------------------- //== 操作系统启动 os_sys_init(init_task); // //-------------------------------------- }
static int bign_asn1_params2fieldid(BIGN_FIELDID* field, const bign_params* params) { int ok = 0; BIGNUM* p = NULL; octet rev[64]; // ����������� ������� �������� if (!params || !field) { BEE2EVPerr(BEE2EVP_F_BIGN_ASN1_PARAMS2FIELDID, ERR_R_PASSED_NULL_PARAMETER); return 0; } // ����������� field if (field->fieldType) ASN1_OBJECT_free(field->fieldType); if (field->prime) ASN1_INTEGER_free(field->prime); // ���������� fieldType if (!(field->fieldType = OBJ_nid2obj(id_bign_primefield))) { BEE2EVPerr(BEE2EVP_F_BIGN_ASN1_PARAMS2FIELDID, ERR_R_OBJ_LIB); goto err; } // ���������� prime memCopy(rev, params->p, params->l / 4); memRev(rev, params->l / 4); if (!(p = BN_new()) || !BN_bin2bn(rev, params->l / 4, p)) { BEE2EVPerr(BEE2EVP_F_BIGN_ASN1_PARAMS2FIELDID, ERR_R_MALLOC_FAILURE); goto err; } field->prime = BN_to_ASN1_INTEGER(p, NULL); if (!field->prime) { BEE2EVPerr(BEE2EVP_F_BIGN_ASN1_PARAMS2FIELDID, ERR_R_ASN1_LIB); goto err; } ok = 1; // ����� err: p ? OPENSSL_free(p) : 0; memSetZero(rev, sizeof(rev)); return ok; }
void sreplace(char *s,char *orig,char *rep,char multi,long dsize) { char *p; memChunk *buffer,*string,*result; if(!(p=strstr(s, orig))) return; buffer=memReserve(dsize); string=memString(s); memCopy(buffer, string); snprintf(buffer->address+(p-s), buffer->size-(p-s),"%s%s", rep, p+strlen(orig)); result=memString(buffer->address); strcpy(s,result->address); //unsafe memFree(string); memFree(result); memFree(buffer); }
// run sh_handler on each line of a file (or the buffer) void sh_shell(char* params){ struct StringListNode *temp; if(strEquals(params,"buffer")){ temp = fileBuffer->firstLine; } else { struct File *f = readFile(params); temp = f->firstLine; } while(temp){ int len = strLen(temp->str)-1; if((temp->str)[len-1] == '\n'){ // lines ends with \n char* line = (char*) malloc(len); memCopy(temp->str, line, len); line[len-1] = 0; sh_handler(line); free(line, len); } else { // line doesn't end with \n (last line in file) sh_handler(temp->str); } temp = temp->next; } }
int bign_i2o_pubkey(unsigned char** out, const bign_key* key) { int ret; // ������� �������� if (!key) { BEE2EVPerr(BEE2EVP_F_BIGN_I2O_PUBKEY, ERR_R_PASSED_NULL_PARAMETER); return 0; } // ����� ����� � ������� ret = key->params.l / 2; if (!out) return ret; // ����������� ����� if (!*out && !(*out = OPENSSL_malloc(ret))) { BEE2EVPerr(BEE2EVP_F_BIGN_I2O_PUBKEY, ERR_R_MALLOC_FAILURE); return 0; } // ���������� ���� memCopy(*out, key->pubKey, ret); return ret; }
static err_t fileMsgWrite(size_t* written, const void* buf, size_t count, void* file) { file_msg_st* f; // pre ASSERT(memIsValid(file, sizeof(file_msg_st))); ASSERT(memIsValid(buf, count)); ASSERT(memIsValid(written, sizeof(size_t))); // найти сообщение f = (file_msg_st*)file; if (f->i >= 4) return ERR_FILE_WRITE; // записать if (count > sizeof(_msgs[f->i].buf)) return ERR_OUTOFMEMORY; _msgs[f->i].valid = TRUE; memCopy(_msgs[f->i].buf, buf, count); *written = _msgs[f->i].len = count; // к следующему сообщению ++f->i, f->offset = 0; // все нормально return ERR_OK; }
static err_t beeReadAndCalcStamp(octet stampRead[STAMP_SIZE], octet stampCalc[STAMP_SIZE]) { err_t code = ERR_OK; char name[MAX_PATH]; HANDLE hFile, hMapping; DWORD size, offset; octet* image; void* hash_state; // имя модуля if (!GetModuleFileNameA(GetModuleHandleA("bee2.dll"), name, sizeof(name))) return ERR_SYS; // открыть файл hFile = CreateFileA(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return ERR_FILE_OPEN; // длина файла size = SetFilePointer(hFile, 0, NULL, FILE_END); if (size == INVALID_SET_FILE_POINTER) { CloseHandle(hFile); return ERR_SYS; } // проецировать файл в память hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hMapping == NULL) { CloseHandle(hFile); return ERR_SYS; } // отобразить файл в память image = (octet*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0); if (image == NULL) { CloseHandle(hMapping), CloseHandle(hFile); return ERR_SYS; } // найти смещение контрольной характеристики offset = stampFindOffset(image, size); if (offset == (DWORD)-1) { UnmapViewOfFile(image), CloseHandle(hMapping), CloseHandle(hFile); return ERR_BAD_FORMAT; } // сохранить характеристику memCopy(stampRead, image + offset, STAMP_SIZE); // вычислить характеристику CASSERT(STAMP_SIZE >= 32); memSetZero(stampCalc, STAMP_SIZE); hash_state = blobCreate(beltHash_keep()); if (hash_state) { // хэшировать beltHashStart(hash_state); beltHashStepH(image, offset, hash_state); beltHashStepH(image + offset + STAMP_SIZE, size - offset - STAMP_SIZE, hash_state); beltHashStepG(stampCalc, hash_state); blobClose(hash_state); } else code = ERR_OUTOFMEMORY; // очистка и выход UnmapViewOfFile(image); CloseHandle(hMapping); CloseHandle(hFile); return code; }
void main(void) { uint_least8_t estNumber = 0; #ifdef FAST_ROM_V1p6 uint_least8_t ctrlNumber = 0; #endif // Only used if running from FLASH // Note that the variable FLASH is defined by the project #ifdef FLASH // Copy time critical code and Flash setup code to RAM // The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart // symbols are created by the linker. Refer to the linker files. memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart); #ifdef F2802xF //copy .econst to unsecure RAM if(*econst_end - *econst_start) { memCopy((uint16_t *)&econst_start,(uint16_t *)&econst_end,(uint16_t *)&econst_ram_load); } //copy .switch ot unsecure RAM if(*switch_end - *switch_start) { memCopy((uint16_t *)&switch_start,(uint16_t *)&switch_end,(uint16_t *)&switch_ram_load); } #endif #endif // initialize the hardware abstraction layer halHandle = HAL_init(&hal,sizeof(hal)); // check for errors in user parameters USER_checkForErrors(&gUserParams); // store user parameter error in global variable gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams); // do not allow code execution if there is a user parameter error if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError) { for(;;) { gMotorVars.Flag_enableSys = false; } } // initialize the user parameters USER_setParams(&gUserParams); // set the hardware abstraction layer parameters HAL_setParams(halHandle,&gUserParams); // initialize the controller #ifdef FAST_ROM_V1p6 ctrlHandle = CTRL_initCtrl(ctrlNumber, estNumber); //v1p6 format (06xF and 06xM devices) controller_obj = (CTRL_Obj *)ctrlHandle; #else ctrlHandle = CTRL_initCtrl(estNumber,&ctrl,sizeof(ctrl)); //v1p7 format default #endif { CTRL_Version version; // get the version number CTRL_getVersion(ctrlHandle,&version); gMotorVars.CtrlVersion = version; } // set the default controller parameters CTRL_setParams(ctrlHandle,&gUserParams); // initialize the frequency of execution monitoring module femHandle = FEM_init(&fem,sizeof(fem)); FEM_setParams(femHandle, USER_SYSTEM_FREQ_MHz * 1000000.0, // timer frequency, Hz (uint32_t)USER_SYSTEM_FREQ_MHz * 1000000, // timer period, cnts USER_CTRL_FREQ_Hz, // set point frequency, Hz 1000.0); // max frequency error, Hz // initialize the CPU usage module cpu_usageHandle = CPU_USAGE_init(&cpu_usage,sizeof(cpu_usage)); CPU_USAGE_setParams(cpu_usageHandle, (uint32_t)USER_SYSTEM_FREQ_MHz * 1000000, // timer period, cnts (uint32_t)USER_ISR_FREQ_Hz); // average over 1 second of ISRs // setup faults HAL_setupFaults(halHandle); // initialize the interrupt vector table HAL_initIntVectorTable(halHandle); // enable the ADC interrupts HAL_enableAdcInts(halHandle); // reload timer to start running frequency of execution monitoring HAL_reloadTimer(halHandle,0); // enable global interrupts HAL_enableGlobalInts(halHandle); // enable debug interrupts HAL_enableDebugInt(halHandle); // disable the PWM HAL_disablePwm(halHandle); #ifdef DRV8301_SPI // turn on the DRV8301 if present HAL_enableDrv(halHandle); // initialize the DRV8301 interface HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars); #endif #ifdef DRV8305_SPI // turn on the DRV8305 if present HAL_enableDrv(halHandle); // initialize the DRV8305 interface HAL_setupDrvSpi(halHandle,&gDrvSpi8305Vars); #endif // enable DC bus compensation CTRL_setFlag_enableDcBusComp(ctrlHandle, true); // compute scaling factors for flux and torque calculations gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf(); gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf(); gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf(); gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf(); // disable offsets recalibration by default gMotorVars.Flag_enableOffsetcalc = false; for(;;) { // Waiting for enable system flag to be set while(!(gMotorVars.Flag_enableSys)); // loop while the enable system flag is true while(gMotorVars.Flag_enableSys) { CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle; // increment counters gCounter_updateGlobals++; // enable/disable the use of motor parameters being loaded from user.h CTRL_setFlag_enableUserMotorParams(ctrlHandle,gMotorVars.Flag_enableUserParams); // enable/disable Rs recalibration during motor startup EST_setFlag_enableRsRecalc(obj->estHandle,gMotorVars.Flag_enableRsRecalc); // enable/disable automatic calculation of bias values CTRL_setFlag_enableOffset(ctrlHandle,gMotorVars.Flag_enableOffsetcalc); if(CTRL_isError(ctrlHandle)) { // set the enable controller flag to false CTRL_setFlag_enableCtrl(ctrlHandle,false); // set the enable system flag to false gMotorVars.Flag_enableSys = false; // disable the PWM HAL_disablePwm(halHandle); } else { // update the controller state bool flag_ctrlStateChanged = CTRL_updateState(ctrlHandle); // enable or disable the control CTRL_setFlag_enableCtrl(ctrlHandle, gMotorVars.Flag_Run_Identify); if(flag_ctrlStateChanged) { CTRL_State_e ctrlState = CTRL_getState(ctrlHandle); if(ctrlState == CTRL_State_OffLine) { // enable the PWM HAL_enablePwm(halHandle); } else if(ctrlState == CTRL_State_OnLine) { if(gMotorVars.Flag_enableOffsetcalc == true) { // update the ADC bias values HAL_updateAdcBias(halHandle); } else { // set the current bias HAL_setBias(halHandle,HAL_SensorType_Current,0,_IQ(I_A_offset)); HAL_setBias(halHandle,HAL_SensorType_Current,1,_IQ(I_B_offset)); HAL_setBias(halHandle,HAL_SensorType_Current,2,_IQ(I_C_offset)); // set the voltage bias HAL_setBias(halHandle,HAL_SensorType_Voltage,0,_IQ(V_A_offset)); HAL_setBias(halHandle,HAL_SensorType_Voltage,1,_IQ(V_B_offset)); HAL_setBias(halHandle,HAL_SensorType_Voltage,2,_IQ(V_C_offset)); } // Return the bias value for currents gMotorVars.I_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Current,0); gMotorVars.I_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Current,1); gMotorVars.I_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Current,2); // Return the bias value for voltages gMotorVars.V_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Voltage,0); gMotorVars.V_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Voltage,1); gMotorVars.V_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Voltage,2); // enable the PWM HAL_enablePwm(halHandle); } else if(ctrlState == CTRL_State_Idle) { // disable the PWM HAL_disablePwm(halHandle); gMotorVars.Flag_Run_Identify = false; } if((CTRL_getFlag_enableUserMotorParams(ctrlHandle) == true) && (ctrlState > CTRL_State_Idle) && (gMotorVars.CtrlVersion.minor == 6)) { // call this function to fix 1p6 USER_softwareUpdate1p6(ctrlHandle); } } } if(EST_isMotorIdentified(obj->estHandle)) { // set the current ramp EST_setMaxCurrentSlope_pu(obj->estHandle,gMaxCurrentSlope); gMotorVars.Flag_MotorIdentified = true; // set the speed reference CTRL_setSpd_ref_krpm(ctrlHandle,gMotorVars.SpeedRef_krpm); // set the speed acceleration CTRL_setMaxAccel_pu(ctrlHandle,_IQmpy(MAX_ACCEL_KRPMPS_SF,gMotorVars.MaxAccel_krpmps)); if(Flag_Latch_softwareUpdate) { Flag_Latch_softwareUpdate = false; USER_calcPIgains(ctrlHandle); } } else { Flag_Latch_softwareUpdate = true; // the estimator sets the maximum current slope during identification gMaxCurrentSlope = EST_getMaxCurrentSlope_pu(obj->estHandle); } // when appropriate, update the global variables if(gCounter_updateGlobals >= NUM_MAIN_TICKS_FOR_GLOBAL_VARIABLE_UPDATE) { // reset the counter gCounter_updateGlobals = 0; updateGlobalVariables_motor(ctrlHandle); } // get the maximum delta count observed gMaxDeltaCntObserved = FEM_getMaxDeltaCntObserved(femHandle); // check for errors if(FEM_isFreqError(femHandle)) { gNumFreqErrors = FEM_getErrorCnt(femHandle); } // update CPU usage updateCPUusage(); // enable/disable the forced angle EST_setFlag_enableForceAngle(obj->estHandle,gMotorVars.Flag_enableForceAngle); // enable or disable power warp CTRL_setFlag_enablePowerWarp(ctrlHandle,gMotorVars.Flag_enablePowerWarp); #ifdef DRV8301_SPI HAL_writeDrvData(halHandle,&gDrvSpi8301Vars); HAL_readDrvData(halHandle,&gDrvSpi8301Vars); #endif #ifdef DRV8305_SPI HAL_writeDrvData(halHandle,&gDrvSpi8305Vars); HAL_readDrvData(halHandle,&gDrvSpi8305Vars); #endif } // end of while(gFlag_enableSys) loop // disable the PWM HAL_disablePwm(halHandle); // set the default controller parameters (Reset the control to re-identify the motor) CTRL_setParams(ctrlHandle,&gUserParams); gMotorVars.Flag_Run_Identify = false; } // end of for(;;) loop } // end of main() function
err_t g12sVerify(const g12s_params* params, const octet hash[], const octet sig[], const octet pubkey[]) { err_t code; size_t m, mo; // состояние ec_o* ec; word* Q; /* [2n] открытый ключ / точка R */ word* r; /* [m] первая (старшая) часть подписи */ word* s; /* [m] вторая часть подписи */ word* e; /* [m] обработанное хэш-значение, v */ void* stack; // старт code = g12sCreateEc(&ec, params, g12sVerify_deep); ERR_CALL_CHECK(code); // размерности order m = W_OF_B(params->l); mo = O_OF_B(params->l); // проверить входные указатели if (!memIsValid(hash, mo) || !memIsValid(sig, 2 * mo) || !memIsValid(pubkey, 2 * ec->f->no)) { g12sCloseEc(ec); return ERR_BAD_INPUT; } // раскладка состояния Q = objEnd(ec, word); r = Q + 2 * ec->f->n; s = r + m; e = s + m; stack = e + m; // загрузить Q if (!qrFrom(ecX(Q), pubkey, ec->f, stack) || !qrFrom(ecY(Q, ec->f->n), pubkey + ec->f->no, ec->f, stack)) { g12sCloseEc(ec); return ERR_BAD_PUBKEY; } // загрузить r и s memCopy(s, sig + mo, mo); memRev(s, mo); wwFrom(s, s, mo); memCopy(r, sig, mo); memRev(r, mo); wwFrom(r, r, mo); if (wwIsZero(s, m) || wwIsZero(r, m) || wwCmp(s, ec->order, m) >= 0 || wwCmp(r, ec->order, m) >= 0) { g12sCloseEc(ec); return ERR_BAD_SIG; } // e <- hash \mod q memCopy(e, hash, mo); memRev(e, mo); wwFrom(e, e, mo); zzMod(e, e, m, ec->order, m, stack); // e == 0 => e <- 1 if (wwIsZero(e, m)) e[0] = 1; // e <- e^{-1} \mod q [v] zzInvMod(e, e, ec->order, m, stack); // s <- s e \mod q [z1] zzMulMod(s, s, e, ec->order, m, stack); // e <- - e r \mod q [z2] zzMulMod(e, e, r, ec->order, m, stack); zzNegMod(e, e, ec->order, m); // Q <- s P + e Q [z1 P + z2 Q = R] if (!ecAddMulA(Q, ec, stack, 2, ec->base, s, m, Q, e, m)) { g12sCloseEc(ec); return ERR_BAD_PARAMS; } // s <- x_Q \mod q [x_R \mod q] qrTo((octet*)Q, ecX(Q), ec->f, stack); wwFrom(Q, Q, ec->f->no); zzMod(s, Q, ec->f->n, ec->order, m, stack); // s == r? code = wwEq(r, s, m) ? ERR_OK : ERR_BAD_SIG; // завершение g12sCloseEc(ec); return code; }
err_t g12sSign(octet sig[], const g12s_params* params, const octet hash[], const octet privkey[], gen_i rng, void* rng_stack) { err_t code; size_t m, mo; // состояние ec_o* ec; word* d; /* [m] личный ключ */ word* e; /* [m] обработанное хэш-значение */ word* k; /* [m] одноразовый ключ */ word* C; /* [2n] вспомогательная точка */ word* r; /* [m] первая (старшая) часть подписи */ word* s; /* [m] вторая часть подписи */ void* stack; // проверить rng if (rng == 0) return ERR_BAD_RNG; // старт code = g12sCreateEc(&ec, params, g12sSign_deep); ERR_CALL_CHECK(code); // размерности order m = W_OF_B(params->l); mo = O_OF_B(params->l); // проверить входные указатели if (!memIsValid(hash, mo) || !memIsValid(privkey, mo) || !memIsValid(sig, 2 * mo)) { g12sCloseEc(ec); return ERR_BAD_INPUT; } // раскладка состояния d = objEnd(ec, word); e = d + m; k = e + m; C = k + m; r = C + 2 * ec->f->n; s = r + m; stack = s + m; // загрузить d wwFrom(d, privkey, mo); if (wwIsZero(d, m) || wwCmp(d, ec->order, m) >= 0) { g12sCloseEc(ec); return ERR_BAD_PRIVKEY; } // e <- hash \mod q memCopy(e, hash, mo); memRev(e, mo); wwFrom(e, e, mo); zzMod(e, e, m, ec->order, m, stack); // e == 0 => e <- 1 if (wwIsZero(e, m)) e[0] = 1; // k <-R {1,2,..., q - 1} gen_k: if (!zzRandNZMod(k, ec->order, m, rng, rng_stack)) { g12sCloseEc(ec); return ERR_BAD_RNG; } // C <- k P if (!ecMulA(C, ec->base, ec, k, m, stack)) { // если params корректны, то этого быть не должно g12sCloseEc(ec); return ERR_BAD_INPUT; } // r <- x_C \mod q qrTo((octet*)C, ecX(C), ec->f, stack); wwFrom(r, C, ec->f->no); zzMod(r, r, ec->f->n, ec->order, m, stack); // r == 0 => повторить генерацию k if (wwIsZero(r, m)) goto gen_k; // s <- (rd + ke) \mod q zzMulMod(k, k, e, ec->order, m, stack); zzMulMod(s, r, d, ec->order, m, stack); zzAddMod(s, s, k, ec->order, m); // выгрузить ЭЦП wwTo(sig, mo, s); wwTo(sig + mo, mo, r); memRev(sig, 2 * mo); // все нормально g12sCloseEc(ec); return ERR_OK; }
void main(void) { uint_least8_t estNumber = 0; #ifdef FAST_ROM_V1p6 uint_least8_t ctrlNumber = 0; #endif // Only used if running from FLASH // Note that the variable FLASH is defined by the project #ifdef FLASH // Copy time critical code and Flash setup code to RAM // The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart // symbols are created by the linker. Refer to the linker files. memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart); #endif // initialize the hardware abstraction layer halHandle = HAL_init(&hal,sizeof(hal)); // check for errors in user parameters USER_checkForErrors(&gUserParams); // store user parameter error in global variable gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams); // do not allow code execution if there is a user parameter error if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError) { for(;;) { gMotorVars.Flag_enableSys = false; } } // initialize the user parameters USER_setParams(&gUserParams); // set the hardware abstraction layer parameters HAL_setParams(halHandle,&gUserParams); // initialize the controller #ifdef FAST_ROM_V1p6 ctrlHandle = CTRL_initCtrl(ctrlNumber, estNumber); //v1p6 format (06xF and 06xM devices) controller_obj = (CTRL_Obj *)ctrlHandle; #else ctrlHandle = CTRL_initCtrl(estNumber,&ctrl,sizeof(ctrl)); //v1p7 format default #endif { CTRL_Version version; // get the version number CTRL_getVersion(ctrlHandle,&version); gMotorVars.CtrlVersion = version; } // set the default controller parameters CTRL_setParams(ctrlHandle,&gUserParams); // Initialize field weakening fwHandle = FW_init(&fw,sizeof(fw)); // Disable field weakening FW_setFlag_enableFw(fwHandle, false); // Clear field weakening counter FW_clearCounter(fwHandle); // Set the number of ISR per field weakening ticks FW_setNumIsrTicksPerFwTick(fwHandle, FW_NUM_ISR_TICKS_PER_CTRL_TICK); // Set the deltas of field weakening FW_setDeltas(fwHandle, FW_INC_DELTA, FW_DEC_DELTA); // Set initial output of field weakening to zero FW_setOutput(fwHandle, _IQ(0.0)); // Set the field weakening controller limits FW_setMinMax(fwHandle,_IQ(USER_MAX_NEGATIVE_ID_REF_CURRENT_A/USER_IQ_FULL_SCALE_CURRENT_A),_IQ(0.0)); // setup faults HAL_setupFaults(halHandle); // initialize the interrupt vector table HAL_initIntVectorTable(halHandle); // enable the ADC interrupts HAL_enableAdcInts(halHandle); // enable global interrupts HAL_enableGlobalInts(halHandle); // enable debug interrupts HAL_enableDebugInt(halHandle); // disable the PWM HAL_disablePwm(halHandle); #ifdef DRV8301_SPI // turn on the DRV8301 if present HAL_enableDrv(halHandle); // initialize the DRV8301 interface HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars); #endif // enable DC bus compensation CTRL_setFlag_enableDcBusComp(ctrlHandle, true); // compute scaling factors for flux and torque calculations gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf(); gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf(); gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf(); gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf(); for(;;) { // Waiting for enable system flag to be set while(!(gMotorVars.Flag_enableSys)); Flag_Latch_softwareUpdate = true; // Enable the Library internal PI. Iq is referenced by the speed PI now CTRL_setFlag_enableSpeedCtrl(ctrlHandle, true); // loop while the enable system flag is true while(gMotorVars.Flag_enableSys) { CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle; // increment counters gCounter_updateGlobals++; // enable/disable the use of motor parameters being loaded from user.h CTRL_setFlag_enableUserMotorParams(ctrlHandle,gMotorVars.Flag_enableUserParams); // enable/disable Rs recalibration during motor startup EST_setFlag_enableRsRecalc(obj->estHandle,gMotorVars.Flag_enableRsRecalc); // enable/disable automatic calculation of bias values CTRL_setFlag_enableOffset(ctrlHandle,gMotorVars.Flag_enableOffsetcalc); if(CTRL_isError(ctrlHandle)) { // set the enable controller flag to false CTRL_setFlag_enableCtrl(ctrlHandle,false); // set the enable system flag to false gMotorVars.Flag_enableSys = false; // disable the PWM HAL_disablePwm(halHandle); } else { // update the controller state bool flag_ctrlStateChanged = CTRL_updateState(ctrlHandle); // enable or disable the control CTRL_setFlag_enableCtrl(ctrlHandle, gMotorVars.Flag_Run_Identify); if(flag_ctrlStateChanged) { CTRL_State_e ctrlState = CTRL_getState(ctrlHandle); if(ctrlState == CTRL_State_OffLine) { // enable the PWM HAL_enablePwm(halHandle); } else if(ctrlState == CTRL_State_OnLine) { if(gMotorVars.Flag_enableOffsetcalc == true) { // update the ADC bias values HAL_updateAdcBias(halHandle); } else { // set the current bias HAL_setBias(halHandle,HAL_SensorType_Current,0,_IQ(I_A_offset)); HAL_setBias(halHandle,HAL_SensorType_Current,1,_IQ(I_B_offset)); HAL_setBias(halHandle,HAL_SensorType_Current,2,_IQ(I_C_offset)); // set the voltage bias HAL_setBias(halHandle,HAL_SensorType_Voltage,0,_IQ(V_A_offset)); HAL_setBias(halHandle,HAL_SensorType_Voltage,1,_IQ(V_B_offset)); HAL_setBias(halHandle,HAL_SensorType_Voltage,2,_IQ(V_C_offset)); } // Return the bias value for currents gMotorVars.I_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Current,0); gMotorVars.I_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Current,1); gMotorVars.I_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Current,2); // Return the bias value for voltages gMotorVars.V_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Voltage,0); gMotorVars.V_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Voltage,1); gMotorVars.V_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Voltage,2); // enable the PWM HAL_enablePwm(halHandle); } else if(ctrlState == CTRL_State_Idle) { // disable the PWM HAL_disablePwm(halHandle); gMotorVars.Flag_Run_Identify = false; } if((CTRL_getFlag_enableUserMotorParams(ctrlHandle) == true) && (ctrlState > CTRL_State_Idle) && (gMotorVars.CtrlVersion.minor == 6)) { // call this function to fix 1p6 USER_softwareUpdate1p6(ctrlHandle); } } } if(EST_isMotorIdentified(obj->estHandle)) { _iq Is_Max_squared_pu = _IQ((USER_MOTOR_MAX_CURRENT*USER_MOTOR_MAX_CURRENT)/ \ (USER_IQ_FULL_SCALE_CURRENT_A*USER_IQ_FULL_SCALE_CURRENT_A)); _iq Id_squared_pu = _IQmpy(CTRL_getId_ref_pu(ctrlHandle),CTRL_getId_ref_pu(ctrlHandle)); // Take into consideration that Iq^2+Id^2 = Is^2 Iq_Max_pu = _IQsqrt(Is_Max_squared_pu-Id_squared_pu); //Set new max trajectory CTRL_setSpdMax(ctrlHandle, Iq_Max_pu); // set the current ramp EST_setMaxCurrentSlope_pu(obj->estHandle,gMaxCurrentSlope); gMotorVars.Flag_MotorIdentified = true; // set the speed reference CTRL_setSpd_ref_krpm(ctrlHandle,gMotorVars.SpeedRef_krpm); // set the speed acceleration CTRL_setMaxAccel_pu(ctrlHandle,_IQmpy(MAX_ACCEL_KRPMPS_SF,gMotorVars.MaxAccel_krpmps)); if(Flag_Latch_softwareUpdate) { Flag_Latch_softwareUpdate = false; USER_calcPIgains(ctrlHandle); // initialize the watch window kp and ki current values with pre-calculated values gMotorVars.Kp_Idq = CTRL_getKp(ctrlHandle,CTRL_Type_PID_Id); gMotorVars.Ki_Idq = CTRL_getKi(ctrlHandle,CTRL_Type_PID_Id); } } else { Flag_Latch_softwareUpdate = true; // initialize the watch window kp and ki values with pre-calculated values gMotorVars.Kp_spd = CTRL_getKp(ctrlHandle,CTRL_Type_PID_spd); gMotorVars.Ki_spd = CTRL_getKi(ctrlHandle,CTRL_Type_PID_spd); // the estimator sets the maximum current slope during identification gMaxCurrentSlope = EST_getMaxCurrentSlope_pu(obj->estHandle); } // when appropriate, update the global variables if(gCounter_updateGlobals >= NUM_MAIN_TICKS_FOR_GLOBAL_VARIABLE_UPDATE) { // reset the counter gCounter_updateGlobals = 0; updateGlobalVariables_motor(ctrlHandle); } // update Kp and Ki gains updateKpKiGains(ctrlHandle); // set field weakening enable flag depending on user's input FW_setFlag_enableFw(fwHandle,gMotorVars.Flag_enableFieldWeakening); // enable/disable the forced angle EST_setFlag_enableForceAngle(obj->estHandle,gMotorVars.Flag_enableForceAngle); // enable or disable power warp CTRL_setFlag_enablePowerWarp(ctrlHandle,gMotorVars.Flag_enablePowerWarp); #ifdef DRV8301_SPI HAL_writeDrvData(halHandle,&gDrvSpi8301Vars); HAL_readDrvData(halHandle,&gDrvSpi8301Vars); #endif } // end of while(gFlag_enableSys) loop // disable the PWM HAL_disablePwm(halHandle); // set the default controller parameters (Reset the control to re-identify the motor) CTRL_setParams(ctrlHandle,&gUserParams); gMotorVars.Flag_Run_Identify = false; } // end of for(;;) loop } // end of main() function
bool_t beltTest() { octet buf[48]; octet buf1[48]; octet mac[8]; octet mac1[8]; octet hash[32]; octet hash1[32]; u32 key[8]; octet level[12]; octet state[1024]; // создать стек ASSERT(sizeof(state) >= beltECB_keep()); ASSERT(sizeof(state) >= beltCBC_keep()); ASSERT(sizeof(state) >= beltCFB_keep()); ASSERT(sizeof(state) >= beltCTR_keep()); ASSERT(sizeof(state) >= beltMAC_keep()); ASSERT(sizeof(state) >= beltDWP_keep()); ASSERT(sizeof(state) >= beltKWP_keep()); ASSERT(sizeof(state) >= beltHash_keep()); ASSERT(sizeof(state) >= beltKRP_keep()); ASSERT(sizeof(state) >= beltHMAC_keep()); // тест A.1 memCopy(buf, beltH(), 16); beltKeyExpand2(key, beltH() + 128, 32); beltBlockEncr(buf, key); if (!hexEq(buf, "69CCA1C93557C9E3D66BC3E0FA88FA6E")) return FALSE; // тест A.4 memCopy(buf, beltH() + 64, 16); beltKeyExpand2(key, beltH() + 128 + 32, 32); beltBlockDecr(buf, key); if (!hexEq(buf, "0DC5300600CAB840B38448E5E993F421")) return FALSE; // тест A.6 memCopy(buf, beltH(), 48); beltECBStart(state, beltH() + 128, 32); beltECBStepE(buf, 32, state); beltECBStepE(buf + 32, 48 - 32, state); if (!hexEq(buf, "69CCA1C93557C9E3D66BC3E0FA88FA6E" "5F23102EF109710775017F73806DA9DC" "46FB2ED2CE771F26DCB5E5D1569F9AB0")) return FALSE; beltECBEncr(buf1, beltH(), 48, beltH() + 128, 32); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.7 memCopy(buf, beltH(), 47); beltECBStart(state, beltH() + 128, 32); beltECBStepE(buf, 16, state); beltECBStepE(buf + 16, 47 - 16, state); if (!hexEq(buf, "69CCA1C93557C9E3D66BC3E0FA88FA" "6E36F00CFED6D1CA1498C12798F4BE" "B2075F23102EF109710775017F7380" "6DA9")) return FALSE; beltECBEncr(buf1, beltH(), 47, beltH() + 128, 32); if (!memEq(buf, buf1, 47)) return FALSE; // тест A.8 memCopy(buf, beltH() + 64, 48); beltECBStart(state, beltH() + 128 + 32, 32); beltECBStepD(buf, 16, state); beltECBStepD(buf + 16, 48 - 16, state); if (!hexEq(buf, "0DC5300600CAB840B38448E5E993F421" "E55A239F2AB5C5D5FDB6E81B40938E2A" "54120CA3E6E19C7AD750FC3531DAEAB7")) return FALSE; beltECBDecr(buf1, beltH() + 64, 48, beltH() + 128 + 32, 32); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.9 memCopy(buf, beltH() + 64, 36); beltECBStart(state, beltH() + 128 + 32, 32); beltECBStepD(buf, 36, state); if (!hexEq(buf, "0DC5300600CAB840B38448E5E993F421" "5780A6E2B69EAFBB258726D7B6718523" "E55A239F")) return FALSE; beltECBDecr(buf1, beltH() + 64, 36, beltH() + 128 + 32, 32); if (!memEq(buf, buf1, 36)) return FALSE; // тест A.10 memCopy(buf, beltH(), 48); beltCBCStart(state, beltH() + 128, 32, beltH() + 192); beltCBCStepE(buf, 32, state); beltCBCStepE(buf + 32, 48 - 32, state); if (!hexEq(buf, "10116EFAE6AD58EE14852E11DA1B8A74" "5CF2480E8D03F1C19492E53ED3A70F60" "657C1EE8C0E0AE5B58388BF8A68E3309")) return FALSE; beltCBCEncr(buf1, beltH(), 48, beltH() + 128, 32, beltH() + 192); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.11 memCopy(buf, beltH(), 36); beltCBCStart(state, beltH() + 128, 32, beltH() + 192); beltCBCStepE(buf, 16, state); beltCBCStepE(buf + 16, 36 - 16, state); if (!hexEq(buf, "10116EFAE6AD58EE14852E11DA1B8A74" "6A9BBADCAF73F968F875DEDC0A44F6B1" "5CF2480E")) return FALSE; beltCBCEncr(buf1, beltH(), 36, beltH() + 128, 32, beltH() + 192); if (!memEq(buf, buf1, 36)) return FALSE; // тест A.12 memCopy(buf, beltH() + 64, 48); beltCBCStart(state, beltH() + 128 + 32, 32, beltH() + 192 + 16); beltCBCStepD(buf, 16, state); beltCBCStepD(buf + 16, 48 - 16, state); if (!hexEq(buf, "730894D6158E17CC1600185A8F411CAB" "0471FF85C83792398D8924EBD57D03DB" "95B97A9B7907E4B020960455E46176F8")) return FALSE; beltCBCDecr(buf1, beltH() + 64, 48, beltH() + 128 + 32, 32, beltH() + 192 + 16); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.13 memCopy(buf, beltH() + 64, 36); beltCBCStart(state, beltH() + 128 + 32, 32, beltH() + 192 + 16); beltCBCStepD(buf, 16, state); beltCBCStepD(buf + 16, 36 - 16, state); if (!hexEq(buf, "730894D6158E17CC1600185A8F411CAB" "B6AB7AF8541CF85755B8EA27239F08D2" "166646E4")) return FALSE; beltCBCDecr(buf1, beltH() + 64, 36, beltH() + 128 + 32, 32, beltH() + 192 + 16); if (!memEq(buf, buf1, 36)) return FALSE; // тест A.14 memCopy(buf, beltH(), 48); beltCFBStart(state, beltH() + 128, 32, beltH() + 192); beltCFBStepE(buf, 16, state); beltCFBStepE(buf + 16, 3, state); beltCFBStepE(buf + 16 + 3, 48 - 16 - 3, state); if (!hexEq(buf, "C31E490A90EFA374626CC99E4B7B8540" "A6E48685464A5A06849C9CA769A1B0AE" "55C2CC5939303EC832DD2FE16C8E5A1B")) return FALSE; beltCFBEncr(buf1, beltH(), 48, beltH() + 128, 32, beltH() + 192); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.15 memCopy(buf, beltH() + 64, 48); beltCFBStart(state, beltH() + 128 + 32, 32, beltH() + 192 + 16); beltCFBStepD(buf, 15, state); beltCFBStepD(buf + 15, 7, state); beltCFBStepD(buf + 15 + 7, 48 - 15 - 7, state); if (!hexEq(buf, "FA9D107A86F375EE65CD1DB881224BD0" "16AFF814938ED39B3361ABB0BF0851B6" "52244EB06842DD4C94AA4500774E40BB")) return FALSE; beltCFBDecr(buf1, beltH() + 64, 48, beltH() + 128 + 32, 32, beltH() + 192 + 16); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.16 memCopy(buf, beltH(), 48); beltCTRStart(state, beltH() + 128, 32, beltH() + 192); beltCTRStepE(buf, 15, state); beltCTRStepE(buf + 15, 7, state); beltCTRStepE(buf + 15 + 7, 48 - 15 - 7, state); if (!hexEq(buf, "52C9AF96FF50F64435FC43DEF56BD797" "D5B5B1FF79FB41257AB9CDF6E63E81F8" "F00341473EAE409833622DE05213773A")) return FALSE; beltCTR(buf1, beltH(), 48, beltH() + 128, 32, beltH() + 192); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.17 beltMACStart(state, beltH() + 128, 32); beltMACStepA(beltH(), 13, state); hexTo(buf, "7260DA60138F96C9"); if (!beltMACStepV(buf, state)) return FALSE; beltMAC(buf1, beltH(), 13, beltH() + 128, 32); if (!memEq(buf, buf1, 8)) return FALSE; // тест A.18 [+ инкрементальность] beltMACStart(state, beltH() + 128, 32); beltMACStepA(beltH(), 27, state); beltMACStepG(buf, state); beltMACStepA(beltH() + 27, 48 - 27, state); beltMACStepG2(buf, 4, state); hexTo(buf, "2DAB59771B4B16D0"); if (!beltMACStepV(buf, state) || !beltMACStepV2(buf, 3, state)) return FALSE; beltMAC(buf1, beltH(), 48, beltH() + 128, 32); if (!memEq(buf, buf1, 8)) return FALSE; // тест A.20 beltDWPStart(state, beltH() + 128, 32, beltH() + 192); memCopy(buf, beltH(), 16); beltDWPStepE(buf, 16, state); beltDWPStepI(beltH() + 16, 32, state); beltDWPStepA(buf, 16, state); beltDWPStepG(mac, state); if (!hexEq(buf, "52C9AF96FF50F64435FC43DEF56BD797")) return FALSE; if (!hexEq(mac, "3B2E0AEB2B91854B")) return FALSE; beltDWPWrap(buf1, mac1, beltH(), 16, beltH() + 16, 32, beltH() + 128, 32, beltH() + 192); if (!memEq(buf, buf1, 16) || !memEq(mac, mac1, 8)) return FALSE; // тест A.21 beltDWPStart(state, beltH() + 128 + 32, 32, beltH() + 192 + 16); memCopy(buf, beltH() + 64, 16); beltDWPStepI(beltH() + 64 + 16, 32, state); beltDWPStepA(buf, 16, state); beltDWPStepD(buf, 16, state); beltDWPStepG(mac, state); if (!hexEq(buf, "DF181ED008A20F43DCBBB93650DAD34B")) return FALSE; if (!hexEq(mac, "6A2C2C94C4150DC0")) return FALSE; if (beltDWPUnwrap(buf1, beltH() + 64, 16, beltH() + 64 + 16, 32, mac, beltH() + 128 + 32, 32, beltH() + 192 + 16) != ERR_OK || !memEq(buf, buf1, 16)) return FALSE; // тест A.22 beltKWPStart(state, beltH() + 128, 32); memCopy(buf, beltH(), 32); memCopy(buf + 32, beltH() + 32, 16); beltKWPStepE(buf, 48, state); if (!hexEq(buf, "49A38EE108D6C742E52B774F00A6EF98" "B106CBD13EA4FB0680323051BC04DF76" "E487B055C69BCF541176169F1DC9F6C8")) return FALSE; beltKWPWrap(buf1, beltH(), 32, beltH() + 32, beltH() + 128, 32); if (!memEq(buf, buf1, 48)) return FALSE; // тест A.23 beltKWPStart(state, beltH() + 128 + 32, 32); memCopy(buf, beltH() + 64, 48); beltKWPStepD(buf, 48, state); if (!hexEq(buf, "92632EE0C21AD9E09A39343E5C07DAA4" "889B03F2E6847EB152EC99F7A4D9F154")) return FALSE; if (!hexEq(buf + 32, "B5EF68D8E4A39E567153DE13D72254EE")) return FALSE; if (beltKWPUnwrap(buf1, beltH() + 64, 48, (octet*)buf + 32, beltH() + 128 + 32, 32) != ERR_OK || !memEq(buf, buf1, 32)) return FALSE; // тест A.24 beltHashStart(state); beltHashStepH(beltH(), 13, state); beltHashStepG(hash, state); if (!hexEq(hash, "ABEF9725D4C5A83597A367D14494CC25" "42F20F659DDFECC961A3EC550CBA8C75")) return FALSE; beltHash(hash1, beltH(), 13); if (!memEq(hash, hash1, 32)) return FALSE; // тест A.25 beltHashStart(state); beltHashStepH(beltH(), 32, state); hexTo(hash, "749E4C3653AECE5E48DB4761227742EB" "6DBE13F4A80F7BEFF1A9CF8D10EE7786"); if (!beltHashStepV(hash, state) || !beltHashStepV2(hash, 13, state)) return FALSE; beltHash(hash1, beltH(), 32); if (!memEq(hash, hash1, 32)) return FALSE; // тест A.26 [+ инкрементальность] beltHashStart(state); beltHashStepH(beltH(), 11, state); beltHashStepG2(hash, 32, state); beltHashStepH(beltH() + 11, 48 - 11, state); hexTo(hash, "9D02EE446FB6A29FE5C982D4B13AF9D3" "E90861BC4CEF27CF306BFB0B174A154A"); if (!beltHashStepV2(hash, 32, state)) return FALSE; beltHash(hash1, beltH(), 48); if (!memEq(hash, hash1, 32)) return FALSE; // тест A.29 memSetZero(level, 12); level[0] = 1; beltKRPStart(state, beltH() + 128, 32, level); beltKRPStepG(buf, 16, beltH() + 32, state); if (!hexEq(buf, "6BBBC2336670D31AB83DAA90D52C0541")) return FALSE; beltKRP(buf1, 16, beltH() + 128, 32, level, beltH() + 32); if (!memEq(buf, buf1, 16)) return FALSE; // тест A.30 beltKRPStepG(buf, 24, beltH() + 32, state); if (!hexEq(buf, "9A2532A18CBAF145398D5A95FEEA6C82" "5B9C197156A00275")) return FALSE; beltKRP(buf1, 24, beltH() + 128, 32, level, beltH() + 32); if (!memEq(buf, buf1, 24)) return FALSE; // тест A.31 beltKRPStepG(buf, 32, beltH() + 32, state); if (!hexEq(buf, "76E166E6AB21256B6739397B672B8796" "14B81CF05955FC3AB09343A745C48F77")) return FALSE; beltKRP(buf1, 32, beltH() + 128, 32, level, beltH() + 32); if (!memEq(buf, buf1, 32)) return FALSE; // тест Б.1-1 beltHMACStart(state, beltH() + 128, 29); beltHMACStepA(beltH() + 128 + 64, 32, state); beltHMACStepG(hash, state); if (!hexEq(hash, "D4828E6312B08BB83C9FA6535A463554" "9E411FD11C0D8289359A1130E930676B")) return FALSE; beltHMAC(hash1, beltH() + 128 + 64, 32, beltH() + 128, 29); if (!memEq(hash, hash1, 32)) return FALSE; // тест Б.1-2 beltHMACStart(state, beltH() + 128, 32); beltHMACStepA(beltH() + 128 + 64, 32, state); hexTo(hash, "41FFE8645AEC0612E952D2CDF8DD508F" "3E4A1D9B53F6A1DB293B19FE76B1879F"); if (!beltHMACStepV(hash, state)) return FALSE; beltHMAC(hash1, beltH() + 128 + 64, 32, beltH() + 128, 32); if (!memEq(hash, hash1, 32)) return FALSE; // тест Б.1-3 [+ икрементальность] beltHMACStart(state, beltH() + 128, 42); beltHMACStepA(beltH() + 128 + 64, 17, state); beltHMACStepG(hash, state); beltHMACStepG2(hash, 17, state); beltHMACStepA(beltH() + 128 + 64 + 17, 32 - 17, state); hexTo(hash, "7D01B84D2315C332277B3653D7EC6470" "7EBA7CDFF7FF70077B1DECBD68F2A144"); if (!beltHMACStepV(hash, state) || !beltHMACStepV2(hash, 23, state)) return FALSE; beltHMAC(hash1, beltH() + 128 + 64, 32, beltH() + 128, 42); if (!memEq(hash, hash1, 32)) return FALSE; // все нормально return TRUE; }
real BFGSOptimization() { printf("Before init sites(point_num=%d).\n", point_num); // Use L-BFGS method to compute new sites const real epsg = EPSG; const real epsf = EPSF; const real epsx = EPSX; const int maxits = MAXITS; stpscal = 2.0f; //Set for different problems! int info; total_time = 0; total_time_func = 0; real* x; int* nbd; real* l; real* u; memAlloc<real>(&x, point_num * 2); memAlloc<int>(&nbd, point_num * 2); memAlloc<real>(&l, point_num * 2); memAlloc<real>(&u, point_num * 2); memAllocHost<real>(&f_tb_host, &f_tb_dev, 1); // Kernel이 처리할 수 있도록 site_list를 매핑하는 site_list_dev를 전달. // site_list는 InitializeSites()에서 지정 // Device에 할당된 x에 site_list가 복사 InitSites(x, (float*)site_list_dev, sizeof(SiteType) / sizeof(float), nbd, l, u, point_num * 2, screenwidth, screenheight); printf("Start optimization..."); get_timestamp(start_time); int m = 8; if (point_num * 2 < m) m = point_num * 2; // 내부적으로 funcgrad()를 호출 lbfgsbminimize(point_num*2, m, x, epsg, epsf, epsx, maxits, nbd, l, u, info); //printf("Ending code:%d\n", info); get_timestamp(end_time); elapsed_time = (end_time-start_time); total_time += elapsed_time; printf("Done.\n JFA Time: %lf\tBFGS Time: %lf\tTotal time: %lf\t", total_time_func, elapsed_time - total_time_func, elapsed_time); bReCompute = false; real f = DrawVoronoi(x); // Device에 저장된 x가 실제 이동된 site 정보인 듯 // 이를 Host로 복사한 후, site_list에 할당 real* x_host = new real[point_num * 2]; memCopy(x_host, x, point_num * 2 * sizeof(real), cudaMemcpyDeviceToHost); FILE* fp = fopen("Result.txt", "w"); for(int i = 0; i < point_num; i++) { real ix = x_host[i * 2]; real iy = x_host[i * 2 + 1]; real ox = (ix + 1) * (screenwidth - 1) / 2.0 + 1.0; real oy = (iy + 1) * (screenheight - 1) / 2.0 + 1.0; if(1.0f > ox || ox > screenwidth - 1) continue; if(1.0f > oy || oy > screenheight - 1) continue; fprintf(fp, "%f, %f\n", ox, oy); } fclose(fp); delete[] x_host; memFreeHost(f_tb_host); memFree(x); memFree(nbd); memFree(l); memFree(u); return f; }