Microsoft MVP성태의 닷넷 이야기
닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람 [링크 복사], [링크+제목 복사],
조회: 2811
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 4개 있습니다.)
디버깅 기술: 217. WinDbg - PCI 장치 열거
; https://www.sysnet.pe.kr/2/0/13873

닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)
; https://www.sysnet.pe.kr/2/0/13877

닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람
; https://www.sysnet.pe.kr/2/0/13881

닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람
; https://www.sysnet.pe.kr/2/0/13883




C# - Port I/O를 이용한 PCI Configuration Space 정보 열람

지난 글에서,

WinDbg - PCI 장치 열거
; https://www.sysnet.pe.kr/2/0/13873

"PCI Configuration Space" 정보를 Port I/O와 Memory Mapped I/O를 이용해 조회할 수 있다고 했는데요, 이들 중 Port I/O를 이용한 방법을 지난번에 만들어 둔 device driver의 도움을 받아,

커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램
; https://www.sysnet.pe.kr/2/0/12104

C# 코드로 가져와 보겠습니다. ^^




Port를 이용한 PCI Configuration Space 영역을 읽는 방법은 다음과 같습니다.

// 우선 0xcf8 포트로 읽어낼 PCI 장치와 offset을 지정하고,
(port write), 0xcf8, 0x80000000 | (bus << 16) | (device << 11) | (function << 8) | offset

// 0xcfc 포트로 4바이트 데이터를 읽어옵니다.
(port read), 0xcfc

0xcf8 포트에 쓰는 데이터 형식은 지난 글에서도 이미지로 설명한 적이 있는데요,

pci_tree_3.png

// PCI Configuration Address Register에 쓸 데이트 포맷

bit 0~1: 00
bit 2~7: Register Offset
bit 8~10: Function Number
bit 11~15: Device Number
bit 16~23: Bus Number
bit 24~30: Reserved
bit 31: Enable Bit

Bus, Device, Function을 제외하고 Register Offset으로 할당된 비트가 6비트지만, 사실 0~1 비트도 Register offset 영역에 포함되므로 엄밀히는 8비트 영역의 주소를 지정할 수 있습니다. 즉, Port I/O를 이용한 방식에서는 CAM(Configuration Access Mechanism)의 256 바이트까지만 읽어올 수 있고 PCIe에서 확장된 4KB 영역 전체를 읽어낼 수는 없습니다.

게다가 0~1 비트가 무조건 0이라는 점에서 Register offset 주소 지정은 최소 4바이트 단위로 지정해야 한다는 것을 유의하시면 됩니다.




그리하여, PCI 장치마다 0 ~ 256 바이트만큼을 읽어낼 수 있다는 것은 알았고, Configuration Address Register의 나머지 영역에 해당하는 Bus, Device, Function (줄여서 BDF) 값을 알아내는 것이 남았는데요, 즉, 원하는 PCI 장치의 Configuration Space를 읽어오려면, 이들 값을 알고 있어야 합니다.

그래서 지난 글을 통해 PCI 장치를 열거하는 방법을 알아본 건데요,

C# - PCI 장치 열거 (레지스트리, SetupAPI)
; https://www.sysnet.pe.kr/2/0/13877

한 가지 아쉬운 점은, 레지스트리를 이용하든 / SetupAPI를 이용하든 BDF 값을 필드별로 정확히 알아낼 수는 없고 문자열로부터 추출해야 한다는 것입니다.

가령 SetupAPI의 경우 지난 글에서는 SetupDiGetDeviceProperty를 이용해 DEVPROPKEY에 해당하는 값들을 구해왔는데요,

DEVPROPKEY structure
; https://learn.microsoft.com/en-us/windows-hardware/drivers/install/devpropkey

Property Keys
; https://learn.microsoft.com/en-us/windows-hardware/drivers/install/property-keys

"Unified Device Property Model Properties"로 나열되는 적절한 DEVPROPKEY 중에는 (제가 찾아본 한계로) Device, Function 값을 알 수 있는 키는 없었습니다. 대신, SetupDiGetDeviceRegistryProperty를 이용해 SPDRP_LOCATION_INFORMATION을 이용하면 다음과 같이 문자열로 추출하는 것이 가능합니다.

// SPDRP_LOCATION_INFORMATION으로 반환한 예 (문자열)

"PCI bus 0, device 2, function 0"

참고로, 단순히 BDF 값만 알아내는 것이라면 레지스트리를 이용하는 것도 좋은 방법입니다. 실제로 Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\ 하위의 PCI 장치를 살펴보면 이런 식으로 LocationInformation 값이 주어지는데요,

@System32\drivers\pci.sys,#65536;PCI bus %1, device %2, function %3;(1,0,1)

마지막의 (1,0,1) 값이 각각 (Bus, Device, Function)을 나타냅니다.




이렇게 해서 해당 머신에 장착된 PCI 장치의 BDF 값을 열거했으면 이제 Port I/O를 이용해 Configuration Space를 읽어오는 것은 어렵지 않습니다.

