#include "common_api.h" #include "DriverManager.h" #include "DPC.h" #include "CDI.h" #include "DrvTree.h" //#include "logger.h" #include "LocalConfig.h" #include "BusUnitClient.h" #include "LogicDriver.h" #include "HandleManager.h" #include "PacketAnalizer.h" #include typedef DriverDPC* (*GetDriverDPC)(); typedef void(*ReleaseDriverDPC)(DriverDPC *p); //extern Log4CPP::Logger* mLog::gLogger; DriverManager g_DrvManager; DriverHandle::DriverHandle() { m_DllFileHandle = 0; m_pRootDevice = 0; m_pDynRootDevice = 0; m_pDPC = 0; m_HandleStatus = false; m_AsRootDriver = false; //m_pLog = CreateLogger(); //m_pDynLog = CreateLogger(); m_IsRootHandle = false; //m_pParent = NULL; } DriverHandle::~DriverHandle() { UnloadDriver(); } void DriverHandle::InitDynLogForDPC(DriverHandle *pParent) { //log init //ResDataObject val; //string FullLogFileName; //if (pParent->m_DllFileTitle.size() > 0) //{ // m_DllFileTitle = pParent->m_DllFileTitle; // FullLogFileName = m_DynLogPath + m_DllFileTitle + string(".log"); //} //else //{ // FullLogFileName = m_DynLogPath + "drvlog.log"; //} //m_pDynLog->SetLogFilepath(FullLogFileName.c_str()); //if (pParent == NULL) //{ // if (TryGetValue(m_DrvConfig, "LOGLEVEL", val)) // { // Logger_Pattern lp; // m_pDynLog->GetLogPattern(lp); // if (lp.SetLevel((LONG)val)) // { // m_pDynLog->SetLogPattern(lp); // } // } // //dpc logger // m_pDPC->SetDynLogHandle(m_pDynLog); //} //else// if (pParent != this) //{ // if (m_pDPC) // { // LONG Level; // Logger_Pattern lp; // pParent->m_pLog->GetLogPattern(lp); // Level = lp.m_Level; // m_pDynLog->GetLogPattern(lp); // lp.SetLevel(Level); // m_pDynLog->SetLogPattern(lp); // //dpc logger // m_pDPC->SetDynLogHandle(m_pDynLog); // } //} } void DriverHandle::InitLogForDPC(DriverHandle *pParent) { //log init //ResDataObject val; //string FullLogFileName; //if (pParent == NULL) //{ // if (TryGetValue(m_DrvConfig, "LOGLEVEL", val)) // { // Logger_Pattern lp; // m_pLog->GetLogPattern(lp); // if (lp.SetLevel((LONG)val)) // { // m_pLog->SetLogPattern(lp); // } // } // //dpc logger // ((DriverDPC*)m_pDPC)->SetLogHandle(m_pLog); //} ////else if (pParent == this) ////{ ////} //else //{ // if (pParent->m_DllFileTitle.size() > 0) // { // m_DllFileTitle = pParent->m_DllFileTitle; // FullLogFileName = m_LogPath + m_DllFileTitle + string(".log"); // } // else // { // FullLogFileName = m_LogPath + "drvlog.log"; // } // m_pLog->SetLogFilepath(FullLogFileName.c_str()); // if (m_pDPC) // { // Logger_Pattern lp; // pParent->m_pLog->GetLogPattern(lp); // m_pLog->SetLogPattern(lp); // //dpc logger // ((DriverDPC*)m_pDPC)->SetLogHandle(m_pLog); // } //} } bool DriverHandle::GetThreadsLogger(DWORD ThreadId,PVOID &pLogger) { //if (m_NotifyThread.GetTID() == ThreadId) //{ // pLogger = m_pLog; // return true; //} return false; } bool DriverHandle::InitDynSubDriverObject() { if (m_pDynRootDevice) { //loop drvtree size_t Size = m_pDynRootDevice->size(); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*m_pDynRootDevice)[i]; if (node.m_NodeType == TYPE_DRIVER) { LogicDriver *pDPC = (LogicDriver*)node.m_pObject; DriverHandle *pSubHandle = new DriverHandle(); if (DynInitHandle(pSubHandle, pDPC)) { m_DynSubDriverList.PushBack(pSubHandle); } else { return false; } } } } return true; } bool DriverHandle::InitSubDriverObject() { //mLog::FINFO("CDI "); if (m_pRootDevice) { //loop drvtree size_t Size = m_pRootDevice->size(); //mLog::FINFO("CDI ----- DriverHandle::InitSubDriverObject {$} devices", Size); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*m_pRootDevice)[i]; if (node.m_NodeType == TYPE_DRIVER) { //mLog::FINFO("CDI ----- DriverHandle::InitSubDriverObject InitHandle(pSubHandle, pDPC) again {$}", (int)node.m_NodeType ); LogicDriver*pDPC = (LogicDriver*)node.m_pObject; DriverHandle *pSubHandle = new DriverHandle(); if (InitHandle(pSubHandle, pDPC)) { m_hSubDriverList.PushBack(pSubHandle); } else { //mLog::FINFO("CDI ---- DriverHandle::InitSubDriverObject InitHandle(pSubHandle, pDPC) failed", (int)node.m_NodeType); return false; } } else { //mLog::FINFO("CDI ----- DriverHandle::InitSubDriverObject node.m_NodeType", (int)node.m_NodeType); } } } return true; } //这是一个嵌套函数,用的时候要小心 bool DriverHandle::DynInitHandle(DriverHandle *pSubHandle, LogicDriver*pDPC) { bool ret = false; string procdir; if (m_pDynRootDevice != nullptr) return true; procdir = GetProcessDirectory(); pSubHandle->m_pDPC = pDPC; //mLog::FINFO("CDI ----- DriverHandle::DynInitHandle"); //Probe //mLog::FINFO("Device_Probe "); if (pDPC->Device_Probe(pSubHandle->m_DynProbe)) { //mLog::FINFO("CDI After Device_Probe"); ResDataObject ProcDirRes; ProcDirRes = procdir.c_str(); pSubHandle->m_DynWorkPath = (const char*)MakeWorkPath(pSubHandle->m_DynProbe, pSubHandle->m_Connection, ProcDirRes,true); pSubHandle->m_DynLogPath = (const char*)MakeWorkPath(pSubHandle->m_DynProbe, pSubHandle->m_Connection, ProcDirRes, false); if (pSubHandle->m_DynWorkPath.size() > 0) { pSubHandle->InitDynLogForDPC(this); if (pDPC->SetDeviceWorkPath(pSubHandle->m_DynWorkPath.c_str())) { //mLog::FINFO("CDI pDPC->LoadLogicDevices "); PVOID pDevice = pDPC->LoadLogicDevices(); if (pDevice) { pSubHandle->m_pDynRootDevice = (DevTree*)pDevice; //先假设驱动对象不能动态生成,只能以静态的形式存在!!! //do init Driver Object first //if (pSubHandle->InitDynSubDriverObject() == false) //{ // //mLog::FERROR( "InitSubDriverObject Failed.\n"); // return false; //} //mLog::FINFO("CDI do init device Object second"); //do init device Object second if (DynMakeDevicePaths()) { //mLog::FINFO("CDI DynMakeDeviceSysIFsAndThreads"); if (DynMakeDeviceSysIFsAndThreads()) { return true; } else { //DWORD errNo = GetLastError(); //mLog::FERROR( "MakeDeviceSysIFsAndThreads Failed.ErrNo:{$}\n", errNo); return false; } } else { //DWORD errNo = GetLastError(); //mLog::FERROR( "MakeDevicePaths Failed.ErrNo:{$}\n", errNo); return false; } } //先假设驱动对象不能动态生成,只能以静态的形式存在!!! //为Sub对象 创建Driver线程和Notify线程 //if (pSubHandle->DynMakeDriverPaths()) //{ // if (pSubHandle->DynMakeDriverSysIFsAndThreads()) // { // return true; // } // else // { // DWORD errNo = GetLastError(); // //mLog::FERROR( "MakeDriverSysIFsAndThreads Failed.ErrNo:%d\n", errNo); // return false; // } //} //else //{ // DWORD errNo = GetLastError(); // //mLog::FERROR( "MakeDriverPaths Failed.ErrNo:%d\n", errNo); // return false; //} } else { //DWORD errNo = GetLastError(); //mLog::FERROR( "SetWorkPath Failed.ErrNo:{$}\n", errNo); } } else { //DWORD errNo = GetLastError(); //mLog::FERROR( "Probe Info not right.ErrNo:{$}\n", errNo); } } else { //DWORD errNo = GetLastError(); //mLog::FERROR( "Call Probe Failed.ErrNo:{$}\n", errNo); } return false; } //这是一个嵌套函数,用的时候要小心 bool DriverHandle::InitHandle(DriverHandle *pSubHandle, LogicDriver*pDPC) { bool ret = false; string procdir; procdir = GetProcessDirectory(); //Logger *p = GetGlobalLogger(); //mLog::FINFO( "CDI DriverHandle::InitHandle"); pSubHandle->m_pDPC = pDPC; //Probe //mLog::FINFO("CDI First pDPC->Driver_Probe"); if (pDPC->Driver_Probe(pSubHandle->m_Probe)) { //mLog::FINFO("CDI After pDPC->Driver_Probe"); if (!m_AsRootDriver) { //mLog::FINFO("CDI !m_AsRootDriver"); GUID guid; string guidname; ((LogicDriver*)m_pDPC)->GetDeviceType(guid); guid_2_string(guid, guidname); ResDataObject subpath; subpath = (guidname).c_str(); string fullpath = MakeDevicePath(m_Probe, m_Connection, subpath).encode(); string ccospath = MakeCcosPath(m_Probe, m_Connection, subpath, true).encode(); //pDPC->SetEbusRoot(fullpath.c_str()); pDPC->SetClientRootID(fullpath.c_str(), ccospath.c_str()); //mLog::FINFO("CDI pDPC->SetClientRootID fulpath:[{$}] ccospath:[{$}] use subpath[{$}] Real CCOS path [{$}]", fullpath, ccospath, (const char*)subpath, pDPC->GetCcosRootPath()); g_DrvManager.AddDevice(pDPC->GetCcosRootPath().c_str(), pDPC); g_DrvManager.AddDevice(pDPC->GetCcosAbstractPath().c_str(), pDPC); } //mLog::FINFO("CDI SetWorkPath"); ResDataObject ProcDirRes; ProcDirRes = procdir.c_str(); pSubHandle->m_WorkPath = (const char*)MakeWorkPath(pSubHandle->m_Probe, pSubHandle->m_Connection, ProcDirRes,true); pSubHandle->m_LogPath = (const char*)MakeWorkPath(pSubHandle->m_Probe, pSubHandle->m_Connection, ProcDirRes, false); if (pSubHandle->m_WorkPath.size() > 0) { pSubHandle->InitLogForDPC(this); if (pDPC->SetDriverWorkPath(pSubHandle->m_WorkPath.c_str())) { PVOID pDevice = NULL; if(pDPC->GetDPCType() == DPCDRIVER_NORMAL) { //mLog::FINFO("CDI ----- DriverHandle::InitHandle DPCDRIVER_NORMAL"); pDevice = pDPC->LoadDriver(); //从DPC 上拿到设备树 //mLog::FINFO("CDI pDPC->LoadDriver over."); } else// if (pDPC->GetDPCType() == DPCDRIVER_MDPC) { //mLog::FINFO("CDI ----- DriverHandle::InitHandle ??? DPCDRIVER_MDPC ??"); //no load driver method calling. } //Step1:do init subdriver first if (pDevice) { //mLog::FINFO("CDI Got DevTree"); pSubHandle->m_pRootDevice = (DevTree*)pDevice; //pDevice 以及有这个树上的子节点了 for (int x = 0; x < pSubHandle->m_pRootDevice->size(); x++) { LogicDriver* pChild = (LogicDriver*)((*(pSubHandle->m_pRootDevice))[x].m_pObject); LogicDevice* pDevice = (LogicDevice*)((*(pSubHandle->m_pRootDevice))[x].m_pObject); //mLog::FINFO("CDI {$} Node ", x); //*/ if (!m_AsRootDriver) { //mLog::FINFO("CDI !m_AsRootDriver true"); //LogicDevice* pDevice = (LogicDevice*)pChild; GUID guid2; string guidname; //((LogicDevice*)pChild)->GetDeviceType(guid); pDevice->GetDeviceType(guid2); guid_2_string(guid2, guidname); ResDataObject subpath; subpath = (guidname).c_str(); string fullpath = MakeDevicePath(m_Probe, m_Connection, subpath).encode(); //pDevice->SetEbusRoot(fullpath.c_str()); string ccospath = MakeCcosPath(m_Probe, m_Connection, subpath).encode(); pDevice->SetClientRootID(fullpath.c_str(), ccospath.c_str()); //mLog::FINFO("CDI pDevice->SetClientRootID fullpath :[{$}] ccos path [{$}] Real CCOS path [{$}] ", fullpath, ccospath, pDevice->GetCcosRootPath()); g_DrvManager.AddDevice(pDevice->GetCcosAbstractPath().c_str(), pDevice); g_DrvManager.AddDevice(pDevice->GetCcosRootPath().c_str(), pDevice); } else { string path = string(getRootpath()); pDPC->SetClientRootID(path.c_str(), path.c_str() + 1); //mLog::FINFO("CDI Bus pDPC->SetClientRootID fulpath:[{$}] ccospath:[{$}] Real CCOS path [{$}]", path, path.c_str() + 1, pDPC->GetCcosRootPath()); g_DrvManager.AddDevice(pDevice->GetCcosRootPath().c_str(), pDevice); } pDPC->AddEbusChildren(pChild, pChild->GetRootPath().c_str()); //*/ } //do init Driver Object first //mLog::FINFO("CDI ----- DriverHandle::InitHandle DPCDRIVER_NORMAL"); if (pSubHandle->InitSubDriverObject() == false) { //mLog::FINFO("CDI ----- DriverHandle::InitHandle InitSubDriverObject Failed"); //mLog::FERROR( "InitSubDriverObject Failed.\n"); return false; } } //Step2:do init this driver second //为Sub对象 创建Driver线程和Notify线程 if (pSubHandle->MakeDriverPaths()) { if (pSubHandle->MakeDriverSysIFsAndThreads() == false) { //DWORD errNo = GetLastError(); //mLog::FINFO("CDI ----- DriverHandle::InitHandle MakeDriverSysIFsAndThreads Failed.ErrNo {$}", errNo); //mLog::FERROR( "MakeDriverSysIFsAndThreads Failed.ErrNo:{$}\n", errNo); return false; } } else { //DWORD errNo = GetLastError(); //mLog::FINFO("CDI ----- DriverHandle::InitHandle MakeDriverPaths Failed.ErrNo {$}", errNo); //mLog::FERROR( "MakeDriverPaths Failed.ErrNo:{$}\n", errNo); return false; } //Step3:do init sub devices third if (pDevice) { //mLog::FINFO("CDI do init device Object second"); //do init device Object second if (pSubHandle->MakeDevicePaths()) { if (pSubHandle->MakeDeviceSysIFsAndThreads()) { //mLog::FINFO("CDI pSubHandle->MakeDeviceSysIFsAndThreads"); return true; } else { //DWORD errNo = GetLastError(); //std::cout << "CDI ----- DriverHandle::InitHandle MakeDeviceSysIFsAndThreads Failed.ErrNo" << errNo << std::endl; //mLog::FERROR( "MakeDeviceSysIFsAndThreads Failed.ErrNo:{$}\n", errNo); return false; } } else { //DWORD errNo = GetLastError(); //std::cout << "CDI ----- DriverHandle::InitHandle MakeDevicePaths Failed.ErrNo" << errNo << std::endl; //mLog::FERROR( "MakeDevicePaths Failed.ErrNo:{$}\n", errNo); return false; } } return true; } else { //DWORD errNo = GetLastError(); //std::cout << "CDI ----- DriverHandle::InitHandle" << errNo << std::endl; //mLog::FERROR( "SetWorkPath Failed.ErrNo:{$}\n", errNo); } } else { //DWORD errNo = GetLastError(); //std::cout << "CDI ----- DriverHandle::InitHandle Probe Info not right.ErrNo" << errNo << std::endl; //mLog::FERROR( "Probe Info not right.ErrNo:{$}\n", errNo); } } else { //DWORD errNo = GetLastError(); //std::cout << "CDI ----- DriverHandle::InitHandle Call Probe Failed.ErrNo" << errNo << std::endl; //mLog::FERROR( "Call Probe Failed.ErrNo:{$}\n",errNo); } return false; } bool DriverHandle::IsDPCMatch(LogicDriver*pDriver) { return (m_pDPC == pDriver); } /// /// 驱动统一加载入口,使用DPC /// /// /// bool DriverHandle::LoadDriver(ResDataObject &config) { string procdir; string drvpath; string root; procdir = GetProcessDirectory(); //Logger *p = GetGlobalLogger(); //mLog::FINFO("LoadDriver Begin \n"); std::cout << "------------ CDI: DriverHandle::LoadDriver ResDataObject" << std::endl; try { //load drvpath m_DrvConfig = config["CONFIGURATION"]; drvpath = (const char *)m_DrvConfig["driver"]; root = (const char*)m_DrvConfig["MajorID"]; string temp("%ROOT%"); drvpath = ReplaceSubString(drvpath, temp, procdir); m_DllFileTitle = GetFileTitle(drvpath); string FilePath = GetFileDirectory(drvpath); AddEnvPath(FilePath.c_str()); //oemdriver int oemidx = m_DrvConfig.GetFirstOf("oemdriver"); if (oemidx >= 0) { //exist string oemdrvpath = (const char *)m_DrvConfig["oemdriver"]; string temp("%ROOT%"); oemdrvpath = ReplaceSubString(oemdrvpath, temp, procdir); FilePath = GetFileDirectory(oemdrvpath); AddEnvPath(FilePath.c_str()); m_DrvConfig["oemdriver"] = oemdrvpath.c_str(); } else { m_DrvConfig.add("oemdriver", ""); } TryGetValue(m_DrvConfig, "connections", m_Connection); //mLog::FINFO("GetDriver ok \n"); } catch (ResDataObjectExption &exp) { //exp.what() //mLog::FINFO( exp.what()); //mLog::FINFO( "Unknown Exp Happened while load drvfile:{$}\n", drvpath.c_str()); return false; } catch (...) { //mLog::FINFO("Unknown Exp Happened while load drvfile:{$}\n", drvpath.c_str()); return false; } m_DllFileHandle = dlopen(drvpath.c_str(), RTLD_LAZY); std::cout << "CDI: LoadLibrary :"<< drvpath << std::endl; //mLog::FINFO("CDI: LoadLibrary {$} ", drvpath.c_str()); if (m_DllFileHandle) { //mLog::FINFO("load drvfile:{$} OK \n", drvpath.c_str()); typedef LogicDriver* (*GetDriverDPC)(); GetDriverDPC dpcfunc = (GetDriverDPC)dlsym(m_DllFileHandle, "GetDriverDPC"); const char* dlsym_error = dlerror(); if (!dlsym_error) { //mLog::FINFO("GetDriverDPC FUNC ADDR :{$} OK \n", drvpath.c_str()); //第一次调用的是OemBusUint DPC //第二次调用是真实的DPC,如ImageSave/NewModuleDPC m_pDPC =(LogicDriver*) dpcfunc(); if (m_pDPC) { //mLog::FINFO("GetDriverDPC CALL OK \n"); //取到了DPC->LogicDriver的子类 LogicDriver* pDriver = (LogicDriver*)m_pDPC; m_pDPC->SetDriverConfigFilePath(m_DriverConfigFilePath.c_str()); //m_NotifyThread.m_pDPC = m_pDPC;//init dpc notify thread if (m_pDPC->DriverEntry(m_DrvConfig)) { //mLog::FINFO("DriverEntry CALL OK \n"); std::cout << "------------ CDI: InitHandle start" << std::endl; InitLogForDPC(NULL);//for me if (InitHandle(this, m_pDPC)) { //mLog::FINFO("InitHandle CALL OK \n"); m_HandleStatus = true; m_IsRootHandle = true; //mLog::FINFO("LoadDriver Over \n"); std::cout << "------------ CDI: InitHandle ok" << std::endl; return true; //return InitLoadDynDriver(); } std::cout << "------------ CDI: InitHandle failed" << std::endl; //mLog::FINFO("lib:{$} Load Driver Failed.\n", drvpath.c_str()); } else { std::cerr << "DriverEntry failed: " << dlerror() << std::endl; } } else { std::cerr << "No DPC object returned: " << dlerror() << std::endl; } } else { std::cerr << "Cannot load symbol GetDriverDPC: " << dlsym_error << std::endl; dlclose(m_DllFileHandle); //mLog::FINFO( "lib:{$} no GetDriverDPC entry.ErrNo:{$}\n", drvpath.c_str(), errNo); } } else { std::cerr << "Cannot load library: " << dlerror() << std::endl; //mLog::FINFO("Load lib:{$} failed.ErrNo:{$}\n", drvpath.c_str(), errNo); } //mLog::FINFO("CDI: InitHandle fail\n"); std::cerr << "CDI: InitHandle fail" << std::endl; return false; } //Process:x64,x32 //StartType:ignore //LoadType:module, or new //drvtype:lead,standalone,subsystem,device //driver:dpcpath //entrysource:xxx(it must load to memory) //connection:connections bool DriverHandle::LoadDriver(const char *pConfigFilepath, bool bCommonDPC) { ResDataObject config; //Logger *p = GetGlobalLogger(); m_bCommonDPC = bCommonDPC; //NOT FINISHED YET //ignore all other shit,focus on the drvpath std::cout << "------------ CDI: DriverHandle::LoadDriver" << pConfigFilepath << std::endl; try { if (config.loadFile(pConfigFilepath) == false) { //log here return false; } m_DriverConfigFilePath = pConfigFilepath; //for file path //int idx = config["CONFIGURATION"].GetFirstOf("DRIVERCONFIGFILEPATH"); //if (idx >= 0) //{ // config["CONFIGURATION"].update("DRIVERCONFIGFILEPATH", pConfigFilepath); //} //else //{ // config["CONFIGURATION"].add("DRIVERCONFIGFILEPATH", pConfigFilepath); //} return LoadDriver(config); } catch (ResDataObjectExption &exp) { cout << "What happpend " << exp.what() << endl; //exp.what() //mLog::FERROR( exp.what()); } catch (...) { //mLog::FERROR( "Unknown Exp Happened\n"); } return false; } void DriverHandle::MakeShortPaths(string stackpath, DevTree *pDevTree, map> &ShortpathMap) { if (stackpath.size() > 0) { stackpath += "/"; } stackpath += pDevTree->GetName(); //loop drvtree size_t Size = pDevTree->size(); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*pDevTree)[i]; if (node.m_NodeType == TYPE_DEVICE) { GUID guid; string name; string shortname; LogicDevice *p = (LogicDevice *)node.m_pObject; p->GetDeviceType(guid); guid_2_string(guid, name); shortname = stackpath + string("/") + name; ShortpathMap[shortname].push_back(p); } else { //it's a tree MakeShortPaths(stackpath, (DevTree*)node.m_pObject, ShortpathMap); } } } bool DriverHandle::DynMakeDriverPaths() { //assert(0);//NOT FINISHED YET return true; } bool DriverHandle::MakeDriverPaths() { //assert(0); //子逻辑设备情况,会有多个设备,且有GUID重复的设备,所以需要map //GUID\1,GUID\2这种名字区分开来 //但是驱动对象就只有一个,就是本驱动 //路径是 本驱动::Probe+GUID //详细参照MakeDriverSysIFsAndThreads return true; } bool DriverHandle::DynMakeDevicePaths() { if (m_pDynRootDevice) { map> ShortpathMap; //loop devtree size_t Size = m_pDynRootDevice->size(); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*m_pDynRootDevice)[i]; if (node.m_NodeType == TYPE_DEVICE) { GUID guid; string name; LogicDevice *p = (LogicDevice *)node.m_pObject; p->GetDeviceType(guid); guid_2_string(guid, name); ShortpathMap[name].push_back(p); } //else //{ // //it's a driver // //the first level is equivalent to serialNo!!!!! // // major/minor/vendor/product/[serialno]/guid // MakeShortPaths(string(""), (DevTree*)node.m_pObject, ShortpathMap); //} } //loop shortpath map>::iterator iter = ShortpathMap.begin(); while (iter != ShortpathMap.end()) { if (iter->second.size() > 1) { //we have multiple same type devices in a raw for (size_t i = 0; i < iter->second.size(); i++) { string shortname = iter->first; shortname += "/"; std::stringstream strm; strm << shortname << i; m_DynRootDeviceMap[strm.str()] = (iter->second)[i]; } } else { m_DynRootDeviceMap[iter->first] = (iter->second)[0]; } ++iter; } return true; } return false; } bool DriverHandle::MakeDevicePaths() { if (m_pRootDevice) { map> ShortpathMap; //loop devtree size_t Size = m_pRootDevice->size(); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*m_pRootDevice)[i]; if (node.m_NodeType == TYPE_DEVICE) { GUID guid; string name; LogicDevice *p = (LogicDevice *)node.m_pObject; p->GetDeviceType(guid); guid_2_string(guid, name); ShortpathMap[name].push_back(p); } //else //{ // //it's a driver // //the first level is equivalent to serialNo!!!!! // // major/minor/vendor/product/[serialno]/guid // MakeShortPaths(string(""), (DevTree*)node.m_pObject, ShortpathMap); //} } //loop shortpath map>::iterator iter = ShortpathMap.begin(); while (iter != ShortpathMap.end()) { if (iter->second.size() > 1) { //we have multiple same type devices in a raw for (size_t i = 0; i < iter->second.size(); i++) { string shortname = iter->first; shortname += "/"; std::stringstream strm; strm << shortname << i; m_RootDeviceMap[strm.str()] = (iter->second)[i]; } } else { m_RootDeviceMap[iter->first] = (iter->second)[0]; } ++iter; } return true; } return false; } #define BusUnitGuidStr "{181F92D6-A546-4ACF-8EF1-2CCAA9EA974E}" bool DriverHandle::DynMakeDriverSysIFsAndThreads() { //ServerSysIF *pSys = new ServerSysIF(); //if (pSys) { //update m_AddressMap //UINT64 addr = (UINT64)((LogicDeviceSysIF*)pSys);//be careful..it's changing!!!! //m_DynAddressMap[addr] = pSys; //bind sys <-> logic //((LogicDriver*)m_pDPC)->SetSysLogicDevice((LogicDeviceSysIF*)pSys); //pSys->SetLogicDevice(((LogicDriver*)m_pDPC)); //make full device path GUID guid; string guidname; ((LogicDriver*)m_pDPC)->GetDeviceType(guid); guid_2_string(guid, guidname); ResDataObject subpath; subpath = (guidname).c_str(); string fullpath = MakeDevicePath(m_DynProbe, m_Connection, subpath).encode(); string ccosfull = MakeCcosPath(m_DynProbe, m_Connection, subpath).encode(); //map it m_DynDeviceFullPathMap[fullpath] = 0;// addr; m_CcosDynDeviceFullPathMap[ccosfull] = 0; //log config //((LogicDevice*)m_pDPC)->SetLogHandle(m_pLog); //m_NotifyThread.SetLogger(m_pDynLog); //mLog::FINFO("Set Notify Thread used DPC fullpath [{$}] ccosfull [{$}]", fullpath, ccosfull); m_NotifyThread.SetDPC(m_pDPC); return true; } return false; } /// /// 设置Driver的SysIF 和 Thread /// /// bool DriverHandle::MakeDriverSysIFsAndThreads() { std::cout << "============== CDI : DriverHandle::MakeDriverSysIFsAndThreads" << std::endl; //ServerSysIF *pSys = new ServerSysIF(); //if (pSys) { //update m_AddressMap //UINT64 addr = (UINT64)((LogicDeviceSysIF*)pSys);//be careful..it's changing!!!! //m_AddressMap[addr] = pSys; //bind sys <-> thread //bind sys <-> logic //((LogicDriver*)m_pDPC)->SetSysLogicDevice((LogicDeviceSysIF*)pSys); //pSys->SetLogicDevice(((LogicDriver*)m_pDPC)); //make full device path GUID guid; string guidname; ((LogicDriver*)m_pDPC)->GetDeviceType(guid); guid_2_string(guid, guidname); ResDataObject subpath; subpath = (guidname).c_str(); string fullpath = MakeDevicePath(m_Probe, m_Connection, subpath).encode(); string ccosfull = MakeCcosPath(m_Probe, m_Connection, subpath).encode(); //map it m_DriverFullPathMap = fullpath; m_DeviceFullPathMap[fullpath] = 0; //addr; 原来是SysIF对象地址 m_CcosDeviceFullPathMap[ccosfull] = 0; //m_NotifyThread.SetLogger(m_pLog); //mLog::FINFO("Set Notify Thread used DPC fullpath [{$}] ccosfull [{$}]", fullpath, ccosfull); m_NotifyThread.SetDPC(m_pDPC); std::cout << "============== CDI : DriverHandle::MakeDriverSysIFsAndThreads OK" << std::endl; return true; } std::cout << "============== CDI : DriverHandle::MakeDriverSysIFsAndThreads Failed" << std::endl; return false; } bool DriverHandle::DynMakeDeviceSysIFsAndThreads() { //mLog::FINFO("CDI DriverHandle::DynMakeDeviceSysIFsAndThreads"); //loop m_DeviceFullPathMap,make SysIF and attach it to logicdevice //Dual_Driver_Thread *pMainThread = NULL; map::iterator iter = m_DynRootDeviceMap.begin(); while (iter != m_DynRootDeviceMap.end()) { //mLog::FINFO("CDI DriverHandle::DynMakeDeviceSysIFsAndThreads {$}", iter->first); //ServerSysIF *pSys = new ServerSysIF(); //if (pSys) { //update m_AddressMap //UINT64 addr = (UINT64)((LogicDeviceSysIF*)pSys);//be careful..it's changing!!!! //m_DynAddressMap[addr] = pSys; /* //bind sys <-> thread if (iter->second->GetDevice_Thread_Priority() == THREAD_PRIORITY_NONE) { if (pMainThread == NULL) { pMainThread = new Dual_Driver_Thread(); pMainThread->SetLogger(m_pDynLog); } pSys->SetWorkThread(pMainThread->GetReqThread(), pMainThread->GetResThread()); pMainThread->RegistSysIFObject((LogicDeviceSysIF*)pSys); m_DynThreadMap[pMainThread].push_back(addr); } else { //create a thread for the deivce Dual_Driver_Thread *pThread = new Dual_Driver_Thread(); pThread->SetLogger(m_pDynLog); //NOT FINISHED YET //thread priority need to be set. pSys->SetWorkThread(pThread->GetReqThread(), pThread->GetResThread()); pThread->RegistSysIFObject((LogicDeviceSysIF*)pSys); m_DynThreadMap[pThread].push_back(addr); } */ //bind sys <-> logic //iter->second->SetSysLogicDevice((LogicDeviceSysIF*)pSys); //pSys->SetLogicDevice(iter->second); //make full device path ResDataObject subpath; subpath = (iter->first).c_str(); string fullpath = MakeDevicePath(m_DynProbe, m_Connection, subpath).encode(); string ccospath = MakeCcosPath(m_Probe, m_Connection, subpath).encode(); //map it GUID guid; string guidname; iter->second->GetDeviceType(guid); guid_2_string(guid, guidname); if (guidname == string(BusUnitGuidStr)) { //it's root device fullpath = (const char*)getRootpath(); } m_DynDeviceFullPathMap[fullpath] = 0;// addr; 原来是SysIf的内存指针地址 iter->second->SetClientRootID(fullpath.c_str(), ccospath.c_str()); g_DrvManager.AddDevice(iter->second->GetCcosRootPath().c_str(), iter->second); g_DrvManager.AddDevice(iter->second->GetCcosAbstractPath().c_str(), iter->second); //mLog::FINFO("CDI SetClientRootID dev {$} fullpath {$} ccospath {$} Real CCOS path [{$}]", iter->first, fullpath, ccospath, iter->second->GetCcosRootPath()); //log config //iter->second->SetLogHandle(m_pDynLog); //NOT FINISHED YET. //only device add succeed.no driver info here //这部分已经移到注册的地方,因为设备没有Ready,现在AddDevice有点太快. //((LogicDriver*)m_pDPC)->AddDevice(fullpath.c_str()); } //else //{ // std::cout << "============== CDI : DriverHandle::DynMakeDeviceSysIFsAndThreads failed" << std::endl; // //WTF? // //log here // return false; //} ++iter; } //mLog::FINFO("CDI DriverHandle::DynMakeDeviceSysIFsAndThreads ok"); return true; } /// /// 设置Device的SysIF 和 Thread /// /// bool DriverHandle::MakeDeviceSysIFsAndThreads() { //mLog::FINFO("CDI DriverHandle::MakeDeviceSysIFsAndThreads "); //loop m_DeviceFullPathMap,make SysIF and attach it to logicdevice //Dual_Driver_Thread *pMainThread = NULL; map::iterator iter = m_RootDeviceMap.begin(); while (iter != m_RootDeviceMap.end()) { //mLog::FINFO("CDI DriverHandle::MakeDeviceSysIFsAndThreads {$}", iter->first); //ServerSysIF *pSys = new ServerSysIF(); //if (pSys) { //update m_AddressMap //UINT64 addr = (UINT64)((LogicDeviceSysIF*)pSys);//be careful..it's changing!!!! //m_AddressMap[addr] = pSys; /* //bind sys <-> thread if (iter->second->GetDevice_Thread_Priority() == THREAD_PRIORITY_NONE) { if (pMainThread == NULL) { pMainThread = new Dual_Driver_Thread(); pMainThread->SetLogger(m_pLog); } pSys->SetWorkThread(pMainThread->GetReqThread(), pMainThread->GetResThread()); pMainThread->RegistSysIFObject((LogicDeviceSysIF*)pSys); m_ThreadMap[pMainThread].push_back(addr); } else { //create a thread for the deivce Dual_Driver_Thread *pThread = new Dual_Driver_Thread(); pThread->SetLogger(m_pLog); //NOT FINISHED YET //thread priority need to be set. pSys->SetWorkThread(pThread->GetReqThread(), pThread->GetResThread()); pThread->RegistSysIFObject((LogicDeviceSysIF*)pSys); m_ThreadMap[pThread].push_back(addr); } */ //bind sys <-> logic //iter->second->SetSysLogicDevice((LogicDeviceSysIF*)pSys); //pSys->SetLogicDevice(iter->second); //make full device path ResDataObject subpath; subpath = (iter->first).c_str(); string fullpath = MakeDevicePath(m_Probe, m_Connection, subpath).encode(); string ccosfull = MakeCcosPath(m_Probe, m_Connection, subpath).encode(); //map it GUID guid; string guidname; iter->second->GetDeviceType(guid); guid_2_string(guid, guidname); if (guidname == string(BusUnitGuidStr)) { //it's root device fullpath = (const char*)getRootpath(); } else { m_CcosDeviceFullPathMap[ccosfull] = 0; } m_DeviceFullPathMap[fullpath] = 0; // addr; 原来是SysIf对象地址指针 //mLog::FINFO("CDI m_DeviceFullPathMap[fullpath] = 0 fullpath {$} ccospath {$}", fullpath, ccosfull); //log config // //iter->second->SetLogHandle(m_pLog); //NOT FINISHED YET. //only device add succeed.no driver info here //这部分已经移到注册的地方,因为设备没有Ready,现在AddDevice有点太快. //((LogicDriver*)m_pDPC)->AddDevice(fullpath.c_str()); } //else //{ // std::cout << "============== CDI : DriverHandle::MakeDeviceSysIFsAndThreads failed" << std::endl; // //WTF? // //log here // return false; //} ++iter; } //mLog::FINFO("CDI DriverHandle::MakeDeviceSysIFsAndThreads ok"); return true; } bool DriverHandle::DynStartWork() { bool ret = false; //线程启动之前通知单元设备已经Ready //CompleteDynInit(true); return true; /* map>::iterator iter = m_DynThreadMap.begin(); while (iter != m_DynThreadMap.end()) { if (iter->first->StartThread() == false) { return ret; } iter++; } return true;*/ } void DriverHandle::DynStopWork() { /* bool ret = false; map>::iterator iter = m_DynThreadMap.begin(); while (iter != m_DynThreadMap.end()) { if (iter->first->StopThread() == false) { //mLog::FINFO("{$} Drv:StopThread Used Terminate!!!!!!!!!!!!!!!", m_DllFileTitle.c_str()); } iter++; }*/ //线程Stop后通知单元设备要退出 CompleteDynInit(false); } void DriverHandle::CompleteStaticInit(bool Init) { //mLog::FINFO("CDI {$}", Init); //dpc first if (m_pDPC) std::cout << "CDI m_pDPC "<< std::endl; { //mLog::FINFO("CDI m_pDPC "); if (Init) { ((LogicDriver*)m_pDPC)->CompleteInit(); } else { ((LogicDriver*)m_pDPC)->CompleteUnInit(); } std::cout << "CDI Driver CompleteInit "<< Init << std::endl; //mLog::FINFO("CDI Driver CompleteInit {$}", Init); //init this map::iterator iter = m_RootDeviceMap.begin(); while (iter != m_RootDeviceMap.end()) { //mLog::FINFO("CDI Try CompleteInit {$}", iter->first); if (Init) { iter->second->CompleteInit(); } else { iter->second->CompleteUnInit(); } //mLog::FINFO("CDI CompleteInit over."); ++iter; } //sub drivers for (size_t i = 0; i < m_hSubDriverList.Size(); i++) { //mLog::FINFO("CDI m_hSubDriverList try CompleteStaticInit {$}", i); m_hSubDriverList[i]->CompleteStaticInit(Init); } } } void DriverHandle::CompleteDynInit(bool Init) { //mLog::FINFO("CDI {$}", Init); //init this map::iterator iter = m_DynRootDeviceMap.begin(); while (iter != m_DynRootDeviceMap.end()) { std::cout << "CDI Try Dyn CompleteInit " << iter->first << std::endl; //mLog::FINFO("CDI Try Dyn CompleteInit {$}", iter->first); if (Init) { iter->second->CompleteInit(); } else { iter->second->CompleteUnInit(); } ++iter; } //sub drivers for (size_t i = 0; i < m_DynSubDriverList.Size(); i++) { //mLog::FINFO("CDI m_DynSubDriverList try CompleteStaticInit {$}", i); m_DynSubDriverList[i]->CompleteDynInit(Init); } } bool DriverHandle::StartWork() { bool ret = true; //mLog::FINFO("StartWork Begin with {$}", m_DllFileTitle); std::cout << "StartWork Begin with " << m_DllFileTitle << std::endl; //线程启动之前通知设备单元,初始化全部结束 CompleteStaticInit(true); //工作线程在卸载动态单元的时候,会有Pause通知线程的操作. //如果工作线程太快,通知线程还没有启动,工作线程已经进入Pause流程,导致死循环. //mLog::FINFO("CDI DriverHandle::StartWork m_NotifyThread.StartThread()"); m_NotifyThread.SetName((m_DllFileTitle + "_DriverHandle::Notify").c_str()); //mLog::FINFO("Start NotifyThread"); ret = m_NotifyThread.StartThread();//notify first //mLog::FINFO("Start NotifyThread over with TID=[{$}]", m_NotifyThread.GetTID()); /* map>::iterator iter = m_ThreadMap.begin(); while (iter != m_ThreadMap.end()) { printf("iter->first->StartThread() \n "); if (iter->first->StartThread() == false) { return false; } iter++; }*/ //sub drivers if (ret) { for (size_t i = 0; i < m_hSubDriverList.Size(); i++) { //mLog::FINFO("StartWork Start SubDriverList NotifyThread {$}", i); ret &= m_hSubDriverList[i]->StartWork(); //mLog::FINFO("StartWork Start SubDriverList Over NotifyThread {$}", i); if (ret == false) { return ret; } } } //mLog::FINFO("StartWork Over with {$}" , m_DllFileTitle); return ret; } void DriverHandle::StopWork() { bool ret = false; //map>::iterator iter = m_ThreadMap.begin(); /* while (iter != m_ThreadMap.end()) { if (iter->first->StopThread() == false) { //mLog::FINFO("{$} Drv:StopThread Used Terminate!!!!!!!!!!!!!!!", m_DllFileTitle.c_str()); } iter++; }*/ if (m_NotifyThread.StopThread() == false) { //mLog::FINFO("{$} Drv:StopNotifyThread Used Terminate!!!!!!!!!!!!!!!", m_DllFileTitle.c_str()); } CompleteStaticInit(false); //delete thread /* iter = m_ThreadMap.begin(); while (iter != m_ThreadMap.end()) { delete (iter->first); iter++; }*/ //mLog::FINFO("{$} Drv:delete Thread Done", m_DllFileTitle.c_str()); //mLog::FINFO("{$} Drv:StopThread Done", m_DllFileTitle.c_str()); } bool DriverHandle::DynClearDriverHandles() { vector ifList; DynGetSysIFList(ifList); g_HandleManager.ClearLocalDrvHandles(ifList); return true; } bool DriverHandle::ClearDriverHandles() { vector ifList; GetSysIFList(ifList); g_HandleManager.ClearLocalDrvHandles(ifList); return true; } bool DriverHandle::LoadDynDriver() { bool ret = false; DWORD timeout = INFINITE; string rootpath = ""; //check connection first if (((LogicDriver*)m_pDPC)->GetConnectionStatus() == false) { //mLog::FERROR( "DPC Connection is broken"); //return ret; } //after connect succed if (m_AsRootDriver == false) { rootpath = (const char*)getRootpath(); timeout = 2000; } else { rootpath = (const char*)getChannelRootpath(); } //Get logic devices //make path & work path etc //make Threads //start dyn Threads m_NotifyThread.PauseThread(); if (DynInitHandle(this, m_pDPC)) { //if (DynRegistToRoot(rootpath.c_str(),timeout)) //{ // return DynStartWork(); //} ret = true; } m_NotifyThread.ResumeThread(); return ret; } bool DriverHandle::UnloadDynDriver() { m_NotifyThread.PauseThread(); if (m_HandleStatus == true) { DynUnRegistFromRoot();//unregist from root } //stop thread DynStopWork(); //clear HandleList if (DynClearDriverHandles() == false) { //put some log here //mLog::FINFO("{$} Drv:Dyn Clear Handle Failed", m_DllFileTitle.c_str()); } //mLog::FINFO("{$} Drv:Unload DPC", m_DllFileTitle.c_str()); if (m_pDPC) { //unload devices if (m_pDynRootDevice) { //mLog::FINFO("{$} Drv:UnloadDriver", m_DllFileTitle.c_str()); m_pDPC->UnloadLogicDevices(); ((LogicDriver*)m_pDPC)->DisConnect(); m_pDynRootDevice = NULL;//suppose it deleted DPC::UnloadDriver } } //delete sysif //map::iterator iter1 = m_DynAddressMap.begin(); //while (iter1 != m_DynAddressMap.end()) //{ // delete (iter1->second); // iter1++; //} ////mLog::FINFO("%s Drv:Dyn delete sysif Done", m_DllFileTitle.c_str()); m_NotifyThread.ResumeThread(); // //clear all maps m_DynDeviceFullPathMap.clear(); m_DynRootDeviceMap.clear(); //m_DynAddressMap.clear(); //m_DynThreadMap.clear();// thread : DeviceSysIF[] //mLog::FINFO("{$} Drv:UnloadDevice Done", m_DllFileTitle.c_str()); return true; } bool DriverHandle::UnloadDriver() { //mLog::FINFO("UnloadDrv:{$}", m_DllFileTitle.c_str()); //unload sub drivers for (size_t i = 0; i < m_hSubDriverList.Size(); i++) { delete m_hSubDriverList[i]; } m_hSubDriverList.Clear(); UnloadDynDriver(); if (m_HandleStatus == true) { // root驱动卸载过程中,把自己从Channel卸载, //这个操作因为在自我毁灭过程中进行,所以已经处于加锁状态. //因为加锁,外部命令无法反馈到当前驱动模块. // if (m_AsRootDriver == false) { UnRegistFromRoot();//unregist from root } } //stop thread StopWork(); //clear HandleList if (ClearDriverHandles() == false) { //put some log here //mLog::FINFO("{$} Drv:Clear Handle Failed", m_DllFileTitle.c_str()); } //mLog::FINFO( "{$} Drv:Unload DPC", m_DllFileTitle.c_str()); if (m_pDPC) { //unload devices if (m_pRootDevice /* || m_pDPC->GetDPCType() == DPCDRIVER_MDPC*/) { //mLog::FINFO( "{$} Drv:UnloadDriver", m_DllFileTitle.c_str()); m_pDPC->UnloadDriver(); m_pRootDevice = NULL;//suppose it deleted DPC::UnloadDriver } //disconnect //m_pDPC->DisConnect(); ////mLog::FINFO( "{$} Drv:DisConnectDPC Done", m_DllFileTitle.c_str()); //only root DPC needs to be deleted if (m_IsRootHandle) { //unload dpc ReleaseDriverDPC dpcfunc = (ReleaseDriverDPC)dlsym(m_DllFileHandle, "ReleaseDriverDPC"); if (dpcfunc) { dpcfunc(m_pDPC); //mLog::FINFO("{$} Drv:ReleaseDPC Done", m_DllFileTitle.c_str()); } } //else //{ // delete m_pDPC;//不要擅自删除DPC,非ROOT DPC让驱动自行删除. //} //FreeLibrary(m_DllFileHandle); m_pDPC = NULL; } //delete sysif //map::iterator iter1 = m_AddressMap.begin(); //while (iter1 != m_AddressMap.end()) //{ // //delete (iter1->second); // iter1++; //} ////mLog::FINFO( "{$} Drv:delete sysif Done", m_DllFileTitle.c_str()); //clear all maps m_DllFileHandle = NULL; m_pRootDevice = NULL; m_pDPC = NULL; m_Probe.clear(); m_Connection.clear(); m_WorkPath = ""; m_DeviceFullPathMap.clear(); m_CcosDeviceFullPathMap.clear(); m_CcosDynDeviceFullPathMap.clear(); m_RootDeviceMap.clear(); //m_AddressMap.clear(); //m_ThreadMap.clear();// thread : DeviceSysIF[] //if (m_pLog) //{ // ReleseLogger(m_pLog); // m_pLog = NULL; //} m_HandleStatus = false; //mLog::FINFO( "{$} Drv:UnloadDriver Done", m_DllFileTitle.c_str()); return true; } bool DriverHandle::RegistToRoot(const char* RootPath, DWORD timeout) { BusUnitClient rootclient("DriverHandle_regroot"); //mLog::FINFO("Begain [{$}]", RootPath); //sublist first for (size_t i = 0; i < m_hSubDriverList.Size(); i++) { if (m_hSubDriverList[i]->RegistToRoot(RootPath, timeout) == false) { //mLog::FERROR("RegistToRoot Failed [{$}]", RootPath); return false; } } //me second if (rootclient.Open(RootPath, ACTION, timeout) == false) { //mLog::FERROR("Open Failed [{$}]", RootPath); //printf("Thread:%d,Open Failed\n", GetCurrentThreadId()); return false; } if (rootclient.GetExitFlag() == 0) { map::iterator iter = m_DeviceFullPathMap.begin(); while (iter != m_DeviceFullPathMap.end()) { string path = iter->first; UINT64 procId = (UINT64)getpid(); UINT64 addr = iter->second; string TargetType = "Device"; if (iter->first == m_DriverFullPathMap) { TargetType = "Driver"; } //regist driver //mLog::FINFO("AddDeviceDescrpt [{$}] Try [{$}]", RootPath, path); RET_STATUS ret = (RET_STATUS)rootclient.AddDeviceDescrpt(path.c_str(), TargetType.c_str(),(const char*)getLocalMachineId(), procId, addr); if (ret == RET_FAILED) { //mLog::FERROR("AddDeviceDescrpt [{$}] Failed [{$}]", RootPath, path); //log here //try updadate this driver handle //assert(0);//NOT FINISHED YET //unhook it map::iterator iterBk = m_DeviceFullPathMap.begin(); while (iterBk != iter) { if (rootclient.DelDeviceDescrpt(iterBk->first.c_str()) != RET_SUCCEED) { //log here //shit on going!!!! rootclient.Close(); return false; } ++iterBk; } rootclient.Close(); return false; } else if (ret == RET_INVALID) { return false; } ++iter; } // Ccos PATH iter = m_CcosDeviceFullPathMap.begin(); while (iter != m_CcosDeviceFullPathMap.end()) { string path = iter->first; UINT64 procId = (UINT64)getpid(); UINT64 addr = iter->second; string TargetType = "Device"; if (iter->first == m_DriverFullPathMap) { TargetType = "Driver"; } //regist driver RET_STATUS ret = (RET_STATUS)rootclient.AddDeviceDescrpt(path.c_str(), TargetType.c_str(), (const char*)getLocalMachineId(), procId, addr); if (ret == RET_FAILED) { //log here //try updadate this driver handle //assert(0);//NOT FINISHED YET //mLog::FERROR("AddDeviceDescrpt [{$}] Failed [{$}]", RootPath, path); //unhook it map::iterator iterBk = m_CcosDeviceFullPathMap.begin(); while (iterBk != iter) { if (rootclient.DelDeviceDescrpt(iterBk->first.c_str()) != RET_SUCCEED) { //log here //shit on going!!!! rootclient.Close(); return false; } ++iterBk; } rootclient.Close(); return false; } else if (ret == RET_INVALID) { return false; } ++iter; } } rootclient.Close(); RegistToDrvObject(false,true);//后执行,保证Regist成功 //mLog::FINFO("End of Success. [{$}]", RootPath); return true; } void DriverHandle::RegistToDrvObject(bool dyn, bool regist) { map::iterator iter; if (dyn) { iter = m_DynDeviceFullPathMap.begin(); while (iter != m_DynDeviceFullPathMap.end()) { string path = iter->first; //regist driver if (regist) { ((LogicDriver*)m_pDPC)->AddDevice(path.c_str()); } else { ((LogicDriver*)m_pDPC)->DelDevice(path.c_str()); } ++iter; } } else { /* if (m_pParent) { //mdpc parent exist,this is SubDPC object string path = m_DriverFullPathMap; //regist DPC2MDPC if (regist) { ((LogicDriver*)m_pParent)->AddDevice(path.c_str()); } else { ((LogicDriver*)m_pParent)->DelDevice(path.c_str()); } }*/ //go normal iter = m_DeviceFullPathMap.begin(); while (iter != m_DeviceFullPathMap.end()) { string path = iter->first; if (m_DriverFullPathMap == path) { //exept it's own driver ++iter; continue; } //regist driver if (regist) { ((LogicDriver*)m_pDPC)->AddDevice(path.c_str()); } else { ((LogicDriver*)m_pDPC)->DelDevice(path.c_str()); } ++iter; } } } bool DriverHandle::DynRegistToRoot(const char* RootPath, DWORD timeout) { BusUnitClient rootclient("DriverHandle_dyn_reg"); //me second if (rootclient.Open(RootPath, ACTION, timeout) == false) { //printf("Thread:%d,Open Failed\n", GetCurrentThreadId()); return false; } if (rootclient.GetExitFlag() == 0) { map::iterator iter = m_DynDeviceFullPathMap.begin(); while (iter != m_DynDeviceFullPathMap.end()) { string TargetType = "Device"; string path = iter->first; UINT64 procId = (UINT64)getpid(); UINT64 addr = iter->second; //regist driver if (rootclient.AddDeviceDescrpt(path.c_str(), TargetType.c_str(),(const char*)getLocalMachineId(), procId, addr) != RET_SUCCEED) { //log here //unhook it map::iterator iterBk = m_DynDeviceFullPathMap.begin(); while (iterBk != iter) { if (rootclient.DelDeviceDescrpt(iterBk->first.c_str()) != RET_SUCCEED) { //log here //shit on going!!!! rootclient.Close(); return false; } ++iterBk; } rootclient.Close(); return false; } ++iter; } iter = m_CcosDynDeviceFullPathMap.begin(); while (iter != m_CcosDynDeviceFullPathMap.end()) { string TargetType = "Device"; string path = iter->first; UINT64 procId = (UINT64)getpid(); UINT64 addr = iter->second; //regist driver if (rootclient.AddDeviceDescrpt(path.c_str(), TargetType.c_str(), (const char*)getLocalMachineId(), procId, addr) != RET_SUCCEED) { //log here //unhook it map::iterator iterBk = m_CcosDynDeviceFullPathMap.begin(); while (iterBk != iter) { if (rootclient.DelDeviceDescrpt(iterBk->first.c_str()) != RET_SUCCEED) { //log here //shit on going!!!! rootclient.Close(); return false; } ++iterBk; } rootclient.Close(); return false; } ++iter; } } rootclient.Close(); RegistToDrvObject();//后执行,保证Regist成功 return true; } bool DriverHandle::DynUnRegistFromRoot() { DWORD timeout = 0; string rootpath; BusUnitClient rootclient("DriverHandle_UnReg"); RegistToDrvObject(true,false);//先执行,不管unregist成功与否 if (m_AsRootDriver == false) { rootpath = (const char*)getRootpath(); timeout = 2000; } else { //rootpath = (const char*)getChannelRootpath(); return true;//DriverManager中已经卸载了Root在Channel中的东西 } if (m_AsRootDriver) { timeout = 2000; } else { timeout = INFINITE; } if (rootclient.Open(rootpath.c_str(), ACTION, timeout) == false) { //printf("Thread:%d,Open %s Failed\n", GetCurrentThreadId(), rootpath.c_str()); return false; } map::iterator iter = m_DynDeviceFullPathMap.begin(); while (iter != m_DynDeviceFullPathMap.end()) { string path = iter->first; //regist driver if (rootclient.DelDeviceDescrpt(path.c_str()) != RET_SUCCEED) { //log here rootclient.Close(); return false; } ++iter; } iter = m_CcosDynDeviceFullPathMap.begin(); while (iter != m_CcosDynDeviceFullPathMap.end()) { string path = iter->first; //regist driver if (rootclient.DelDeviceDescrpt(path.c_str()) != RET_SUCCEED) { //log here rootclient.Close(); return false; } ++iter; } rootclient.Close(); return true; } bool DriverHandle::UnRegistFromRoot() { DWORD timeout = 0; string rootpath; BusUnitClient rootclient("DriverHandle_unregroot"); RegistToDrvObject(false, false);//先执行,不管unregist成功与否 if (m_AsRootDriver == false) { rootpath = (const char*)getRootpath(); timeout = 2000; } else { rootpath = (const char*)getChannelRootpath(); } if (m_AsRootDriver) { timeout = 2000; } else { timeout = INFINITE; } if (rootclient.Open(rootpath.c_str(), ACTION, timeout) == false) { //printf("Thread:%d,Open %s Failed\n", GetCurrentThreadId(),rootpath.c_str()); return false; } map::iterator iter = m_DeviceFullPathMap.begin(); while (iter != m_DeviceFullPathMap.end()) { string path = iter->first; //regist driver if (rootclient.DelDeviceDescrpt(path.c_str()) != RET_SUCCEED) { //log here rootclient.Close(); return false; } ++iter; } rootclient.Close(); return true; } void DriverHandle::DynGetSysIFList(vector &ifList) { } void DriverHandle::GetSysIFList(vector &ifList) { } //------------drv manager--------------------------- DriverManager::DriverManager() { m_pRootDrvHandle = NULL; } DriverManager::~DriverManager() { if (m_pRootDrvHandle == NULL) return; UnloadDrivers(); UnloadRootDriver(); } bool DriverManager::UnRegistFromChannel(DWORD timeout) { string RootPath; string ChannelPath; BusUnitClient rootclient("DriverManager_unreg"); RootPath = (const char *)getRootpath(); ChannelPath = (const char*)getChannelRootpath(); if (RootPath == ChannelPath) { return false; } if (rootclient.Open(ChannelPath.c_str(), ACTION, timeout) == false) { //printf("Thread:%d,Open %s Failed\n", GetCurrentThreadId(), ChannelPath.c_str()); return false; } if (rootclient.DelDeviceDescrpt(RootPath.c_str()) != RET_SUCCEED) { //log here rootclient.Close(); return false; } rootclient.Close(); return true; } void DriverManager::UnloadRootDriver() { UnRegistFromChannel(500); //mLog::FINFO("UnRegistFromChannel Fnished"); Thread_Lock(); if (m_pRootDrvHandle) { //mLog::FINFO("Unload Root Driver Begin"); //vector ifList; //m_pRootDrvHandle->GetSysIFList(ifList); //UpdateSysIF(ifList,true); delete m_pRootDrvHandle; m_pRootDrvHandle = NULL; //mLog::FINFO("Unload Root Driver Done"); } Thread_UnLock(); } void DriverManager::UnloadDrivers() { while (1) { DriverHandle* pHandle = NULL; Thread_Lock(); vector::iterator iter = m_SubDriverList.begin(); if (iter != m_SubDriverList.end()) { pHandle = (*iter); iter = m_SubDriverList.erase(iter); break; } Thread_UnLock(); if (pHandle == NULL) { break; } //unload one UnloadDynDrvHandle(pHandle); UnloadDrvHandle(pHandle); } } bool DriverManager::DynLoadDriver(DriverHandle *pDrv) { bool ret = false; const char *pRoot = getRootpath(); //新流程如下. //先注册 if (pDrv->DynRegistToRoot(pRoot) && pDrv->DynStartWork()) { //后插入DPC DynAddDriver(pDrv); ret = true; } if (ret == false) { UnloadDynDrvHandle(pDrv); } return ret; } bool DriverManager::DynDriverInitLoadAll() { Thread_Lock(); int x = 0; //auto it = m_SubDriverList.begin(); //while (it != m_SubDriverList.end()) { // (*it)->InitLoadDynDriver(); // it++; // x++; //} //mLog::FINFO("Begin"); for (; x < m_SubDriverList.size(); x++) { //mLog::FINFO("SubDriverList InitLoadDynDriver {$}",x ); m_SubDriverList[x]->InitLoadDynDriver(); //mLog::FINFO("SubDriverList InitLoadDynDriver {$} over.", x); } //mLog::FINFO("End"); Thread_UnLock(); return true; } void DriverManager::DynAddDriver(DriverHandle *pDrv) { Thread_Lock(); //vector IFList; //pDrv->DynGetSysIFList(IFList); //UpdateSysIF(IFList); for (int x = 0; x < m_SubDriverList.size(); x++) { if (pDrv == m_SubDriverList[x]) return; } m_SubDriverList.push_back(pDrv); Thread_UnLock(); } void DriverManager::AddDriver(DriverHandle *pDrv) { Thread_Lock(); //vector IFList; //pDrv->GetSysIFList(IFList); //UpdateSysIF(IFList); for (int x = 0; x < m_SubDriverList.size(); x++) { if (pDrv == m_SubDriverList[x]) return; } m_SubDriverList.push_back(pDrv); Thread_UnLock(); } bool DriverManager::GetThreadsLogger(DWORD Tid, PVOID &pLogger) { Thread_Lock(); for (size_t i = 0; i < m_SubDriverList.size(); i++) { if (m_SubDriverList[i]->GetThreadsLogger(Tid, pLogger)) { Thread_UnLock(); return true; } } if (m_pRootDrvHandle) { if (m_pRootDrvHandle->GetThreadsLogger(Tid, pLogger)) { Thread_UnLock(); return true; } } Thread_UnLock(); return false; } bool DriverManager::UpdateRootDrvStatus(int Status) { bool ret = true; if (m_pRootDrvHandle) { BusUnitClient rootclient("DriverManager_UpdateRootDrvStatus"); if (rootclient.Open(getRootpath(), ACTION) == false) { //printf("Thread:%d,Open Failed\n", GetCurrentThreadId()); return false; } if (rootclient.SetDeviceStatus(Status) != RET_SUCCEED) { //printf("Thread:%d,SetDeviceStatus Failed\n", GetCurrentThreadId()); ret = false; } rootclient.Close(); //printf("Thread:%d,SetDeviceStatus Succeed\n", GetCurrentThreadId()); } return ret; } void DriverManager::AddDevice(const char* devUri, LogicDevice* pDevice) { //mLog::FINFO("Add Device {$} with {$}", devUri, pDevice->GetCcosRootPath()); m_CcosDeviceMap[devUri] = pDevice; } const char* DriverManager::GetAllDevice(void** pDevices, int& nDevNums) { m_strAllDeviceUri = ""; auto it = m_CcosDeviceMap.begin(); nDevNums = 0; while (it != m_CcosDeviceMap.end()) { m_strAllDeviceUri += it->first + ";"; pDevices[nDevNums++] = it->second; it++; } return m_strAllDeviceUri.c_str(); } bool DriverManager::LoadRootDrv() { //get busid string busId = (const char*)getLocalEbusId(); if (busId.size() == 0) { //some log here return false; } //load drv DriverHandle *pHandle = new DriverHandle(); pHandle->m_AsRootDriver = true;//need to set this string path = GetProcessDirectory() + "/" + "rootdrv.xml"; if (pHandle->LoadDriver(path.c_str(), false)) { //load succeed //printf("Load %s succeed\n", path.c_str()); //Load only device,not include driver .!!!!!! //hook it to tree map::iterator iter = pHandle->m_DeviceFullPathMap.begin(); while (iter != pHandle->m_DeviceFullPathMap.end()) { string path = iter->first; UINT64 procId = (UINT64)getpid(); UINT64 addr = iter->second; if (path == string(getRootpath())) { //make tree node if (g_DrvTree.AddTree(path.c_str(), procId, addr)) { //done //save it m_pRootDrvHandle = (pHandle); // LogicDriver *driver = m_pRootDrvHandle->GetDpcDriver(); driver->SetTreeRoot(true); driver->SetClientRootID(path.c_str(), path.c_str()+1); std::cout << "driver SetClientRootID Real CCOS path [" << path << "] from [" << driver->GetCcosRootPath() << "]" << std::endl; //mLog::FINFO("driver SetClientRootID Real CCOS path [{$}] ", path, driver->GetCcosRootPath()); //driver->SubscribeSelf(); //这个是OemBusUnit对象,可以支持Open //start it { //这里有个瑕疵: //Driver带着一个Device加载,但是Driver意义不大,故在AddTree中过滤掉. //但是SysIF中是带着Driver的地址的.... //vector ifList; //m_pRootDrvHandle->GetSysIFList(ifList); //UpdateSysIF(ifList); return m_pRootDrvHandle->StartWork(); } } } ++iter; } } //printf("Load %s failed\n", path.c_str()); delete pHandle; return false; } bool DriverManager::LoadDrv(ResDataObject &ConfigContext) { //NOT FINISHED YET assert(0); return false; } bool DriverManager::LoadDriver(const char *pConfigFilepath) { bool ret = false; DriverHandle *pHandle = new DriverHandle(); string path = pConfigFilepath; std::cout << "------------ CDI: DriverManager::LoadDriver" << pConfigFilepath << std::endl; if (pHandle->LoadDriver(path.c_str(), true)) { //load succeed const char *pRoot = getRootpath(); //save it AddDriver(pHandle);//这点比较闹心,已经注册到系统,所以... LogicDriver *pRootDriver = m_pRootDrvHandle->GetDpcDriver(); LogicDriver* pClientDriver = pHandle->GetDpcDriver(); pRootDriver->AddEbusChildren(pClientDriver, pClientDriver->GetRootPath().c_str()); //pHandle->get //start it ret = pHandle->StartWork(); if (ret) { //regist to tree ret = pHandle->RegistToRoot(pRoot); } if (ret == false) { //所以得先卸载from系统,然后再清除... UnloadDrvHandle(pHandle); } } else { delete pHandle; } return ret; } bool DriverManager::UnloadDynDrvHandle(DriverHandle *pHandle) { bool ret = false; if (pHandle) { Thread_Lock(); { //kick the SysIF from the map //vector ifList; //pHandle->DynGetSysIFList(ifList); //UpdateSysIF(ifList, true); pHandle->UnloadDynDriver(); ret = true; } Thread_UnLock(); } return ret; } bool DriverManager::UnloadDrvHandle(DriverHandle *pHandle) { bool ret = false; if (pHandle) { Thread_Lock(); vector::iterator iter = find(m_SubDriverList.begin(), m_SubDriverList.end(), pHandle); if (iter != m_SubDriverList.end()) { //do unload work //kick it from list m_SubDriverList.erase(iter); //kick the SysIF from the map //vector ifList; //pHandle->GetSysIFList(ifList); //UpdateSysIF(ifList, true); ret = true; } Thread_UnLock(); //kick the logicdevice from root delete pHandle; //if (pHandle->UnloadDriver() == false) //{ // //put some log here //} } return ret; } //return next try tick bool DriverHandle::InitLoadDynDriver() { bool ret = true; if (!m_bCommonDPC) return true; LogicDevice* pDevice = m_pDPC; if (pDevice) { LogicDriver* pDriver = (LogicDriver*)pDevice; //check connection //if (pDriver->GetConnectionStatus()) //{ // //ok // return false; //} //makesure it's disconnected //if (m_pDrvHandle) { ////mLog::FINFO("Try UnloadDynDrv "); //UnloadDynDriver(); //if (g_DrvManager.UnloadDynDrvHandle(this)) { //do the connection //mLog::FINFO("Try Connect "); //if (pDriver->Connect()) bool bret = pDriver->Connect(); //mLog::FINFO("Try LoadDynDriver with Connect Result ={$} ", bret); //if(bret) { //do load logicdevices if (LoadDynDriver()) { //mLog::FINFO("Try DrvManager::DynLoadDriver "); if (g_DrvManager.DynLoadDriver(this)) { //ok //mLog::FINFO("Try AutomaticConnect Succeed"); return true; } //mLog::FERROR("Try DrvManager::DynLoadDriver Failed"); } else { UnloadDynDriver(); } //report error here //mLog::FERROR("Try LoadDynDriver Failed"); pDriver->DisConnect(); return false; } } } } return false; }