예제 #1
0
        public static bool Initialize()
        {
            int ADLRet = -1;

            if (null != ADL.ADL_Main_Control_Create)
            {
                // Second parameter is 1: Get only the present adapters
                ADLRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
            }
            return(ADL.ADL_SUCCESS == ADLRet);
        }
예제 #2
0
        };                                                                                     // Keep everything until the miner quits.

        public static bool InitializeADL(OpenCLDevice[] mDevices)
        {
            var ADLRet           = -1;
            var NumberOfAdapters = 0;

            if (null != ADL.ADL_Main_Control_Create)
            {
                ADLRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
            }
            if (ADL.ADL_SUCCESS == ADLRet)
            {
                MainForm.Logger("Successfully initialized AMD Display Library.");
                if (null != ADL.ADL_Adapter_NumberOfAdapters_Get)
                {
                    ADL.ADL_Adapter_NumberOfAdapters_Get(ref NumberOfAdapters);
                }
                MainForm.Logger("Number of ADL Adapters: " + NumberOfAdapters.ToString());

                if (0 < NumberOfAdapters)
                {
                    ADLAdapterInfoArray OSAdapterInfoData;
                    OSAdapterInfoData = new ADLAdapterInfoArray();

                    if (null == ADL.ADL_Adapter_AdapterInfo_Get)
                    {
                        MainForm.Logger("ADL.ADL_Adapter_AdapterInfo_Get() is not available.");
                    }
                    else
                    {
                        var AdapterBuffer = IntPtr.Zero;
                        var size          = Marshal.SizeOf(OSAdapterInfoData);
                        AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
                        Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);

                        ADLRet = ADL.ADL_Adapter_AdapterInfo_Get(AdapterBuffer, size);
                        if (ADL.ADL_SUCCESS == ADLRet)
                        {
                            OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
                            bool adrenalineWorkaroundRequired = false;
                            foreach (var device in mDevices)
                            {
                                var openclDevice = device.GetComputeDevice();
                                if (device.GetVendor() == "AMD" && openclDevice.PciBusIdAMD <= 0)
                                {
                                    adrenalineWorkaroundRequired = true;
                                }
                            }
                            if (adrenalineWorkaroundRequired)
                            {
                                // workaround for Adrenalin drivers as PciBusIdAMD does not work properly.
                                MainForm.Logger("Manually matching OpenCL devices with ADL devices...");
                                List <int> taken = new List <int> {
                                };
                                foreach (var device in mDevices)
                                {
                                    var openclDevice = device.GetComputeDevice();
                                    if (device.GetVendor() == "AMD")
                                    {
                                        string boardName    = (new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]+$")).Replace(System.Text.Encoding.ASCII.GetString(openclDevice.BoardNameAMD), ""); // Drop '\0'
                                        int    boardCounter = 0;
                                        for (var i = 0; i < NumberOfAdapters; ++i)
                                        {
                                            if (OSAdapterInfoData.ADLAdapterInfo[i].AdapterName == boardName && !taken.Contains(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber))
                                            {
                                                boardCounter++;
                                            }
                                            while (i + 1 < NumberOfAdapters && OSAdapterInfoData.ADLAdapterInfo[i].BusNumber == OSAdapterInfoData.ADLAdapterInfo[i + 1].BusNumber)
                                            {
                                                ++i;
                                            }
                                        }
                                        if (boardCounter <= 1)
                                        {
                                            for (var i = 0; i < NumberOfAdapters; ++i)
                                            {
                                                if (OSAdapterInfoData.ADLAdapterInfo[i].AdapterName == boardName && !taken.Contains(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber))
                                                {
                                                    device.ADLAdapterIndex = i;
                                                    taken.Add(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber);
                                                    break;
                                                }
                                                while (i + 1 < NumberOfAdapters && OSAdapterInfoData.ADLAdapterInfo[i].BusNumber == OSAdapterInfoData.ADLAdapterInfo[i + 1].BusNumber)
                                                {
                                                    ++i;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            OpenCLDummyLbryMiner dummyMiner = new OpenCLDummyLbryMiner(device);
                                            dummyMinerList.Add(dummyMiner);
                                            dummyMiner.Start();

                                            int[] activityTotalArray = new int[NumberOfAdapters];
                                            for (var i = 0; i < NumberOfAdapters; ++i)
                                            {
                                                activityTotalArray[i] = 0;
                                            }
                                            for (var j = 0; j < 10; ++j)
                                            {
                                                for (var i = 0; i < NumberOfAdapters; ++i)
                                                {
                                                    if (OSAdapterInfoData.ADLAdapterInfo[i].AdapterName == boardName && !taken.Contains(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber))
                                                    {
                                                        ADLPMActivity OSADLPMActivityData;
                                                        OSADLPMActivityData = new ADLPMActivity();
                                                        var activityBuffer = IntPtr.Zero;
                                                        size           = Marshal.SizeOf(OSADLPMActivityData);
                                                        activityBuffer = Marshal.AllocCoTaskMem((int)size);
                                                        Marshal.StructureToPtr(OSADLPMActivityData, activityBuffer, false);

                                                        if (null != ADL.ADL_Overdrive5_CurrentActivity_Get)
                                                        {
                                                            ADLRet = ADL.ADL_Overdrive5_CurrentActivity_Get(i, activityBuffer);
                                                            if (ADL.ADL_SUCCESS == ADLRet)
                                                            {
                                                                OSADLPMActivityData    = (ADLPMActivity)Marshal.PtrToStructure(activityBuffer, OSADLPMActivityData.GetType());
                                                                activityTotalArray[i] += OSADLPMActivityData.iActivityPercent;
                                                            }
                                                        }
                                                    }
                                                    while (i + 1 < NumberOfAdapters && OSAdapterInfoData.ADLAdapterInfo[i].BusNumber == OSAdapterInfoData.ADLAdapterInfo[i + 1].BusNumber)
                                                    {
                                                        ++i;
                                                    }
                                                }
                                                System.Threading.Thread.Sleep(100);
                                            }
                                            int candidate         = -1;
                                            int candidateActivity = 0;
                                            for (var i = 0; i < NumberOfAdapters; ++i)
                                            {
                                                if (OSAdapterInfoData.ADLAdapterInfo[i].AdapterName == boardName && !taken.Contains(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber))
                                                {
                                                    if (candidate < 0 || activityTotalArray[i] > candidateActivity)
                                                    {
                                                        candidateActivity = activityTotalArray[i];
                                                        candidate         = i;
                                                    }
                                                }
                                                while (i + 1 < NumberOfAdapters && OSAdapterInfoData.ADLAdapterInfo[i].BusNumber == OSAdapterInfoData.ADLAdapterInfo[i + 1].BusNumber)
                                                {
                                                    ++i;
                                                }
                                            }
                                            device.ADLAdapterIndex = candidate;
                                            taken.Add(OSAdapterInfoData.ADLAdapterInfo[candidate].BusNumber);

                                            dummyMiner.Stop();
                                            for (int i = 0; i < 50; ++i)
                                            {
                                                if (dummyMiner.Stopped)
                                                {
                                                    break;
                                                }
                                                System.Threading.Thread.Sleep(100);
                                            }
                                            if (!dummyMiner.Stopped)
                                            {
                                                MainForm.Logger("Failed at matching OpenCL devices with ADL devices. Restarting...");
                                                System.Windows.Forms.Application.Exit();
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // Use openclDevice.PciBusIdAMD for matching.
                                foreach (var device in mDevices)
                                {
                                    var openclDevice = device.GetComputeDevice();
                                    if (device.GetVendor() == "AMD")
                                    {
                                        for (var i = 0; i < NumberOfAdapters; i++)
                                        {
                                            var IsActive = 0;
                                            if (null != ADL.ADL_Adapter_Active_Get)
                                            {
                                                ADLRet = ADL.ADL_Adapter_Active_Get(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
                                            }
                                            if (OSAdapterInfoData.ADLAdapterInfo[i].BusNumber == openclDevice.PciBusIdAMD &&
                                                (device.ADLAdapterIndex < 0 || IsActive != 0))
                                            {
                                                device.ADLAdapterIndex = OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            MainForm.Logger("ADL_Adapter_AdapterInfo_Get() returned error code " + ADLRet.ToString());
                        }

                        // Release the memory for the AdapterInfo structure
                        if (IntPtr.Zero != AdapterBuffer)
                        {
                            Marshal.FreeCoTaskMem(AdapterBuffer);
                        }
                    }
                }
                return(true);
            }
            else
            {
                MainForm.Logger("Failed to initialize AMD Display Library.");
                return(false);
            }
        }
예제 #3
0
        public static bool InitializeADL(OpenCLDevice[] pDevices)
        {
            var ADLRet           = -1;
            var NumberOfAdapters = 0;

            if (null == ADL.ADL2_Main_Control_Create ||
                null == ADL.ADL_Main_Control_Create ||
                null == ADL.ADL_Adapter_NumberOfAdapters_Get)
            {
                return(false);
            }

            if (ADL.ADL_SUCCESS == ADL.ADL2_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1, ref ADL2Context) &&
                ADL.ADL_SUCCESS == ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1))
            {
                Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage()
                {
                    OutputText = "Successfully initialized AMD Display Library."
                });
                ADL.ADL_Adapter_NumberOfAdapters_Get(ref NumberOfAdapters);

                if (0 < NumberOfAdapters)
                {
                    ADLAdapterInfoArray OSAdapterInfoData;
                    OSAdapterInfoData = new ADLAdapterInfoArray();

                    if (null == ADL.ADL_Adapter_AdapterInfo_Get)
                    {
                        Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage()
                        {
                            OutputText = "ADL.ADL_Adapter_AdapterInfo_Get() is not available."
                        });
                    }
                    else
                    {
                        var AdapterBuffer = IntPtr.Zero;
                        var size          = Marshal.SizeOf(OSAdapterInfoData);
                        AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
                        Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);

                        ADLRet = ADL.ADL_Adapter_AdapterInfo_Get(AdapterBuffer, size);
                        if (ADL.ADL_SUCCESS == ADLRet)
                        {
                            OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());

                            if (pDevices.Any(x => x.ComputeDevice.Vendor.Equals(Consts.VendorAMD) && x.ComputeDevice.PciBusIdAMD <= 0))
                            {
                                List <int> taken = new List <int>();
                                foreach (var device in pDevices.Where(x => x.ComputeDevice.Vendor.Equals(Consts.VendorAMD)))
                                {
                                    string boardName = (new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]+$")).Replace(Encoding.ASCII.GetString(device.ComputeDevice.BoardNameAMD), "");
                                    var    adapter   = OSAdapterInfoData.ADLAdapterInfo.Where(x => x.AdapterName == boardName && !taken.Contains(x.BusNumber)).FirstOrDefault();

                                    device.ADLAdapterIndex = adapter.BusNumber;
                                    taken.Add(adapter.BusNumber);

                                    setADLVersion(device);
                                }
                            }
                            else
                            {
                                foreach (var device in pDevices)
                                {
                                    if (device.ComputeDevice.Vendor.Equals(Consts.VendorAMD))
                                    {
                                        var adapterInfo = OSAdapterInfoData.ADLAdapterInfo.Where(x => x.BusNumber == device.ComputeDevice.PciBusIdAMD).FirstOrDefault();
                                        device.ADLAdapterIndex = adapterInfo.AdapterIndex;
                                    }

                                    setADLVersion(device);
                                }
                            }
                        }

                        // Release the memory for the AdapterInfo structure
                        if (IntPtr.Zero != AdapterBuffer)
                        {
                            Marshal.FreeCoTaskMem(AdapterBuffer);
                        }
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #4
0
        private bool QueryAdl()
        {
            // ADL does not get devices in order map devices by bus number
            // bus id, <name, uuid>
            var isAdlInit = true;

            var adlRet           = -1;
            var numberOfAdapters = 0;
            var adl2Control      = IntPtr.Zero;

            if (null != ADL.ADL_Main_Control_Create)
            {
                // Second parameter is 1: Get only the present adapters
                adlRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
            }
            if (ADL.ADL_SUCCESS == adlRet)
            {
                ADL.ADL_Adapter_NumberOfAdapters_Get?.Invoke(ref numberOfAdapters);
                Helpers.ConsolePrint(Tag, "Number Of Adapters: " + numberOfAdapters);

                if (0 < numberOfAdapters)
                {
                    // Get OS adpater info from ADL
                    var osAdapterInfoData = new ADLAdapterInfoArray();

                    if (null != ADL.ADL_Adapter_AdapterInfo_Get)
                    {
                        var size          = Marshal.SizeOf(osAdapterInfoData);
                        var adapterBuffer = Marshal.AllocCoTaskMem(size);
                        Marshal.StructureToPtr(osAdapterInfoData, adapterBuffer, false);

                        adlRet = ADL.ADL_Adapter_AdapterInfo_Get(adapterBuffer, size);

                        var adl2Ret = -1;
                        if (ADL.ADL2_Main_Control_Create != null)
                        {
                            adl2Ret = ADL.ADL2_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 0, ref adl2Control);
                        }

                        var adl2Info = new ADLAdapterInfoArray();
                        var size2    = Marshal.SizeOf(adl2Info);
                        var buffer   = Marshal.AllocCoTaskMem(size2);
                        if (adl2Ret == ADL.ADL_SUCCESS && ADL.ADL2_Adapter_AdapterInfo_Get != null)
                        {
                            Marshal.StructureToPtr(adl2Info, buffer, false);
                            adl2Ret = ADL.ADL2_Adapter_AdapterInfo_Get(adl2Control, buffer, Marshal.SizeOf(adl2Info));
                        }
                        else
                        {
                            adl2Ret = -1;
                        }

                        if (adl2Ret == ADL.ADL_SUCCESS)
                        {
                            adl2Info = (ADLAdapterInfoArray)Marshal.PtrToStructure(buffer, adl2Info.GetType());
                        }

                        if (ADL.ADL_SUCCESS == adlRet)
                        {
                            osAdapterInfoData =
                                (ADLAdapterInfoArray)Marshal.PtrToStructure(adapterBuffer,
                                                                            osAdapterInfoData.GetType());
                            var isActive = 0;

                            for (var i = 0; i < numberOfAdapters; i++)
                            {
                                // Check if the adapter is active
                                if (null != ADL.ADL_Adapter_Active_Get)
                                {
                                    adlRet = ADL.ADL_Adapter_Active_Get(
                                        osAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref isActive);
                                }

                                if (ADL.ADL_SUCCESS != adlRet)
                                {
                                    continue;
                                }

                                // we are looking for amd
                                // TODO check discrete and integrated GPU separation
                                var vendorID = osAdapterInfoData.ADLAdapterInfo[i].VendorID;
                                var devName  = osAdapterInfoData.ADLAdapterInfo[i].AdapterName;

                                if (vendorID != AmdVendorID && !devName.ToLower().Contains("amd") &&
                                    !devName.ToLower().Contains("radeon") &&
                                    !devName.ToLower().Contains("firepro"))
                                {
                                    continue;
                                }

                                var pnpStr = osAdapterInfoData.ADLAdapterInfo[i].PNPString;
                                // find vi controller pnp
                                var infSection = "";
                                foreach (var vCtrl in _availableControllers)
                                {
                                    if (vCtrl.PnpDeviceID == pnpStr)
                                    {
                                        infSection = vCtrl.InfSection;
                                    }
                                }

                                var backSlashLast = pnpStr.LastIndexOf('\\');
                                var serial        = pnpStr.Substring(backSlashLast, pnpStr.Length - backSlashLast);
                                var end0          = serial.IndexOf('&');
                                var end1          = serial.IndexOf('&', end0 + 1);
                                // get serial
                                serial = serial.Substring(end0 + 1, end1 - end0 - 1);

                                var       udid            = osAdapterInfoData.ADLAdapterInfo[i].UDID;
                                const int pciVenIDStrSize = 21; // PCI_VEN_XXXX&DEV_XXXX
                                var       uuid            = udid.Substring(0, pciVenIDStrSize) + "_" + serial;
                                var       budId           = osAdapterInfoData.ADLAdapterInfo[i].BusNumber;
                                var       index           = osAdapterInfoData.ADLAdapterInfo[i].AdapterIndex;

                                if (_amdDeviceUuid.Contains(uuid))
                                {
                                    continue;
                                }

                                try
                                {
                                    Helpers.ConsolePrint(Tag,
                                                         $"ADL device added BusNumber:{budId}  NAME:{devName}  UUID:{uuid}");
                                }
                                catch (Exception e)
                                {
                                    Helpers.ConsolePrint(Tag, e.Message);
                                }

                                _amdDeviceUuid.Add(uuid);
                                //_busIds.Add(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber);
                                //_amdDeviceName.Add(devName);

                                if (_busIdInfos.ContainsKey(budId))
                                {
                                    continue;
                                }

                                var adl2Index = -1;
                                if (adl2Ret == ADL.ADL_SUCCESS)
                                {
                                    adl2Index = adl2Info.ADLAdapterInfo
                                                .FirstOrDefault(a => a.UDID == osAdapterInfoData.ADLAdapterInfo[i].UDID)
                                                .AdapterIndex;
                                }

                                var info = new BusIdInfo
                                {
                                    Name       = devName,
                                    Uuid       = uuid,
                                    InfSection = infSection,
                                    Adl1Index  = index,
                                    Adl2Index  = adl2Index
                                };

                                _busIdInfos.Add(budId, info);
                            }
                        }
                        else
                        {
                            Helpers.ConsolePrint(Tag,
                                                 "ADL_Adapter_AdapterInfo_Get() returned error code " +
                                                 adlRet);
                            isAdlInit = false;
                        }

                        // Release the memory for the AdapterInfo structure
                        if (IntPtr.Zero != adapterBuffer)
                        {
                            Marshal.FreeCoTaskMem(adapterBuffer);
                        }
                        if (buffer != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(buffer);
                        }
                    }
                }

                if (null != ADL.ADL_Main_Control_Destroy && numberOfAdapters <= 0)
                {
                    // Close ADL if it found no AMD devices
                    ADL.ADL_Main_Control_Destroy();
                }
                if (ADL.ADL2_Main_Control_Destroy != null && adl2Control != IntPtr.Zero)
                {
                    ADL.ADL2_Main_Control_Destroy(adl2Control);
                }
            }
            else
            {
                // TODO
                Helpers.ConsolePrint(Tag,
                                     "ADL_Main_Control_Create() returned error code " + adlRet);
                Helpers.ConsolePrint(Tag, "Check if ADL is properly installed!");
                isAdlInit = false;
            }

            return(isAdlInit);
        }
예제 #5
0
        static void Main(string[] args)
        {
            int ADLRet           = -1;
            int NumberOfAdapters = 0;
            int NumberOfDisplays = 0;

            if (null != ADL.ADL_Main_Control_Create)
            {
                // Second parameter is 1: Get only the present adapters
                ADLRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
            }
            if (ADL.ADL_SUCCESS == ADLRet)
            {
                if (null != ADL.ADL_Adapter_NumberOfAdapters_Get)
                {
                    ADL.ADL_Adapter_NumberOfAdapters_Get(ref NumberOfAdapters);
                }
                Console.WriteLine("Number Of Adapters: " + NumberOfAdapters.ToString() + "\n");

                if (0 < NumberOfAdapters)
                {
                    // Get OS adpater info from ADL
                    ADLAdapterInfoArray OSAdapterInfoData;
                    OSAdapterInfoData = new ADLAdapterInfoArray();

                    if (null != ADL.ADL_Adapter_AdapterInfo_Get)
                    {
                        IntPtr AdapterBuffer = IntPtr.Zero;
                        int    size          = Marshal.SizeOf(OSAdapterInfoData);
                        AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
                        Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);

                        if (null != ADL.ADL_Adapter_AdapterInfo_Get)
                        {
                            ADLRet = ADL.ADL_Adapter_AdapterInfo_Get(AdapterBuffer, size);
                            if (ADL.ADL_SUCCESS == ADLRet)
                            {
                                OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
                                int IsActive = 0;

                                for (int i = 0; i < NumberOfAdapters; i++)
                                {
                                    // Check if the adapter is active
                                    if (null != ADL.ADL_Adapter_Active_Get)
                                    {
                                        ADLRet = ADL.ADL_Adapter_Active_Get(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
                                    }

                                    if (ADL.ADL_SUCCESS == ADLRet)
                                    {
                                        Console.WriteLine("Adapter is   : " + (0 == IsActive ? "DISABLED" : "ENABLED"));
                                        Console.WriteLine("Adapter Index: " + OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex.ToString());
                                        Console.WriteLine("Adapter UDID : " + OSAdapterInfoData.ADLAdapterInfo[i].UDID);
                                        Console.WriteLine("Bus No       : " + OSAdapterInfoData.ADLAdapterInfo[i].BusNumber.ToString());
                                        Console.WriteLine("Driver No    : " + OSAdapterInfoData.ADLAdapterInfo[i].DriverNumber.ToString());
                                        Console.WriteLine("Function No  : " + OSAdapterInfoData.ADLAdapterInfo[i].FunctionNumber.ToString());
                                        Console.WriteLine("Vendor ID    : " + OSAdapterInfoData.ADLAdapterInfo[i].VendorID.ToString());
                                        Console.WriteLine("Adapter Name : " + OSAdapterInfoData.ADLAdapterInfo[i].AdapterName);
                                        Console.WriteLine("Display Name : " + OSAdapterInfoData.ADLAdapterInfo[i].DisplayName);
                                        Console.WriteLine("Present      : " + (0 == OSAdapterInfoData.ADLAdapterInfo[i].Present ? "No" : "Yes"));
                                        Console.WriteLine("Exist        : " + (0 == OSAdapterInfoData.ADLAdapterInfo[i].Exist ? "No" : "Yes"));
                                        Console.WriteLine("Driver Path  : " + OSAdapterInfoData.ADLAdapterInfo[i].DriverPath);
                                        Console.WriteLine("Driver Path X: " + OSAdapterInfoData.ADLAdapterInfo[i].DriverPathExt);
                                        Console.WriteLine("PNP String   : " + OSAdapterInfoData.ADLAdapterInfo[i].PNPString);

                                        // Obtain information about displays
                                        ADLDisplayInfo oneDisplayInfo = new ADLDisplayInfo();

                                        if (null != ADL.ADL_Display_DisplayInfo_Get)
                                        {
                                            IntPtr DisplayBuffer = IntPtr.Zero;
                                            int    j             = 0;

                                            // Force the display detection and get the Display Info. Use 0 as last parameter to NOT force detection
                                            ADLRet = ADL.ADL_Display_DisplayInfo_Get(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1);
                                            if (ADL.ADL_SUCCESS == ADLRet)
                                            {
                                                List <ADLDisplayInfo> DisplayInfoData = new List <ADLDisplayInfo>();
                                                for (j = 0; j < NumberOfDisplays; j++)
                                                {
                                                    oneDisplayInfo = (ADLDisplayInfo)Marshal.PtrToStructure(new IntPtr(DisplayBuffer.ToInt32() + j * Marshal.SizeOf(oneDisplayInfo)), oneDisplayInfo.GetType());
                                                    DisplayInfoData.Add(oneDisplayInfo);
                                                }
                                                Console.WriteLine("\nTotal Number of Displays supported: " + NumberOfDisplays.ToString());
                                                Console.WriteLine("\nDispID  AdpID  Type OutType  CnctType Connected  Mapped  InfoValue DisplayName ");

                                                for (j = 0; j < NumberOfDisplays; j++)
                                                {
                                                    int    InfoValue    = DisplayInfoData[j].DisplayInfoValue;
                                                    string StrConnected = (1 == (InfoValue & 1)) ? "Yes" : "No ";
                                                    string StrMapped    = (2 == (InfoValue & 2)) ? "Yes" : "No ";
                                                    int    AdpID        = DisplayInfoData[j].DisplayID.DisplayLogicalAdapterIndex;
                                                    string StrAdpID     = (AdpID < 0) ? "--" : AdpID.ToString("d2");

                                                    Console.WriteLine(DisplayInfoData[j].DisplayID.DisplayLogicalIndex.ToString() + "        " +
                                                                      StrAdpID + "      " +
                                                                      DisplayInfoData[j].DisplayType.ToString() + "      " +
                                                                      DisplayInfoData[j].DisplayOutputType.ToString() + "      " +
                                                                      DisplayInfoData[j].DisplayConnector.ToString() + "        " +
                                                                      StrConnected + "        " +
                                                                      StrMapped + "      " +
                                                                      InfoValue.ToString("x4") + "   " +
                                                                      DisplayInfoData[j].DisplayName.ToString());
                                                }
                                                Console.WriteLine();
                                            }
                                            else
                                            {
                                                Console.WriteLine("ADL_Display_DisplayInfo_Get() returned error code " + ADLRet.ToString());
                                            }
                                            // Release the memory for the DisplayInfo structure
                                            if (IntPtr.Zero != DisplayBuffer)
                                            {
                                                Marshal.FreeCoTaskMem(DisplayBuffer);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("ADL_Adapter_AdapterInfo_Get() returned error code " + ADLRet.ToString());
                            }
                        }
                        // Release the memory for the AdapterInfo structure
                        if (IntPtr.Zero != AdapterBuffer)
                        {
                            Marshal.FreeCoTaskMem(AdapterBuffer);
                        }
                    }
                }
                if (null != ADL.ADL_Main_Control_Destroy)
                {
                    ADL.ADL_Main_Control_Destroy();
                }
            }
            else
            {
                Console.WriteLine("ADL_Main_Control_Create() returned error code " + ADLRet.ToString());
                Console.WriteLine("\nCheck if ADL is properly installed!\n");
            }

            Console.WriteLine("Press ENTER to EXIT");
            Console.ReadLine();
        }
        private void QueryAMD()
        {
            //showMessageAndStep(International.GetText("Form_Main_loadtext_AMD"));
            //var dump = new sgminer(true);

            if (ConfigManager.Instance.GeneralConfig.DeviceDetection.DisableDetectionAMD)
            {
                Helpers.ConsolePrint(TAG, "Skipping AMD device detection, settings set to disabled");
                showMessageAndStep(International.GetText("Compute_Device_Query_Manager_AMD_Query_Skip"));
                return;
            }

            #region AMD driver check, ADL returns 0
            // check the driver version bool EnableOptimizedVersion = true;
            Dictionary <string, bool> deviceDriverOld = new Dictionary <string, bool>();
            string minerPath         = MinerPaths.sgminer_5_5_0_general;
            bool   ShowWarningDialog = false;

            foreach (var vidContrllr in AvaliableVideoControllers)
            {
                Helpers.ConsolePrint(TAG, String.Format("Checking AMD device (driver): {0} ({1})", vidContrllr.Name, vidContrllr.DriverVersion));

                deviceDriverOld[vidContrllr.Name] = false;
                // TODO checking radeon drivers only?
                if ((vidContrllr.Name.Contains("AMD") || vidContrllr.Name.Contains("Radeon")) && ShowWarningDialog == false)
                {
                    Version AMDDriverVersion = new Version(vidContrllr.DriverVersion);

                    if (AMDDriverVersion.Major < 15)
                    {
                        ShowWarningDialog = true;
                        deviceDriverOld[vidContrllr.Name] = true;
                        Helpers.ConsolePrint(TAG, "WARNING!!! Old AMD GPU driver detected! All optimized versions disabled, mining " +
                                             "speed will not be optimal. Consider upgrading AMD GPU driver. Recommended AMD GPU driver version is 15.7.1.");
                    }
                    else if (AMDDriverVersion.Major == 16 && AMDDriverVersion.Minor >= 150)
                    {
                        if (MinersDownloadManager.Instance.IsMinerBinFolder())
                        {
                            // TODO why this copy?
                            string src = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" +
                                         minerPath.Split('\\')[0] + "\\" + minerPath.Split('\\')[1] + "\\kernel";

                            foreach (var file in Directory.GetFiles(src))
                            {
                                string dest = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Temp\\" + System.IO.Path.GetFileName(file);
                                if (!File.Exists(dest))
                                {
                                    File.Copy(file, dest, false);
                                }
                            }
                        }
                    }
                }
            }
            if (ConfigManager.Instance.GeneralConfig.ShowDriverVersionWarning && ShowWarningDialog == true)
            {
                Form WarningDialog = new DriverVersionConfirmationDialog();
                WarningDialog.ShowDialog();
                WarningDialog = null;
            }
            #endregion // AMD driver check

            // get platform version
            showMessageAndStep(International.GetText("Compute_Device_Query_Manager_AMD_Query"));
            if (IsOpenCLQuerrySuccess)
            {
                bool amdPlatformNumFound = false;
                foreach (var kvp in OpenCLJSONData.OCLPlatforms)
                {
                    if (kvp.Key.Contains("AMD") || kvp.Key.Contains("amd"))
                    {
                        amdPlatformNumFound        = true;
                        AMDOpenCLPlatformStringKey = kvp.Key;
                        AMDOpenCLPlatformNum       = kvp.Value;
                        Helpers.ConsolePrint(TAG, String.Format("AMD platform found: Key: {0}, Num: {1}",
                                                                AMDOpenCLPlatformStringKey,
                                                                AMDOpenCLPlatformNum.ToString()));
                        break;
                    }
                }
                if (amdPlatformNumFound)
                {
                    // get only AMD gpus
                    {
                        var amdOCLDevices = OpenCLJSONData.OCLPlatformDevices[AMDOpenCLPlatformStringKey];
                        foreach (var oclDev in amdOCLDevices)
                        {
                            if (oclDev._CL_DEVICE_TYPE.Contains("GPU"))
                            {
                                amdGpus.Add(oclDev);
                            }
                        }
                    }
                    if (amdGpus.Count == 0)
                    {
                        Helpers.ConsolePrint(TAG, "AMD GPUs count is 0");
                    }
                    else
                    {
                        Helpers.ConsolePrint(TAG, "AMD GPUs count : " + amdGpus.Count.ToString());
                        Helpers.ConsolePrint(TAG, "AMD Getting device name and serial from ADL");
                        // ADL
                        bool isAdlInit = true;
                        // ADL does not get devices in order map devices by bus number
                        // bus id, <name, uuid>
                        Dictionary <int, Tuple <string, string> > _busIdsInfo = new Dictionary <int, Tuple <string, string> >();
                        List <string> _amdDeviceName = new List <string>();
                        List <string> _amdDeviceUUID = new List <string>();
                        try {
                            int ADLRet           = -1;
                            int NumberOfAdapters = 0;
                            if (null != ADL.ADL_Main_Control_Create)
                            {
                                // Second parameter is 1: Get only the present adapters
                                ADLRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
                            }
                            if (ADL.ADL_SUCCESS == ADLRet)
                            {
                                if (null != ADL.ADL_Adapter_NumberOfAdapters_Get)
                                {
                                    ADL.ADL_Adapter_NumberOfAdapters_Get(ref NumberOfAdapters);
                                }
                                Helpers.ConsolePrint(TAG, "Number Of Adapters: " + NumberOfAdapters.ToString());

                                if (0 < NumberOfAdapters)
                                {
                                    // Get OS adpater info from ADL
                                    ADLAdapterInfoArray OSAdapterInfoData;
                                    OSAdapterInfoData = new ADLAdapterInfoArray();

                                    if (null != ADL.ADL_Adapter_AdapterInfo_Get)
                                    {
                                        IntPtr AdapterBuffer = IntPtr.Zero;
                                        int    size          = Marshal.SizeOf(OSAdapterInfoData);
                                        AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
                                        Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);

                                        if (null != ADL.ADL_Adapter_AdapterInfo_Get)
                                        {
                                            ADLRet = ADL.ADL_Adapter_AdapterInfo_Get(AdapterBuffer, size);
                                            if (ADL.ADL_SUCCESS == ADLRet)
                                            {
                                                OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
                                                int IsActive = 0;

                                                for (int i = 0; i < NumberOfAdapters; i++)
                                                {
                                                    // Check if the adapter is active
                                                    if (null != ADL.ADL_Adapter_Active_Get)
                                                    {
                                                        ADLRet = ADL.ADL_Adapter_Active_Get(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
                                                    }

                                                    if (ADL.ADL_SUCCESS == ADLRet)
                                                    {
                                                        // we are looking for amd
                                                        // TODO check discrete and integrated GPU separation
                                                        var vendorID = OSAdapterInfoData.ADLAdapterInfo[i].VendorID;
                                                        var devName  = OSAdapterInfoData.ADLAdapterInfo[i].AdapterName;
                                                        if (vendorID == AMD_VENDOR_ID ||
                                                            devName.ToLower().Contains("amd") ||
                                                            devName.ToLower().Contains("radeon") ||
                                                            devName.ToLower().Contains("firepro"))
                                                        {
                                                            string PNPStr        = OSAdapterInfoData.ADLAdapterInfo[i].PNPString;
                                                            var    backSlashLast = PNPStr.LastIndexOf('\\');
                                                            var    serial        = PNPStr.Substring(backSlashLast, PNPStr.Length - backSlashLast);
                                                            var    end_0         = serial.IndexOf('&');
                                                            var    end_1         = serial.IndexOf('&', end_0 + 1);
                                                            // get serial
                                                            serial = serial.Substring(end_0 + 1, (end_1 - end_0) - 1);

                                                            var udid = OSAdapterInfoData.ADLAdapterInfo[i].UDID;
                                                            var pciVen_id_strSize = 21; // PCI_VEN_XXXX&DEV_XXXX
                                                            var uuid  = udid.Substring(0, pciVen_id_strSize) + "_" + serial;
                                                            int budId = OSAdapterInfoData.ADLAdapterInfo[i].BusNumber;
                                                            if (!_amdDeviceUUID.Contains(uuid))
                                                            {
                                                                try {
                                                                    Helpers.ConsolePrint(TAG, String.Format("ADL device added BusNumber:{0}  NAME:{1}  UUID:{2}"),
                                                                                         budId,
                                                                                         devName,
                                                                                         uuid);
                                                                } catch { }

                                                                _amdDeviceUUID.Add(uuid);
                                                                //_busIds.Add(OSAdapterInfoData.ADLAdapterInfo[i].BusNumber);
                                                                _amdDeviceName.Add(devName);
                                                                if (!_busIdsInfo.ContainsKey(budId))
                                                                {
                                                                    var nameUuid = new Tuple <string, string>(devName, uuid);
                                                                    _busIdsInfo.Add(budId, nameUuid);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                Helpers.ConsolePrint(TAG, "ADL_Adapter_AdapterInfo_Get() returned error code " + ADLRet.ToString());
                                            }
                                        }
                                        // Release the memory for the AdapterInfo structure
                                        if (IntPtr.Zero != AdapterBuffer)
                                        {
                                            Marshal.FreeCoTaskMem(AdapterBuffer);
                                        }
                                    }
                                }
                                if (null != ADL.ADL_Main_Control_Destroy)
                                {
                                    ADL.ADL_Main_Control_Destroy();
                                }
                            }
                            else
                            {
                                // TODO
                                Helpers.ConsolePrint(TAG, "ADL_Main_Control_Create() returned error code " + ADLRet.ToString());
                                Helpers.ConsolePrint(TAG, "Check if ADL is properly installed!");
                            }
                        } catch (Exception ex) {
                            Helpers.ConsolePrint(TAG, "AMD ADL exception: " + ex.Message);
                            isAdlInit = false;
                        }
                        if (isAdlInit)
                        {
                            if (amdGpus.Count == _amdDeviceUUID.Count)
                            {
                                Helpers.ConsolePrint(TAG, "AMD OpenCL and ADL AMD query COUNTS GOOD/SAME");
                            }
                            else
                            {
                                Helpers.ConsolePrint(TAG, "AMD OpenCL and ADL AMD query COUNTS DIFFERENT/BAD");
                            }
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.AppendLine("");
                            stringBuilder.AppendLine("QueryAMD devices: ");
                            for (int i_id = 0; i_id < amdGpus.Count; ++i_id)
                            {
                                HasAMD = true;

                                int busID = amdGpus[i_id].AMD_BUS_ID;
                                if (busID != -1 && _busIdsInfo.ContainsKey(busID))
                                {
                                    var deviceName = _busIdsInfo[busID].Item1;
                                    var newAmdDev  = new AmdGpuDevice(amdGpus[i_id], deviceDriverOld[deviceName]);
                                    newAmdDev.DeviceName = deviceName;
                                    newAmdDev.UUID       = _busIdsInfo[busID].Item2;
                                    bool   isDisabledGroup    = ConfigManager.Instance.GeneralConfig.DeviceDetection.DisableDetectionAMD;
                                    string skipOrAdd          = isDisabledGroup ? "SKIPED" : "ADDED";
                                    string isDisabledGroupStr = isDisabledGroup ? " (AMD group disabled)" : "";
                                    string etherumCapableStr  = newAmdDev.IsEtherumCapable() ? "YES" : "NO";

                                    new ComputeDevice(newAmdDev, true, true);
                                    // just in case
                                    try {
                                        stringBuilder.AppendLine(String.Format("\t{0} device{1}:", skipOrAdd, isDisabledGroupStr));
                                        stringBuilder.AppendLine(String.Format("\t\tID: {0}", newAmdDev.DeviceID.ToString()));
                                        stringBuilder.AppendLine(String.Format("\t\tNAME: {0}", newAmdDev.DeviceName));
                                        stringBuilder.AppendLine(String.Format("\t\tCODE_NAME: {0}", newAmdDev.Codename));
                                        stringBuilder.AppendLine(String.Format("\t\tUUID: {0}", newAmdDev.UUID));
                                        stringBuilder.AppendLine(String.Format("\t\tMEMORY: {0}", newAmdDev.DeviceGlobalMemory.ToString()));
                                        stringBuilder.AppendLine(String.Format("\t\tETHEREUM: {0}", etherumCapableStr));
                                    } catch { }
                                }
                                else
                                {
                                    stringBuilder.AppendLine(String.Format("\tDevice not added, Bus No. {0} not found:", busID));
                                }
                            }
                            Helpers.ConsolePrint(TAG, stringBuilder.ToString());
                        }
                    }
                }
            }
        }