static unsafe void Main(string[] args)
{
    using (KernelMemoryIO portIo = new KernelMemoryIO())
    {
        if (portIo.IsInitialized == false)
        {
            Console.WriteLine("Failed to open device");
            return;
        }

        foreach (BDF bdf in PciHelper.EnumeatePCI())
        {
            Console.WriteLine($"Bus: {bdf.Bus}, Device: {bdf.Device}, Function: {bdf.Function}");

            List<byte> bytes = new List<byte>();
            for (uint where = 0; where < 256; where += 4)
            {
                uint configCommand = CONFIG_CMD(bdf.Bus, bdf.Device, bdf.Function, where);
                portIo.Outportl(0xcf8, configCommand);

                uint data = portIo.Inportl(0xcfc, out int errorNo);

                if (errorNo != 0)
                {
                    Console.WriteLine($"Error: {errorNo}");
                    break;
                }
                else
                {
                    byte[] buffer = BitConverter.GetBytes(data);
                    bytes.AddRange(buffer);
                }
            }

            for (int i = 0; i < bytes.Count; i++)
            {
                Console.Write($"{bytes[i]:x2} ");
                if (i % 16 == 15)
                {
                    Console.WriteLine();
                }
            }

            Console.WriteLine();
        }
    }
}

위의 프로그램을 Hyper-V Gen1 VM에서 실행하면 대충 이런 결과가 나옵니다.

c:\ex> ConsoleApp1.exe
Bus: 0, Device: 7, Function: 1
86 80 10 71 07 00 00 02 01 00 01 06 00 00 80 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
...[생략]...
00 00 00 00 00 00 00 00 30 0f 00 00 00 00 00 00

Bus: 0, Device: 7, Function: 0
86 80 10 71 07 00 00 02 01 00 01 06 00 00 80 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
...[생략]...
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Bus: 0, Device: 0, Function: 0
86 80 92 71 06 00 00 02 03 00 00 06 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
...[생략]...
00 00 00 00 00 00 00 00 20 0f 00 00 00 00 00 00

참고로, 그것의 첫 64바이트는 포맷이 고정돼 있기 때문에,

pci_config_space_struct_1.png

이에 맞춰 구조체를 정의해 출력하면 좀 더 다듬어진 결과를 얻을 수 있습니다. ^^

byte[] configSpaces = bytes.ToArray();
fixed (byte* ptr = configSpaces)
{
    PCIConfigSpace pciInfo = Marshal.PtrToStructure<PCIConfigSpace>((IntPtr)ptr);
    Console.WriteLine($"VendorId: {pciInfo.VendorId:x4}");
    Console.WriteLine($"DeviceId: {pciInfo.DeviceId:x4}");
}

[System.Runtime.CompilerServices.InlineArray(3)]
public struct ClassCode
{
    private byte _element0; // public 접근을 허용하지만 실용적이지 않음
                            // 필드는 단 한 개만 정의할 수 있음
}

[StructLayout(LayoutKind.Sequential)]
public struct PCIConfigSpace
{
    public ushort VendorId;
    public ushort DeviceId;

    public ushort Command;
    public ushort Status;

    public byte RevisionId;
    public ClassCode ClassCode;

    public byte CacheLineS;
    public byte LatTimer;
    public byte HeaderType;
    public byte BIST;

    public uint BAR1;
    public uint BAR2;
    public uint BAR3;
    public uint BAR4;
    public uint BAR5;
    public uint BAR6;

    public uint CardbusCISPointer;

    public ushort SubsystemVendorId;
    public ushort SubsystemId;

    public uint ExpansionROMBaseAddress;

    public byte CapPointer;
    public byte Reserved1;
    public byte Reserved2;
    public byte Reserved3;

    public uint Reserved;

    public byte InterruptLine;
    public byte InterruptPin;
    public byte MinGnt;
    public byte MaxLat;
}

뭐, 이 정도면 (DDK 영역이 아닌) 사용자 모드의 소프트웨어 개발자에게는 차고 넘칠 정도의 정보를 가져온 것이니 굳이 ECAM 4KB 영역까지 읽어낼 필요는 없을 것 같습니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




검색하다 보니, PCI 장치 열거를 통해 해당 환경이 XBox인지 확인하는 코드가 있군요. ^^

PCI 버스 접근
; https://blog.naver.com/kgh2797/90063940615

/* Check for Xbox by identifying device at PCI 0:0:0, if it's
* 0x10de/0x02a5 then we're running on an Xbox */

WRITE_PORT_ULONG((ULONG*) 0xcf8, CONFIG_CMD(0, 0, 0));
PciId = READ_PORT_ULONG((ULONG*) 0xcfc);
if (0x02a510de == PciId)
{
    XboxMachInit(CmdLine);
}
else
{
    PcMachInit(CmdLine);
}

#define CONFIG_CMD(bus, dev_fn, where) \
 (0x80000000 | (((ULONG)(bus)) << 16) | (((dev_fn) & 0x1F) << 11) | (((dev_fn) & 0xE0) << 3) | ((where) & ~3))





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/12/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13566정성태2/27/20249529오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20248623닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/202410142Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20249632디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20249333오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/202410135닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/202410183디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/202410993오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/202410169닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20249046Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20249424Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20249633닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20249058VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20248606닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20248717닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20249809닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/202410252Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/202411219개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/202410784개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/202410449개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/202410138Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20249660닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20249325오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20249749Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20248828오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20249580VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...