static DWORD vl(__CMD_PARA_OBJ* pCmdObj) { #ifdef __CFG_SYS_DDF HANDLE hFile = NULL; CHAR Buffer[128]; DWORD dwWritten = 0; CHAR FullName[MAX_FILE_NAME_LEN]; INT dwCounter = 6; if(pCmdObj->byParameterNum < 2) { PrintLine(" Please specify the file name to be displayed."); goto __TERMINAL; } strcpy(FullName,FsGlobalData.CurrentDir); strcat(FullName,pCmdObj->Parameter[1]); ToCapital(FullName); //Try to open the target file. hFile = IOManager.CreateFile((__COMMON_OBJECT*)&IOManager, FullName, FILE_ACCESS_WRITE | FILE_OPEN_ALWAYS, 0, NULL); if(NULL == hFile) { PrintLine(" Please specify a valid and present file name."); goto __TERMINAL; } while(dwCounter!= 0) { _hx_sprintf(Buffer,"Wish it can work,this line number is %d.\r\n",dwCounter); if(!IOManager.WriteFile((__COMMON_OBJECT*)&IOManager, hFile, strlen(Buffer), Buffer, &dwWritten)) { _hx_sprintf(Buffer," Can not write to file,The line number is %d.",dwCounter); PrintLine(Buffer); goto __TERMINAL; } dwCounter --; } __TERMINAL: if(hFile) { IOManager.CloseFile((__COMMON_OBJECT*)&IOManager, hFile); } return SHELL_CMD_PARSER_SUCCESS;; #else return FS_CMD_FAILED; #endif }
// //This routine is the default interrupt handler. //If no entity(such as device driver) install an interrupt handler,this handler //will be called to handle the appropriate interrupt. //It will only print out a message indicating the interrupt's number and return. // static VOID DefaultIntHandler(LPVOID lpEsp,UCHAR ucVector) { CHAR strBuffer[64]; static DWORD dwTotalNum = 0; dwTotalNum ++; //Record this unhandled exception or interrupt. PrintLine(" Unhandled interrupt."); //Print out this message. _hx_sprintf(strBuffer," Interrupt number = %d.",ucVector); PrintLine(strBuffer); _hx_sprintf(strBuffer," Total unhandled interrupt times = %d.",dwTotalNum); PrintLine(strBuffer); return; }
struct lbs_private *lbs_add_card(void *card) { struct lbs_private *priv =&gmarvell_priv; lbs_deb_enter("enter lbs_add_card!\n"); memset(priv,0,sizeof(struct lbs_private)); if (lbs_init_adapter(priv)) {//Initialize priv structure. lbs_pr_err("failed to initialize adapter structure.\n"); goto err_init_adapter; } priv->card = card;//if_sdio_card priv->mesh_open = 0; priv->infra_open = 0; _hx_sprintf((char *)priv->mesh_ssid,"mesh"); priv->mesh_ssid_len = 4; priv->wol_criteria = 0xffffffff; priv->wol_gpio = 0xff; goto done; err_init_adapter: done: lbs_deb_leave_args("leave lbs_add_card",0); return priv; }
static DWORD SysNameHandler(__CMD_PARA_OBJ* pCmdParaObj) { //__CMD_PARA_OBJ* pCmdObj = NULL; //pCmdParaObj = FormParameterObj(pszSysName); if(NULL == pCmdParaObj) { PrintLine("Not enough system resource to interpret the command."); goto __TERMINAL; } if((0 == pCmdParaObj->byParameterNum) || (0 == pCmdParaObj->Parameter[0][0])) { PrintLine("Invalid command parameter."); goto __TERMINAL; } if(StrLen(pCmdParaObj->Parameter[0]) >= MAX_HOSTNAME_LEN) { PrintLine("System name must not exceed 16 bytes."); goto __TERMINAL; } //SaveSysName(pCmdParaObj->Parameter[0]); //StrCpy(pCmdObj->Parameter[0],&s_szPrompt[0]); _hx_sprintf(s_szPrompt,"[%s]",pCmdParaObj->Parameter[0]); if(StrLen(s_szPrompt) <= 0) { StrCpy(DEF_PROMPT_STR,&s_szPrompt[0]); } __TERMINAL: return SHELL_CMD_PARSER_SUCCESS; }
//A helper routine used to dumpout a network interface. static void ShowIf(struct netif* pIf) { char buff[128]; //Print out all information about this interface. PrintLine(" --------------------------------------"); _hx_sprintf(buff," Inetface name : %c%c",pIf->name[0],pIf->name[1]); PrintLine(buff); _hx_sprintf(buff," IPv4 address : %s",inet_ntoa(pIf->ip_addr)); PrintLine(buff); _hx_sprintf(buff," IPv4 mask : %s",inet_ntoa(pIf->netmask)); PrintLine(buff); _hx_sprintf(buff," IPv4 gateway : %s",inet_ntoa(pIf->gw)); PrintLine(buff); _hx_sprintf(buff," Interface MTU : %d",pIf->mtu); PrintLine(buff); }
//A local helper routine to print the directory list,used by dir command. static VOID PrintDir(FS_FIND_DATA* pFindData) { CHAR Buffer[MAX_FILE_NAME_LEN] = {0}; if(!pFindData->bGetLongName) { _hx_sprintf(Buffer,"%13s %16d %4s", pFindData->cAlternateFileName, pFindData->nFileSizeLow, (pFindData->dwFileAttribute & FILE_ATTR_DIRECTORY) ? "DIR" : "FILE"); } else { _hx_sprintf(Buffer,"%s",strlen(pFindData->cFileName)?pFindData->cFileName:pFindData->cAlternateFileName); } PrintLine(Buffer); }
static DWORD use(__CMD_PARA_OBJ* pCmdObj) { CHAR Info[4]; int i; BOOL bMatched = FALSE; CHAR* strError = " Please specify a valid file system identifier."; if(1 == pCmdObj->byParameterNum) //Without any parameter. { Info[0] = FsGlobalData.CurrentFs; Info[1] = ':'; Info[2] = 0; _hx_sprintf(Buffer," Current file system is: %s",Info); PrintLine(Buffer); goto __TERMINAL; } //Parse the user input. if(strlen(pCmdObj->Parameter[1]) > 2) //File system identifier can not exceed 2 characters. { PrintLine(strError); goto __TERMINAL; } Info[0] = pCmdObj->Parameter[1][0]; Info[1] = pCmdObj->Parameter[1][1]; Info[2] = 0; if(Info[1] != ':') { PrintLine(strError); goto __TERMINAL; } for(i = 0;i < FILE_SYSTEM_NUM;i ++) { if(FsGlobalData.FsArray[i].FileSystemIdentifier == Info[0]) //FS is in system now. { bMatched = TRUE; break; } } if(!bMatched) //The specified file system identifier is not in system now. { PrintLine(" The specified file system is not present now."); goto __TERMINAL; } //Valid file system,change current information. FsGlobalData.CurrentDir[0] = Info[0]; FsGlobalData.CurrentDir[1] = Info[1]; FsGlobalData.CurrentDir[2] = '\\'; FsGlobalData.CurrentDir[3] = 0; FsGlobalData.CurrentFs = Info[0]; __TERMINAL: return SHELL_CMD_PARSER_SUCCESS;; }
static DWORD cd(__CMD_PARA_OBJ* pCmdObj) { #ifdef __CFG_SYS_DDF CHAR NewPath[MAX_FILE_NAME_LEN]; CHAR* pCurrPos = NULL; DWORD dwFileAttr = 0; if(1 == pCmdObj->byParameterNum) //Print out the current directory. { _hx_sprintf(Buffer," Current directory is: %s",FsGlobalData.CurrentDir); PrintLine(Buffer); goto __TERMINAL; } if(0 == strcmp(".",pCmdObj->Parameter[1])) //Current directory. { goto __TERMINAL; } if(0 == strcmp("..",pCmdObj->Parameter[1])) //Parent directory. { PrintLine(" Can not supported yet.:-)"); goto __TERMINAL; } if(0 == strcmp("\\",pCmdObj->Parameter[1])) //Root directory is specified. { FsGlobalData.CurrentDir[0] = FsGlobalData.CurrentFs; FsGlobalData.CurrentDir[1] = ':'; FsGlobalData.CurrentDir[2] = '\\'; FsGlobalData.CurrentDir[3] = 0; goto __TERMINAL; } //Want to enter a new directory. strcpy(NewPath,FsGlobalData.CurrentDir); strcat(NewPath,pCmdObj->Parameter[1]); //Form the new path. strcat(NewPath,"\\"); //Specify a slash. ToCapital(NewPath); //Convert to capital. if((dwFileAttr = IOManager.GetFileAttributes((__COMMON_OBJECT*)&IOManager, NewPath)) == 0) //Use GetFileAttributes to verify the validity of new directory. { PrintLine(" Bad target directory name."); goto __TERMINAL; } if((dwFileAttr & FILE_ATTR_DIRECTORY) == 0) //Is not a directory,is a regular file. { PrintLine(" Please specify a DIRECTORY name,not a file name."); goto __TERMINAL; } //Validation is ok,set the new path as current directory. strcpy(FsGlobalData.CurrentDir,NewPath); __TERMINAL: return SHELL_CMD_PARSER_SUCCESS;; #else return FS_CMD_FAILED; #endif }
int snprintf(char * buf, size_t size, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); //i=vsnprintf(buf,size,fmt,args); i = _hx_sprintf(buf,fmt,args); va_end(args); return i; }
/* * A helper routine to register a new initialized R8152 device into * HelloX Kernel. */ static int Register_R8152(struct usb_device *dev, struct ueth_data *ss) { __ETHERNET_INTERFACE* pEthInt = NULL; unsigned char mac_addr[ETH_MAC_LEN]; char eth_name[MAX_ETH_NAME_LEN + 1]; int err = 0; /* Retrieve hardware address of the device. */ err = r8152_read_mac(ss->dev_priv, mac_addr); if (err < 0) { _hx_printf("%s: failed to retrieve MAC addr,err = %d.\r\n", __func__, err); return 0; } /* Construct the default ethernet interface name. */ _hx_sprintf(eth_name, "%s%d", R8152_NAME_BASE, ss->ef_idx); /* Add R8152 corresponding Ethernet interface. */ pEthInt = EthernetManager.AddEthernetInterface( eth_name, mac_addr, ss, __r8152_init, __r8152_send, NULL, //Receive operation is put into receiving thread,since it may lead long time blocking. __r8152_control); if (NULL == pEthInt) { _hx_printf("Failed to add [%s] to network.\r\n", eth_name); return 0; } //Save into USB ethernet private data. ss->thisIf = pEthInt; _hx_printf("Add eth_if[name = %s,mac = %.2X-%.2X-%.2X-%.2X-%.2X-%.2X] successfully.\r\n", eth_name, mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); return 1; }
static void Logcat(__DEBUG_MANAGER *pThis, char *buf, int len) { __DEBUG_MANAGER *pDebugManager = pThis; __LOG_MESSAGE *pMsg = NULL; __LOG_MESSAGE *p = NULL; int Result = -1; pMsg = (__LOG_MESSAGE *)KMemAlloc(sizeof(__LOG_MESSAGE),KMEM_SIZE_TYPE_ANY); // // Get the authority to visit the kernel bufferqueue // Result = DebugManager.pMutexForKRNLBufferQueue->WaitForThisObject((__COMMON_OBJECT*)DebugManager.pMutexForKRNLBufferQueue); if (Result == OBJECT_WAIT_RESOURCE) { p = pDebugManager->pKRNLBufferQueue->Dequeue(pDebugManager->pKRNLBufferQueue); pDebugManager->pMutexForKRNLBufferQueue->ReleaseMutex((__COMMON_OBJECT*)DebugManager.pMutexForKRNLBufferQueue); } if(p == NULL) { // // Get the authority to visit the user bufferqueue // Result = DebugManager.pMutexForBufferQueue->WaitForThisObject((__COMMON_OBJECT*)DebugManager.pMutexForBufferQueue); if (Result == OBJECT_WAIT_RESOURCE) { p = pDebugManager->pBufferQueue->Dequeue(pDebugManager->pBufferQueue); pDebugManager->pMutexForBufferQueue->ReleaseMutex((__COMMON_OBJECT*)DebugManager.pMutexForBufferQueue); } } if(p != NULL) { pMsg->pid = p->pid; pMsg->tid = p->tid; pMsg->time = p->time; StrCpy(p->tag, pMsg->tag); StrCpy(p->name, pMsg->name); StrCpy(p->msg, pMsg->msg); _hx_sprintf(buf, "tag:%s name:%s time:%d pid:%d tid:%d msg:%s", pMsg->tag, pMsg->name, pMsg->time, pMsg->pid, pMsg->tid, pMsg->msg); } KMemFree(pMsg, KMEM_SIZE_TYPE_ANY, 0); return; }
//Default handler of Exception. static VOID DefaultExcepHandler(LPVOID pESP,UCHAR ucVector) { CHAR Buff[64]; static DWORD totalExcepNum = 0; #ifdef __I386__ DWORD excepAddr = 0; #endif __KERNEL_THREAD_OBJECT* pKernelThread = KernelThreadManager.lpCurrentKernelThread; //Switch to text mode,because the exception maybe caused in GUI mode. #ifdef __I386__ SwitchToText(); #endif _hx_sprintf(Buff," Unknown exception occured: excep number = %d",ucVector); PrintLine(Buff); totalExcepNum ++; if(totalExcepNum >= 1) //Too many exception,maybe in deadlock,so halt the system. { PrintLine(" Fatal error : total unhandled exception number reached maximal value!"); PrintLine(" Please power off the system and reboot it."); if(pKernelThread) { _hx_sprintf(Buff," Exception thread ID = %d.",pKernelThread->dwThreadID); PrintLine(Buff); _hx_sprintf(Buff," Exception thread name : %s.",pKernelThread->KernelThreadName); PrintLine(Buff); //Get the exception address try to access. #ifdef __I386__ __asm{ push eax mov eax,cr2 mov excepAddr,eax pop eax } _hx_sprintf(Buff," Exception memaddr = 0x%X.",excepAddr); PrintLine(Buff); _hx_sprintf(Buff," EIP = 0x%X.",*((DWORD*)pESP + 8)); PrintLine(Buff); _hx_sprintf(Buff," CS = 0x%X.",*((DWORD*)pESP + 9)); PrintLine(Buff); _hx_sprintf(Buff," EFlags = 0x%X.",*((DWORD*)pESP + 10)); PrintLine(Buff); #else #endif } while(1); //Make a dead loop. } return; }
/* Parser core - when encountering text, process appropriately. */ static const char *parse_value(cJSON *item,const char *value) { if (!value) return 0; /* Fail on null. */ if (!mystrncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } if (!mystrncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } if (!mystrncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } if (*value=='\"') { return parse_string(item,value); } if (*value=='-' || (*value>='0' && *value<='9')) { _hx_sprintf("parse_number call"); return parse_number(item,value); } if (*value=='[') { return parse_array(item,value); } if (*value=='{') { return parse_object(item,value); } ep=value;return 0; /* failure. */ }
void CheckESP(__KERNEL_THREAD_OBJECT* pKernelThread,LPVOID pESP) { char buff[64]; if((DWORD)pKernelThread->lpInitStackPointer <= (DWORD)pESP) { _hx_sprintf(buff,"Fault error: InitStackPtr = %X,ESP = %X.\r\n",(DWORD)pKernelThread->lpInitStackPointer, (DWORD)pESP); SER_PutString(buff); while(TRUE); } if((DWORD)pKernelThread->lpInitStackPointer - pKernelThread->dwStackSize >= (DWORD)pESP) { SER_PutString(" CHECK ESP ERROR,bottom overflow.\r\n"); while(TRUE); } if((DWORD)pKernelThread->lpInitStackPointer - (DWORD)pESP >= (3 * DEFAULT_STACK_SIZE) / 4) { SER_PutString(" CHECK ESP WARNING:thread has less 1/4 bytes stack.\r\n"); } }
/* Render the cstring provided to an escaped version that can be printed. */ static char *print_string_ptr(const char *str) { const char *ptr;char *ptr2,*out;int len=0;unsigned char token; if (!str) return cJSON_strdup(""); ptr=str; while ((token=*ptr) && ++len) { if (mystrchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++; } out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;ptr=str; *ptr2++='\"'; while (*ptr) { if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; else { *ptr2++='\\'; switch (token=*ptr++) { case '\\': *ptr2++='\\'; break; case '\"': *ptr2++='\"'; break; case '\b': *ptr2++='b'; break; case '\f': *ptr2++='f'; break; case '\n': *ptr2++='n'; break; case '\r': *ptr2++='r'; break; case '\t': *ptr2++='t'; break; default: _hx_sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ } } } *ptr2++='\"';*ptr2++=0; return out; }
static DWORD fslist(__CMD_PARA_OBJ* pcpo) { CHAR Buffer[96]; int i; PrintLine(" fs_id fs_label fs_type"); PrintLine(" ----- -------- -------"); for(i = 0;i < FILE_SYSTEM_NUM;i ++) { if(0 == FsGlobalData.FsArray[i].FileSystemIdentifier) //Not used yet. { continue; } _hx_sprintf(Buffer," %4c: %11s %8X", FsGlobalData.FsArray[i].FileSystemIdentifier, FsGlobalData.FsArray[i].VolumeLbl, FsGlobalData.FsArray[i].dwAttribute); PrintLine(Buffer); } return SHELL_CMD_PARSER_SUCCESS;; }
//Handler for 'runtime' command. VOID RunTimeHandler(LPSTR pstr) { CHAR Buffer[192]; DWORD week = 0,day = 0,hour = 0,minute = 0,second = 0; second = System.GetSysTick(NULL); //Get system tick counter. //Convert to second. second *= SYSTEM_TIME_SLICE; second /= 1000; if(second >= 60) //Use minute. { minute = second / 60; second = second % 60; } if(minute >= 60) //use hour. { hour = minute / 60; minute = minute % 60; } if(hour >= 24) //Use day. { day = hour / 24; hour = hour % 24; } if(day >= 7) //Use week. { week = day / 7; day = day % 7; } //Show out the result. _hx_sprintf(Buffer,"System has running %d week(s), %d day(s), %d hour(s), %d minute(s), %d second(s).", week,day,hour,minute,second); PrintLine(Buffer); }
//Helper routine to obtain volume lable. static BOOL GetVolumeLbl(__FAT32_FS* pFat32Fs,CHAR* pVolumeLbl) { BOOL bResult = FALSE; __FAT32_SHORTENTRY* pfse = NULL; BYTE* pBuffer = NULL; DWORD dwCurrClus = 0; DWORD dwSector = 0; CHAR Buffer[128] = {0}; INT i,j; if((NULL == pFat32Fs) || (NULL == pVolumeLbl)) { goto __TERMINAL; } //Create local buffer to contain one cluster. pBuffer = (BYTE*)FatMem_Alloc(pFat32Fs->SectorPerClus * pFat32Fs->dwBytePerSector); if(NULL == pBuffer) { PrintLine("Can not allocate memory from heap."); goto __TERMINAL; } dwCurrClus = pFat32Fs->dwRootDirClusStart; while(!IS_EOC(dwCurrClus)) //Main loop to check the root directory. { dwSector = GetClusterSector(pFat32Fs,dwCurrClus); if(0 == dwSector) //Fatal error. { goto __TERMINAL; } if(!ReadDeviceSector((__COMMON_OBJECT*)pFat32Fs->pPartition, dwSector, pFat32Fs->SectorPerClus, pBuffer)) //Can not read the appropriate sector(s). { _hx_sprintf(Buffer," Read sector failed in GetVolumeLbl,Info: %d %d %d %d %d %d %d ", dwCurrClus, dwSector, pFat32Fs->dwClusterSize, pFat32Fs->dwDataSectorStart, pFat32Fs->dwFatSectorNum, pFat32Fs->dwFatBeginSector, pFat32Fs->SectorPerClus); PrintLine(Buffer); //Only used for debugging. goto __TERMINAL; } //Now check the root directory to seek the volume ID entry. pfse = (__FAT32_SHORTENTRY*)pBuffer; for(i = 0; i < pFat32Fs->SectorPerClus * 16; i ++) { if(0xE5 == (BYTE)pfse->FileName[0]) //Empty entry. { pfse += 1; //Seek to the next entry. continue; } if(0 == pfse->FileName[0]) //All rest part is zero,no need to check futher. { break; } if(FILE_ATTR_LONGNAME == pfse->FileAttributes) //Long file name entry. { pfse += 1; continue; } if(FILE_ATTR_VOLUMEID & pfse->FileAttributes) //Volume label entry. { for(j = 0; j < 11; j ++) { pVolumeLbl[j] = pfse->FileName[j]; } pVolumeLbl[j] = 0; //Set the terminator. bResult = TRUE; goto __TERMINAL; } pfse += 1; } if(!GetNextCluster(pFat32Fs,&dwCurrClus)) { _hx_printf(Buffer,"Current cluster number is %d\n",dwCurrClus); break; } } __TERMINAL: FatMem_Free(pBuffer); return bResult; }
// //The main entry of OS.When the OS kernel is loaded into memory and all hardware //context is initialized OK,Hello China OS's kernel will run from here. //This is a never finish(infinite) routine and will never end unless powers off //the system or reboot the system. //It's main functions are initializing all system level objects and modules,loading kernel //mode hardware drivers,loading external function modules(such as GUI and network),then //creating several kernel thread(s) and entering a dead loop. //But the dead loop codes only run a short time since the kernel thread(s) will be //scheduled once system clock occurs and the dead loop will end. // void __OS_Entry() { __KERNEL_THREAD_OBJECT* lpIdleThread = NULL; __KERNEL_THREAD_OBJECT* lpShellThread = NULL; #ifdef __CFG_USE_EOS __KERNEL_THREAD_OBJECT* lpUserThread = NULL; #endif DWORD dwIndex = 0; CHAR strInfo[64]; char* pszErrorMsg = "INIT: OK"; //Print out welcome message. //Please note the output should put here that before the System.BeginInitialization routine, //since it may cause the interrupt enable,which will lead the failure of system initialization. /*ClearScreen(); PrintStr(pszStartMsg1); PrintStr(pszStartMsg2); GotoHome(); ChangeLine(); PrintStr(pszHelpInfo); //Print out help information. GotoHome(); ChangeLine();*/ //Prepare the OS initialization environment.It's worth noting that even the System //object self is not initialized yet. if(!System.BeginInitialize((__COMMON_OBJECT*)&System)) { pszErrorMsg = "INIT ERROR: System.BeginInitialization routine failed."; goto __TERMINAL; } //Initialize memory management object.This object must be initialized before any other //system level objects since it's function maybe required by them. if(!AnySizeBuffer.Initialize(&AnySizeBuffer)) { pszErrorMsg = "INIT ERROR: Failed to initialize AnySizeBuffer object."; goto __TERMINAL; } #ifdef __I386__ // load display device dwIndex = 0; while(DisplayEntryArray[dwIndex]) { if(!DisplayManager.LoadDisplay(DisplayEntryArray[dwIndex])) //Failed to load. { //sprintf(strInfo,"Failed to load the %dth driver.",dwIndex); //Show an error. //PrintLine(strInfo); } dwIndex ++; //Continue to load. } CD_InitDisplay(0); #endif ClearScreen(); PrintStr(pszStartMsg1); PrintStr(pszStartMsg2); GotoHome(); ChangeLine(); PrintStr(pszHelpInfo); //Print out help information. GotoHome(); ChangeLine(); #ifdef __CFG_SYS_VMM //Enable VMM. *(__PDE*)PD_START = NULL_PDE; //Set the first page directory entry to NULL,to indicate //this location is not initialized yet. #endif //******************************************************************************** // //The following code initializes system level global objects. // //******************************************************************************** #ifdef __CFG_SYS_VMM //Should enable virtual memory model. lpVirtualMemoryMgr = (__VIRTUAL_MEMORY_MANAGER*)ObjectManager.CreateObject(&ObjectManager, NULL, OBJECT_TYPE_VIRTUAL_MEMORY_MANAGER); //Create virtual memory manager object. if(NULL == lpVirtualMemoryMgr) //Failed to create this object. { pszErrorMsg = "INIT ERROR: Can not create VirtualMemoryManager object."; goto __TERMINAL; } if(!lpVirtualMemoryMgr->Initialize((__COMMON_OBJECT*)lpVirtualMemoryMgr)) { pszErrorMsg = "INIT ERROR: Can not initialize VirtualMemoryManager object."; goto __TERMINAL; } #endif //Initialize Kernel Thread Manager object. if(!KernelThreadManager.Initialize((__COMMON_OBJECT*)&KernelThreadManager)) { pszErrorMsg = "INIT ERROR: Can not initialize KernelThreadManager object."; goto __TERMINAL; } //Initialize System object. if(!System.Initialize((__COMMON_OBJECT*)&System)) { pszErrorMsg = "INIT ERROR: Can not initialize System object."; goto __TERMINAL; } //Set the general interrupt handler,after this action,interrupt and //exceptions in system can be handled by System object. //This routine must be called earlier than any modules who will use //system call. #ifdef __I386__ SetGeneralIntHandler(GeneralIntHandler); #endif #ifdef __CFG_SYS_VMM //Initialize PageFrmaeManager object. if(!PageFrameManager.Initialize((__COMMON_OBJECT*)&PageFrameManager, (LPVOID)0x02000000, (LPVOID)0x09FFFFFF)) { pszErrorMsg = "INIT ERROR: Can not initialize PageFrameManager object."; goto __TERMINAL; } #endif //Device Driver Framework related global functions. #ifdef __CFG_SYS_DDF //Initialize IOManager object. if(!IOManager.Initialize((__COMMON_OBJECT*)&IOManager)) { pszErrorMsg = "INIT ERROR: Can not initialize IOManager object."; goto __TERMINAL; } //Initialize DeviceManager object. if(!DeviceManager.Initialize(&DeviceManager)) { pszErrorMsg = "INIT ERROR: Can not initialize DeviceManager object."; goto __TERMINAL; } #endif //Initialize CPU statistics object. #ifdef __CFG_SYS_CPUSTAT if(!StatCpuObject.Initialize(&StatCpuObject)) { pszErrorMsg = "INIT ERROR: Can not initialize StatCpuObject."; goto __TERMINAL; } #endif //Enable the virtual memory management mechanism if __CFG_SYS_VMM flag is defined. #ifdef __CFG_SYS_VMM EnableVMM(); #endif //******************************************************************************** // //The following code loads all inline device drivers,and external drivers implemented as //external module. // //******************************************************************************** #ifdef __CFG_SYS_DDF dwIndex = 0; while(DriverEntryArray[dwIndex]) { if(!IOManager.LoadDriver(DriverEntryArray[dwIndex])) //Failed to load. { _hx_sprintf(strInfo,"Failed to load the %dth driver.",dwIndex); //Show an error. PrintLine(strInfo); } dwIndex ++; //Continue to load. } #endif //Initialize Console object if necessary. #ifdef __CFG_SYS_CONSOLE if(!Console.Initialize(&Console)) { pszErrorMsg = "INIT ERROR: Can not initialize Console object."; goto __TERMINAL; } #endif //BISStartup(); //******************************************************************************** // //The following code creates all system level kernel threads. // //******************************************************************************** //The first one is IDLE thread,which will be scheduled when no thread need to schedule, //so it's priority is the lowest one in system,which is PRIORITY_LEVEL_LOWEST. //Also need to mention that this thread is mandatory and without any switch to turn off //it. lpIdleThread = KernelThreadManager.CreateKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, PRIORITY_LEVEL_LOWEST, SystemIdle, NULL, NULL, "IDLE"); if(NULL == lpIdleThread) { pszErrorMsg = "INIT ERROR: Can not create SystemIdle kernel thread."; goto __TERMINAL; } //Create statistics kernel thread. #ifdef __CFG_SYS_CPUSTAT lpStatKernelThread = KernelThreadManager.CreateKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, PRIORITY_LEVEL_HIGH, //With high priority. StatThreadRoutine, NULL, NULL, "CPU STAT"); if(NULL == lpStatKernelThread) { pszErrorMsg = "INIT ERROR: Can not create CPU_Stat kernel thread."; goto __TERMINAL; } #endif //Create shell thread.The shell thread's implementation code resides in shell.cpp //file in shell directory. #ifdef __CFG_SYS_SHELL //Shell can be eleminated by turn off this switch. if(NULL == ModuleMgr.ShellEntry) //Use default shell. { lpShellThread = KernelThreadManager.CreateKernelThread( //Create shell thread. (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, PRIORITY_LEVEL_HIGH, ShellEntryPoint, NULL, NULL, "SHELL"); if(NULL == lpShellThread) { pszErrorMsg = "INIT ERROR: Can not create Shell kernel thread."; goto __TERMINAL; } } else //Use other kernel module specified shell. { lpShellThread = KernelThreadManager.CreateKernelThread( //Create shell thread. (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, PRIORITY_LEVEL_HIGH, ModuleMgr.ShellEntry, NULL, NULL, "SHELL"); if(NULL == lpShellThread) { pszErrorMsg = "INIT ERROR: Can not create Shell kernel thread."; goto __TERMINAL; } } g_lpShellThread = lpShellThread; //Initialize the shell thread global variable. //Print out the default system prompt,which can be changed by 'sysname' command. //strcpy(&HostName[0],"[system-view]"); #endif //Initialize DeviceInputManager object. if(!DeviceInputManager.Initialize((__COMMON_OBJECT*)&DeviceInputManager, NULL, (__COMMON_OBJECT*)lpShellThread)) { pszErrorMsg = "INIT ERROR: Can not initialize DeviceInputManager object."; goto __TERMINAL; } //******************************************************************************** // //The following code creates user's main kernel thread if used as EOS. // //******************************************************************************** //Create user kernel thread. #ifdef __CFG_USE_EOS lpUserThread = KernelThreadManager.CreateKernelThread( //Create shell thread. (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, __HCNMAIN_PRIORITY, _HCNMain, NULL, NULL, __HCNMAIN_NAME); if(NULL == lpUserThread) { pszErrorMsg = "INIT ERROR: Can not create User_Main kernel thread."; goto __TERMINAL; } #endif //If log debugging functions is enabled. #ifdef __CFG_SYS_LOGCAT DebugManager.Initialize(&DebugManager); lpLogcatDaemonThread = KernelThreadManager.CreateKernelThread( //Create logcat daemon thread. (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_READY, PRIORITY_LEVEL_NORMAL, LogcatDaemon, NULL, NULL, "Logcat Daemon"); if(NULL == lpLogcatDaemonThread) { pszErrorMsg = "INIT ERROR: Can not create Logcat_Daemon object."; goto __TERMINAL; } #endif //__CFG_SYS_LOGCAT. #ifdef __CFG_NET_IPv4 //IPv4 network protocol is enabled. if(!IPv4_Entry(NULL)) { pszErrorMsg = "INIT ERROR: Can not initialize IPv4 protocol function."; goto __TERMINAL; } if(!InitializeEthernetIf()) { pszErrorMsg = "INIT ERROR: Can not initialize Ethernet interface."; goto __TERMINAL; } #endif System.EndInitialize((__COMMON_OBJECT*)&System); //Enter a dead loop to wait for the scheduling of kernel threads. DeadLoop(); //The following code will never be executed if corrected. __TERMINAL: GotoHome(); ChangeLine(); PrintLine(pszErrorMsg); //Show error msg. DeadLoop(); }
//Read one or several sector(s) from a specified hard disk. //Please make sure the pBuffer is long enough to contain the sectors read. BOOL ReadSector(int nHdNum,DWORD dwStartSector,DWORD dwSectorNum,BYTE* pBuffer) { BYTE DrvHdr = (BYTE)IDE_DRV0_LBA; BYTE LbaLow; BYTE LbaMid; BYTE LbaHigh; UCHAR tmp; CHAR Buffer[64]; //For debug. BOOL bResult = FALSE; //---------------------------------------------------------------------- // Use BIOS service to query hard disk sector since we can not read HD // directly sometimes. //---------------------------------------------------------------------- /*while(dwSectorNum > 4) { bResult = BIOSReadSector(nHdNum,dwStartSector,4,pBuffer); //Read 4 sectors because of the BIOS buffer's limitation. if(!bResult) { return FALSE; } dwStartSector += 4; dwSectorNum -= 4; pBuffer += 512 * 4; }*/ #ifdef __I386__ return BIOSReadSector(nHdNum,dwStartSector,dwSectorNum,pBuffer); #else return FALSE; #endif if((nHdNum > 1) || (NULL == pBuffer) || (0 == dwSectorNum)) { return FALSE; } //Form the access mode and driver. if(1 == nHdNum) { DrvHdr = (BYTE)IDE_DRV1_LBA; } tmp = (UCHAR)(dwStartSector >> 24); //Get the high byte. tmp &= 0x0F; //Only keep the last 4 bits. DrvHdr += tmp; //Driver and access mode(LBA). tmp = (UCHAR)dwStartSector; LbaLow = tmp; tmp = (UCHAR)(dwStartSector >> 8); LbaMid = tmp; tmp = (UCHAR)(dwStartSector >> 16); LbaHigh = tmp; tmp = (UCHAR)dwSectorNum; //Issue the read sector command. WaitForBsy(IDE_CTRL0_PORT_STATUS,0); //WaitForRdy(IDE_CTRL0_PORT_STATUS,0); //WriteByteToPort(0x4b,IDE_CTRL0_PORT_PRECOMP); __outb(0x4B,IDE_CTRL0_PORT_PRECOMP); //WriteByteToPort(0x01,IDE_CTRL0_PORT_SECTORNUM); __outb(tmp,IDE_CTRL0_PORT_SECTORNUM); //WriteByteToPort(byStartSector,IDE_CTRL0_PORT_STARTSECTOR); __outb(LbaLow,IDE_CTRL0_PORT_STARTSECTOR); //WriteByteToPort(byCylinderLo,IDE_CTRL0_PORT_CYLINDLO); __outb(LbaMid,IDE_CTRL0_PORT_CYLINDLO); //WriteByteToPort(byCylinderHi,IDE_CTRL0_PORT_CYLINDHI); __outb(LbaHigh,IDE_CTRL0_PORT_CYLINDHI); //WriteByteToPort(byDrvHdr,IDE_CTRL0_PORT_HEADER); __outb(DrvHdr,IDE_CTRL0_PORT_HEADER); //WaitForBsy(IDE_CTRL0_PORT_STATUS,0); WaitForRdy(IDE_CTRL0_PORT_STATUS,0); //WriteByteToPort(IDE_CMD_READ,IDE_CTRL0_PORT_CMD); __outb(IDE_CMD_READ,IDE_CTRL0_PORT_CMD); //Wait for completion. //WaitForBsy(IDE_CTRL0_PORT_STATUS,0); WaitForDrq(IDE_CTRL0_PORT_STATUS,0); //WaitForRdy(IDE_CTRL0_PORT_STATUS,0); //Read data from port. __inws(pBuffer,tmp * 512,IDE_CTRL0_PORT_DATA); //WaitForBsy(IDE_CTRL0_PORT_STATUS,0); //WaitForRdy(IDE_CTRL0_PORT_STATUS,0); //Appended by Garry in 2011.05.30 if(CmdSucc(IDE_CTRL0_PORT_STATUS)) { return TRUE; } tmp = __inb(0x1f2); _hx_sprintf(Buffer,"The error number is : %d",tmp); PrintLine(Buffer); return FALSE; }
//Get one free cluster and mark the cluster as used. //If find,TRUE will be returned and the cluster number will be set in pdwFreeCluster, //else FALSE will be returned without any changing to pdwFreeCluster. BOOL GetFreeCluster(__FAT32_FS* pFat32Fs,DWORD dwStartToFind,DWORD* pdwFreeCluster) { DWORD dwCurrCluster = 0; DWORD dwSector = 0; BYTE* pBuffer = NULL; DWORD* pCluster = NULL; BOOL bResult = FALSE; DWORD i; CHAR Buffer[64]; pBuffer = (BYTE*)KMemAlloc(pFat32Fs->dwBytePerSector,KMEM_SIZE_TYPE_ANY); if(NULL == pBuffer) //Can not allocate temporary buffer. { return FALSE; } dwSector = pFat32Fs->dwFatBeginSector; while(dwSector < pFat32Fs->dwFatSectorNum + pFat32Fs->dwFatBeginSector) { if(!ReadDeviceSector((__COMMON_OBJECT*)pFat32Fs->pPartition, dwSector, 1, pBuffer)) //Can not read the sector from fat region. { goto __TERMINAL; } pCluster = (DWORD*)pBuffer; //Analysis the sector to find a free cluster entry. for(i = 0;i < pFat32Fs->dwBytePerSector / sizeof(DWORD);i ++) { if(0 == ((*pCluster) & 0x0FFFFFFF)) //Find one free cluster. { (*pCluster) |= 0x0FFFFFFF; //Mark the cluster to EOC,occupied. if(!WriteDeviceSector((__COMMON_OBJECT*)pFat32Fs->pPartition, dwSector, 1, pBuffer)) { goto __TERMINAL; } //Write to backup FAT region. WriteDeviceSector((__COMMON_OBJECT*)pFat32Fs->pPartition, dwSector + pFat32Fs->dwFatSectorNum, 1, pBuffer); //It is no matter if write to backup fat failed. bResult = TRUE; _hx_sprintf(Buffer," In GetFreeCluster,success,cluster = %d,next = %d",dwCurrCluster,*pCluster); PrintLine(Buffer); goto __TERMINAL; } pCluster ++; dwCurrCluster ++; } dwSector ++; //Travel the FAT region in sector unit one by one. } __TERMINAL: if(pBuffer) { KMemFree(pBuffer,KMEM_SIZE_TYPE_ANY,0); } if(bResult) //Found one free cluster successfully,return it. { *pdwFreeCluster = dwCurrCluster; } return bResult; }
//Initializes one directory,i.e,write dot and dotdot directories into one directory newly created. // @dwParentCluster : The start cluster number of target directory's parent directory; // @dwDirCluster : The start cluster number of target directory. BOOL InitDirectory(__FAT32_FS* pFat32Fs,DWORD dwParentCluster,DWORD dwDirCluster) { BYTE* pBuffer = NULL; //Temprory buffer used to contain first cluster. __FAT32_SHORTENTRY* pfse = NULL; BOOL bResult = FALSE; DWORD dwDirSector = 0; CHAR Buffer[128]; if((NULL == pFat32Fs) || (dwParentCluster < 2) || (dwDirCluster < 2) || IS_EOC(dwParentCluster) || IS_EOC(dwDirCluster)) { _hx_sprintf(Buffer," In InitDirectory: parent clus = %d,dir clus = %d", dwParentCluster, dwDirCluster); PrintLine(Buffer); PrintLine(" In InitDirectory: Condition 0"); goto __TERMINAL; } //Allocate temporary buffer. pBuffer = (BYTE*)KMemAlloc(pFat32Fs->dwClusterSize, KMEM_SIZE_TYPE_ANY); if(NULL == pBuffer) { PrintLine(" In InitDirectory: Condition 1"); goto __TERMINAL; } dwDirSector = GetClusterSector(pFat32Fs,dwDirCluster); //Get the start cluster number of target dir. if(IS_EOC(dwDirSector)) { PrintLine(" In InitDirectory: Condition 2"); goto __TERMINAL; } //Clear cluster's content to zero. memzero(pBuffer,pFat32Fs->dwClusterSize); pfse = (__FAT32_SHORTENTRY*)pBuffer; InitShortEntry(pfse,".",dwDirCluster,0,FILE_ATTR_DIRECTORY); //Create the dot directory. /*pfse->CreateDate = 0; pfse->CreateTime = 0; pfse->CreateTimeTenth = 0; pfse->dwFileSize = 0; pfse->FileAttributes = FILE_ATTR_DIRECTORY; pfse->FileName[0] = '.'; pfse->LastAccessDate = 0; pfse->wFirstClusHi = (WORD)(dwDirCluster >> 16); pfse->wFirstClusLow = (WORD)dwDirCluster; pfse->WriteDate = 0; pfse->WriteTime = 0;*/ pfse ++; //Create the dotdot directory. InitShortEntry(pfse,"..",dwDirCluster,0,FILE_ATTR_DIRECTORY); /*pfse->CreateDate = 0; pfse->CreateTime = 0; pfse->CreateTimeTenth = 0; pfse->dwFileSize = 0; pfse->FileAttributes = FILE_ATTR_DIRECTORY; pfse->FileName[0] = '.'; pfse->FileName[1] = '.'; pfse->LastAccessDate = 0; pfse->wFirstClusHi = (WORD)(dwParentCluster >> 16); pfse->wFirstClusLow = (WORD)dwParentCluster; pfse->WriteDate = 0; pfse->WriteTime = 0;*/ pfse ++; //Write the cluster into directory. if(!WriteDeviceSector((__COMMON_OBJECT*)pFat32Fs->pPartition, dwDirSector, pFat32Fs->SectorPerClus, pBuffer)) { PrintLine(" In InitDirectory: Condition 3"); goto __TERMINAL; } bResult = TRUE; __TERMINAL: if(pBuffer) { KMemFree(pBuffer,KMEM_SIZE_TYPE_ANY,0); } return bResult; }
static VOID DispatchInterrupt(__COMMON_OBJECT* lpThis, LPVOID lpEsp, UCHAR ucVector) { __INTERRUPT_OBJECT* lpIntObject = NULL; __SYSTEM* lpSystem = (__SYSTEM*)lpThis; CHAR strError[64]; //To print out the BUG information. if((NULL == lpThis) || (NULL == lpEsp)) { return; } lpSystem->ucIntNestLevel += 1; //Increment nesting level. if(lpSystem->ucIntNestLevel <= 1) { //Call thread hook here,because current kernel thread is //interrupted. //If interrupt occurs before any kernel thread is scheduled, //lpCurrentKernelThread is NULL. if(KernelThreadManager.lpCurrentKernelThread) { KernelThreadManager.CallThreadHook( THREAD_HOOK_TYPE_ENDSCHEDULE, KernelThreadManager.lpCurrentKernelThread, NULL); } } //For debugging. else { #ifdef __CFG_SYS_INTNEST //Interupt nest is enabled. //Do nothing. #else _hx_printf("Fatal error,interrupt nested(enter-int,vector = %d,nestlevel = %d)\r\n", ucVector, lpSystem->ucIntNestLevel); BUG(); #endif } lpIntObject = lpSystem->lpInterruptVector[ucVector]; if(NULL == lpIntObject) //The current interrupt vector has not handler object. { DefaultIntHandler(lpEsp,ucVector); goto __RETFROMINT; } while(lpIntObject) //Travel the whole interrupt list of this vector. { if(lpIntObject->InterruptHandler(lpEsp, lpIntObject->lpHandlerParam)) //If an interrupt object handles the interrupt,then returns. { break; } lpIntObject = lpIntObject->lpNextInterruptObject; } __RETFROMINT: lpSystem->ucIntNestLevel -= 1; //Decrement interrupt nesting level. if(0 == lpSystem->ucIntNestLevel) //The outmost interrupt. { if (IN_SYSINITIALIZATION()) //It's a abnormal case. { _hx_sprintf(strError, "Warning: Interrupt[%d] raised in sys initialization.", ucVector); PrintLine(strError); } else { KernelThreadManager.ScheduleFromInt((__COMMON_OBJECT*)&KernelThreadManager, lpEsp); //Re-schedule kernel thread. } } else { #ifdef __CFG_SYS_INTNEST //Interrupt nest is enabled. //Do nothing. #else _hx_printf("Fatal error,interrupt nested(leave-int,vector = %d,nestlevel = %d)\r\n", ucVector, lpSystem->ucIntNestLevel); BUG(); #endif //__CFG_SYS_INTNEST } return; }
static DWORD type(__CMD_PARA_OBJ* pCmdObj) { #ifdef __CFG_SYS_DDF HANDLE hFile = NULL; CHAR Buffer[128]; DWORD dwReadSize = 0; DWORD dwTotalRead = 0; DWORD i; CHAR FullName[MAX_FILE_NAME_LEN]; WORD ch = 0x0700; if(pCmdObj->byParameterNum < 2) { PrintLine(" Please specify the file name to be displayed."); goto __TERMINAL; } strcpy(FullName,FsGlobalData.CurrentDir); strcat(FullName,pCmdObj->Parameter[1]); ToCapital(FullName); //Try to open the target file. hFile = IOManager.CreateFile((__COMMON_OBJECT*)&IOManager, FullName, FILE_ACCESS_READ, 0, NULL); if(NULL == hFile) { PrintLine(" Please specify a valid and present file name."); goto __TERMINAL; } //Try to read the target file and display it. GotoHome(); ChangeLine(); do{ if(!IOManager.ReadFile((__COMMON_OBJECT*)&IOManager, hFile, 128, Buffer, &dwReadSize)) { PrintLine(" Can not read the target file."); goto __TERMINAL; } for(i = 0;i < dwReadSize;i ++) { if('\r' == Buffer[i]) { GotoHome(); continue; } if('\n' == Buffer[i]) { ChangeLine(); continue; } ch += Buffer[i]; PrintCh(ch); ch = 0x0700; } dwTotalRead += dwReadSize; }while(dwReadSize == 128); GotoHome(); ChangeLine(); _hx_sprintf(Buffer,"%d byte(s) read.",dwTotalRead); PrintLine(Buffer); __TERMINAL: if(NULL != hFile) { IOManager.CloseFile((__COMMON_OBJECT*)&IOManager, hFile); } return SHELL_CMD_PARSER_SUCCESS;; #else return FS_CMD_FAILED; #endif }
/* * A helper routine to initialize and register a new found R8152 * device. It will be invoked when a new device is scaned in Driver Entry * routine. */ static int Init_R8152(struct usb_device *dev, unsigned int ifnum) { struct usb_interface *iface; struct usb_interface_descriptor *iface_desc; int ep_in_found = 0, ep_out_found = 0; struct ueth_data* ss = NULL; int i, ret = 0; struct r8152 *tp = NULL; char recv_name[64]; static int ef_idx = 0; /* Construct a new management data struct of R8152. */ ss = _hx_malloc(sizeof(struct ueth_data)); if (NULL == ss) { goto __TERMINAL; } memset(ss, 0, sizeof(struct ueth_data)); /* let's examine the device now */ iface = &dev->config.if_desc[ifnum]; iface_desc = &dev->config.if_desc[ifnum].desc; /* At this point, we know we've got a live one */ debug("\n\nUSB Ethernet device detected: %#04x:%#04x\n", dev->descriptor.idVendor, dev->descriptor.idProduct); /* Initialize the ueth_data structure with some useful info */ ss->ifnum = ifnum; ss->pusb_dev = dev; ss->subclass = iface_desc->bInterfaceSubClass; ss->protocol = iface_desc->bInterfaceProtocol; /* alloc driver private */ ss->dev_priv = calloc(1, sizeof(struct r8152)); if (!ss->dev_priv) { goto __TERMINAL; } memzero(ss->dev_priv, sizeof(struct r8152)); /* * We are expecting a minimum of 3 endpoints - in, out (bulk), and * int. We will ignore any others. */ for (i = 0; i < iface_desc->bNumEndpoints; i++) { /* is it an BULK endpoint? */ if ((iface->ep_desc[i].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK) { u8 ep_addr = iface->ep_desc[i].bEndpointAddress; if ((ep_addr & USB_DIR_IN) && !ep_in_found) { ss->ep_in = ep_addr & USB_ENDPOINT_NUMBER_MASK; ep_in_found = 1; } else { if (!ep_out_found) { ss->ep_out = ep_addr & USB_ENDPOINT_NUMBER_MASK; ep_out_found = 1; } } } /* is it an interrupt endpoint? */ if ((iface->ep_desc[i].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) { ss->ep_int = iface->ep_desc[i].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK; ss->irqinterval = iface->ep_desc[i].bInterval; } } debug("Endpoints In %d Out %d Int %d\n", ss->ep_in, ss->ep_out, ss->ep_int); /* Do some basic sanity checks, and bail if we find a problem */ if (usb_set_interface(dev, iface_desc->bInterfaceNumber, 0) || !ss->ep_in || !ss->ep_out || !ss->ep_int) { debug("Problems with device\n"); goto __TERMINAL; } /* Establish data structure's relationship. */ dev->privptr = (void *)ss; tp = ss->dev_priv; tp->udev = dev; tp->intf = iface; r8152b_get_version(tp); if (rtl_ops_init(tp)) { _hx_printf("%s: failed to init r8152 device.\r\n", __func__); goto __TERMINAL; } tp->rtl_ops.init(tp); tp->rtl_ops.up(tp); rtl8152_set_speed(tp, AUTONEG_ENABLE, tp->supports_gmii ? SPEED_1000 : SPEED_100, DUPLEX_FULL); /* Assign a index value to this USB ethernet interface. */ ss->ef_idx = ef_idx++; /* Initialization seems OK,now register the R8152 device into * HelloX kernel. */ if (!Register_R8152(dev, ss)) { _hx_printf("Failed to register R8152 into system.\r\n"); goto __TERMINAL; } /* * Create the recv and send buffer.These 2 buffers * will be released when the corresponding rx/tx thread exit. */ ss->rx_buff = (char*)_hx_aligned_malloc(RTL8152_AGG_BUF_SZ, USB_DMA_MINALIGN); if (NULL == ss->rx_buff) { goto __TERMINAL; } ss->tx_buff = (char*)_hx_aligned_malloc(RTL8152_AGG_BUF_SZ, USB_DMA_MINALIGN); if (NULL == ss->tx_buff) { goto __TERMINAL; } /* * Create the rx and tx bulk transfer descriptor,which is used * by the corresponding rx/tx thread. * These 2 descriptors will be destroyed by the rx/tx thread before * exit. */ ss->pTxDesc = usbCreateAsyncDescriptor( ss->pusb_dev, usb_sndbulkpipe(ss->pusb_dev, ss->ep_out), ss->tx_buff, RTL8152_AGG_BUF_SZ, NULL); if (NULL == ss->pTxDesc) { goto __TERMINAL; } ss->pRxDesc = usbCreateAsyncDescriptor( ss->pusb_dev, usb_rcvbulkpipe(ss->pusb_dev, ss->ep_in), ss->rx_buff, RTL8152_AGG_BUF_SZ, NULL); if (NULL == ss->pRxDesc) { _hx_printf("%s: create rx desc failed.\r\n", __func__); goto __TERMINAL; } /* * Create the dedicated receiving kernel thread. */ _hx_sprintf(recv_name, "%s%d", R8152_RECV_NAME_BASE, ss->ef_idx); ss->pRxThread = KernelThreadManager.CreateKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_SUSPENDED, PRIORITY_LEVEL_NORMAL, __R8152_Recv, (LPVOID)ss, NULL, recv_name); if (NULL == ss->pRxThread) { goto __TERMINAL; } /* * Create the dedicated sending kernel thread. */ _hx_sprintf(recv_name, "%s%d", R8152_SEND_NAME_BASE, ss->ef_idx); ss->pTxThread = KernelThreadManager.CreateKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, 0, KERNEL_THREAD_STATUS_SUSPENDED, PRIORITY_LEVEL_NORMAL, __R8152_Send, (LPVOID)ss, NULL, recv_name); if (NULL == ss->pTxThread) { goto __TERMINAL; } /* Link the management data structure into global list. */ ss->pNext = global_list; global_list = ss; /* Resume the corresponding thread to run. */ /*KernelThreadManager.ResumeKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, (__COMMON_OBJECT*)ss->pRxThread); KernelThreadManager.ResumeKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, (__COMMON_OBJECT*)ss->pTxThread);*/ /* Mark all things in place. */ ret = 1; __TERMINAL: if (0 == ret) /* Failed,should release all resources allocated. */ { if (ss) { Unregister_R8152(dev, ss); if (ss->pRxThread) //Shoud destroy it. { WaitForThisObject((HANDLE)ss->pRxThread); KernelThreadManager.DestroyKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, (__COMMON_OBJECT*)ss->pRxThread); } if (ss->pTxThread) { WaitForThisObject((HANDLE)ss->pTxThread); KernelThreadManager.DestroyKernelThread( (__COMMON_OBJECT*)&KernelThreadManager, (__COMMON_OBJECT*)ss->pTxThread); } if (ss->dev_priv) { _hx_free(ss->dev_priv); } if (ss->rx_buff) { _hx_free(ss->rx_buff); } if (ss->tx_buff) { _hx_free(ss->tx_buff); } if (ss->pRxDesc) { usbStopAsyncXfer(ss->pRxDesc); usbDestroyAsyncDescriptor(ss->pRxDesc); } if (ss->pTxDesc) { usbStopAsyncXfer(ss->pTxDesc); usbDestroyAsyncDescriptor(ss->pTxDesc); } _hx_free(ss); } /* Reset USB device's private pointer since it maybe changed in * above process. */ dev->privptr = NULL; } return ret; }
//Hardware fault handler. void HardFault_Handler() { DWORD* msp = (DWORD*)__get_MSP(); //int i = 16; char buff[32]; DWORD* esp = (DWORD*)KernelThreadManager.lpCurrentKernelThread->lpKernelThreadContext; SER_PutString("\r\nHardFault_Handler\r\n"); SER_PutString(" ---- Thread Info ---- \r\n"); SER_PutString(" Thread name: "); SER_PutString((char*)KernelThreadManager.lpCurrentKernelThread->KernelThreadName); SER_PutString("\r\n"); SER_PutString(" Thread Status: "); if(KERNEL_THREAD_STATUS_RUNNING == KernelThreadManager.lpCurrentKernelThread->dwThreadStatus) { SER_PutString(" RUNNING.\r\n"); } if(KERNEL_THREAD_STATUS_READY == KernelThreadManager.lpCurrentKernelThread->dwThreadStatus) { SER_PutString(" READY.\r\n"); } if(KERNEL_THREAD_STATUS_BLOCKED == KernelThreadManager.lpCurrentKernelThread->dwThreadStatus) { SER_PutString(" BLOCKED.\r\n"); } _hx_sprintf(buff,"ESP = %X\r\n",KernelThreadManager.lpCurrentKernelThread->lpKernelThreadContext); SER_PutString(buff); _hx_sprintf(buff,"MSP = %X\r\n",msp); SER_PutString(buff); _hx_sprintf(buff,"xPSR = %X\r\n",*esp ++); SER_PutString(buff); _hx_sprintf(buff,"PC = %X\r\n",*esp ++); SER_PutString(buff); _hx_sprintf(buff,"LR = %X\r\n",*esp ++); SER_PutString(buff); _hx_sprintf(buff,"R12 = %X\r\n",*esp ++); SER_PutString(buff); SER_PutString(" ---- Exception Info ---- \r\n"); _hx_sprintf(buff,"MSP = %X\r\n",msp); SER_PutString(buff); _hx_sprintf(buff,"D1 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D2 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D3 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D4 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D5 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D6 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D7 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D8 = %X\r\n",*msp ++); SER_PutString(buff); _hx_sprintf(buff,"D9 = %X\r\n",*msp ++); SER_PutString(buff); while(TRUE); }