moving drivers to 64-bit nar ganapathy architect windows device experience group microsoft...

44
Moving Drivers To Moving Drivers To 64-Bit 64-Bit Nar Ganapathy Nar Ganapathy Architect Architect Windows Device Experience Windows Device Experience Group Group Microsoft Corporation Microsoft Corporation

Upload: osborne-wells

Post on 16-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Moving Drivers To 64-Moving Drivers To 64-BitBit

Nar GanapathyNar GanapathyArchitectArchitectWindows Device Experience Windows Device Experience GroupGroupMicrosoft CorporationMicrosoft Corporation

Page 2: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

AgendaAgenda

64 bit Windows goals64 bit Windows goals

Programming modelProgramming model

Porting guidelinesPorting guidelines

ToolsTools

Summary Summary

ResourcesResources

Call to actionCall to action

Page 3: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

64-Bit Windows Goals64-Bit Windows Goals

Supporting both Win32® 32-bit and Supporting both Win32® 32-bit and 64-bit should be simple64-bit should be simple

A single source code base for 32-bit A single source code base for 32-bit and 64-bit platformsand 64-bit platforms

Enable existing applications to scale Enable existing applications to scale to enterprise capacitiesto enterprise capacities

Enable new designs that use huge Enable new designs that use huge address space and memoryaddress space and memory

Support existing 32-bit applicationsSupport existing 32-bit applications

Page 4: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

What Is Windows What Is Windows 64-Bit Edition?64-Bit Edition?

64-bit Windows is enabled by an evolution 64-bit Windows is enabled by an evolution of the Windows programming model and of the Windows programming model and the Win32 APIthe Win32 API

LLP64 modelLLP64 model

Pointers are expanded to 64 bitsPointers are expanded to 64 bits

Memory allocation sizes are 64 bitsMemory allocation sizes are 64 bits

Longs and ints default to 32 bitsLongs and ints default to 32 bits

Specific types for 64-bit integersSpecific types for 64-bit integers

Page 5: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Why port drivers to 64-bit Why port drivers to 64-bit Windows ?Windows ?Increase device coverage for 64-bit Increase device coverage for 64-bit windowswindows

No support for 32-bit driversNo support for 32-bit driversKernel-mode drivers running in same Kernel-mode drivers running in same address space as 64-bit OSaddress space as 64-bit OS

Scaling to large systemsScaling to large systemsCan make use of larger address spaces Can make use of larger address spaces for paged/non-paged pool and system for paged/non-paged pool and system cachecache

Page 6: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

64-Bit Programming Model64-Bit Programming Model

Uses the same Win32 DDIs/APIsUses the same Win32 DDIs/APIs

Adds new explicitly sized typesAdds new explicitly sized types

Adds new integral types that match Adds new integral types that match the precision of a pointerthe precision of a pointer

Pointer Precision TypePointer Precision Type

Fixed Width TypeFixed Width Type

Most Win32 32-bit data types remain Most Win32 32-bit data types remain 32-bits32-bits

E.g., size of ULONG is 32 bitsE.g., size of ULONG is 32 bits

Pointers are 64 bitsPointers are 64 bits

Page 7: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

64-Bit Programming Model64-Bit Programming Model

Example of items expanded to 64 Example of items expanded to 64 bitsbits

Length for most memory allocationsLength for most memory allocations

CPU maskCPU mask

UnchangedUnchangedLength for I/O operationsLength for I/O operations

Unicode string lengthsUnicode string lengths

Page 8: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Fixed-Width Data TypesFixed-Width Data Types

Type nameType name What it isWhat it is

LONG32, INT32LONG32, INT32 32-bit signed32-bit signed

LONG64, INT64LONG64, INT64 64-bit signed64-bit signed

ULONG32,UINT32,ULONG32,UINT32,DWORD32DWORD32

32-bit unsigned32-bit unsigned

ULONG64,UINT64,ULONG64,UINT64,DWORD64DWORD64

64-bit unsigned64-bit unsigned

Page 9: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Pointer-Precision Data TypesPointer-Precision Data Types

Type nameType name What it isWhat it is

INT_PTR,INT_PTR,

LONG_PTRLONG_PTR

Signed Int,Signed Int,

Pointer precisionPointer precision

UINT_PTR,UINT_PTR,ULONG_PTR, ULONG_PTR, DWORD_PTRDWORD_PTR

Unsigned Int,Unsigned Int,

Pointer precisionPointer precision

SIZE_TSIZE_T Unsigned count, Unsigned count, Pointer precisionPointer precision

SSIZE_TSSIZE_T Signed count,Signed count,

Pointer precisionPointer precision

Page 10: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

IA-64 Memory LayoutIA-64 Memory Layout

User addresses range from User addresses range from 0x10000 – 0x000006FBFFFEFFFF 0x10000 – 0x000006FBFFFEFFFF

One terabyte system cacheOne terabyte system cache

16 gigabyte HyperSpace16 gigabyte HyperSpace

128 gigabyte paged pool128 gigabyte paged pool

128 gigabyte System address space 128 gigabyte System address space for kernel threads, etc. for kernel threads, etc.

8K page size8K page size

128 gigabyte non-paged pool128 gigabyte non-paged pool

Physical memory addresses are 64 bitsPhysical memory addresses are 64 bits

Page 11: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

x64 Memory Layoutx64 Memory Layout

User addresses range from User addresses range from 0x10000 – 0x000007FFFFFEFFFF 0x10000 – 0x000007FFFFFEFFFF

One terabyte system cacheOne terabyte system cache

512 gigabyte HyperSpace512 gigabyte HyperSpace

128 gigabyte paged pool128 gigabyte paged pool

128 gigabyte System address space 128 gigabyte System address space for kernel threads, etc. for kernel threads, etc.

4K page size4K page size

128 gigabyte non-paged pool128 gigabyte non-paged pool

Physical memory addresses are 64 bitsPhysical memory addresses are 64 bits

Page 12: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Coding GuidelinesCoding Guidelines

Use Windows 64-bit and 32-bit safe data Use Windows 64-bit and 32-bit safe data typestypes

Examine all pointer usage, especially Examine all pointer usage, especially pointer arithmeticpointer arithmetic

Remove inline assembly code (use Remove inline assembly code (use intrinsics or native assembly code)intrinsics or native assembly code)

Use #if defined (__AMD64__) for X64-Use #if defined (__AMD64__) for X64-specific codespecific code

No __X64__ definitionNo __X64__ definition

Use #if defined(__IA64__) for IA64-specific Use #if defined(__IA64__) for IA64-specific codecode

Build environment for x64 is AMD64Build environment for x64 is AMD64

Page 13: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Porting issues for DriversPorting issues for DriversDriver support for 32-bit and 64-bit Driver support for 32-bit and 64-bit versions of IOCTL commandsversions of IOCTL commands

DMA support DMA support For hardware that can address only 32 bits of For hardware that can address only 32 bits of physical addressphysical address

Drivers need to be WDM-compliantDrivers need to be WDM-compliantSupport Plug and Play and Power Management Support Plug and Play and Power Management

Legacy (Windows NT4) APIs not allowedLegacy (Windows NT4) APIs not allowed

Programming issuesProgramming issues

User-mode drivers need to be 64 bit alsoUser-mode drivers need to be 64 bit alsoPrint, Scan, CameraPrint, Scan, Camera

Other miscellaneous issues Other miscellaneous issues

Page 14: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

WOW64 WOW64 Windows on WindowsWindows on Windows

Runs Windows NTRuns Windows NT®® x86 binaries x86 binaries

No support for mixing of 32-bit and 64-bit No support for mixing of 32-bit and 64-bit code within a processcode within a process

User/kernel transitions are thunked to User/kernel transitions are thunked to account for structure differences and account for structure differences and transition between instruction setstransition between instruction sets

Only a few DLLs are thunked: ntdll.dll, Only a few DLLs are thunked: ntdll.dll, user.dll, gdi.dll plus a set of LPC callsuser.dll, gdi.dll plus a set of LPC calls

The rest of the DLLs are stock x86 binaries The rest of the DLLs are stock x86 binaries copied from the 32-bit release sharescopied from the 32-bit release shares

Page 15: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Support 32-Bit IOCTLSupport 32-Bit IOCTL

IOCTL structures that contain pointer- IOCTL structures that contain pointer- dependent types have different sizes dependent types have different sizes in 64-bit and 32-bit applicationsin 64-bit and 32-bit applications

Driver has to distinguish between Driver has to distinguish between IOCTLs issued from 32-bit or 64-bit IOCTLs issued from 32-bit or 64-bit threadsthreads

Driver validates the input or output Driver validates the input or output buffer lengths based on the issuer’s bit buffer lengths based on the issuer’s bit widthwidth

Page 16: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Supporting 32-Bit IOCTLSupporting 32-Bit IOCTL

Three possible solutionsThree possible solutionsAvoid having pointer types in IOCTL Avoid having pointer types in IOCTL structuresstructures

Use the API IoIs32bitProcess()Use the API IoIs32bitProcess()

Use a new bit in the Function code field Use a new bit in the Function code field of the IOCTL code for 64-bit callersof the IOCTL code for 64-bit callers

Page 17: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

32-Bit and 64-Bit IOCTL32-Bit and 64-Bit IOCTLExampleExample

IOCTL structure in header fileIOCTL structure in header file

typedef struct _IOCTL_PARAMETERS {typedef struct _IOCTL_PARAMETERS {

PVOID Addr;PVOID Addr;

SIZE_T Length;SIZE_T Length;

HANDLE Handle;HANDLE Handle;

} IOCTL_PARAMETERS, *PIOCTL_PARAMETERS;} IOCTL_PARAMETERS, *PIOCTL_PARAMETERS;

Page 18: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

32-Bit and 64-Bit IOCTL 32-Bit and 64-Bit IOCTL ExampleExample

32-bit IOCTL structure32-bit IOCTL structure////

// This structure is defined // This structure is defined

// inside the driver source code// inside the driver source code

////

typedef struct _IOCTL_PARAMETERS_32 {typedef struct _IOCTL_PARAMETERS_32 {

VOID*POINTER_32 Addr;VOID*POINTER_32 Addr;

INT32 Length;INT32 Length;

VOID*POINTER_32 Handle;VOID*POINTER_32 Handle;

} IOCTL_PARAMETERS_32, *PIOCTL_PARAMETERS_32;} IOCTL_PARAMETERS_32, *PIOCTL_PARAMETERS_32;

Page 19: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

32-Bit and 64-Bit IOCTL32-Bit and 64-Bit IOCTLExampleExample

#ifdef _WIN64#ifdef _WIN64

case IOCTL_REGISTER:case IOCTL_REGISTER:

if (IoIs32bitProcess(Irp)) {if (IoIs32bitProcess(Irp)) { /* If this is a 32 bit process */ /* If this is a 32 bit process */ params32 = params32 =

(PIOCTL_PARAMETERS_32)(Irp>AssociatedIrp.SystemBuffer);(PIOCTL_PARAMETERS_32)(Irp>AssociatedIrp.SystemBuffer);

if(irpSp->Parameters.DeviceIoControl.InputBufferLength <if(irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof(IOCTL_PARAMETERS_32)) { sizeof(IOCTL_PARAMETERS_32)) {

status = STATUS_INVALID_PARAMETER; status = STATUS_INVALID_PARAMETER; } else {} else { LocalParam.Addr = params32->Addr;LocalParam.Addr = params32->Addr;

LocalParam.Handle = params32->Handle; LocalParam.Handle = params32->Handle; LocalParam.Length = params32->Length;LocalParam.Length = params32->Length;

/* Handle the ioctl here *//* Handle the ioctl here */

status = STATUS_SUCCESS;status = STATUS_SUCCESS;Irp->IoStatus.Information = sizeof(IOCTL_PARAMETERS);Irp->IoStatus.Information = sizeof(IOCTL_PARAMETERS);

}}} else { /* 64bit process IOCTL */} else { /* 64bit process IOCTL */ -> (See Next Slide) ->-> (See Next Slide) ->

Page 20: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

32-Bit and 64-Bit IOCTL32-Bit and 64-Bit IOCTLExampleExample

<- (From Last Slide) <-<- (From Last Slide) <-

} else { /* 64bit process IOCTL */} else { /* 64bit process IOCTL */

params = (PIOCTL_PARAMETERS)params = (PIOCTL_PARAMETERS) (Irp->AssociatedIrp.SystemBuffer); (Irp->AssociatedIrp.SystemBuffer);

if if (irpSp->Parameters.DeviceIoControl.InputBufferLength(irpSp->Parameters.DeviceIoControl.InputBufferLength << sizeof(IOCTL_PARAMETERS)) { sizeof(IOCTL_PARAMETERS)) { status = STATUS_INVALID_PARAMETER; status = STATUS_INVALID_PARAMETER;

} } elseelse { { RtlCopyMemory(&LocalParam, params,RtlCopyMemory(&LocalParam, params,

sizeof(IOCTL_PARAMETERS)); sizeof(IOCTL_PARAMETERS));

/* Handle the ioctl here *//* Handle the ioctl here */ status = STATUS_SUCCESS; status = STATUS_SUCCESS;

}}Irp->IoStatus.Information = sizeof(IOCTL_PARAMETERS);Irp->IoStatus.Information = sizeof(IOCTL_PARAMETERS);

}}break;break;

Page 21: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Use New IOCTL CodeUse New IOCTL Code

Use bit in function field to indicate Use bit in function field to indicate 64-bit IOCTL64-bit IOCTL

Current IOCTL codes have five fieldsCurrent IOCTL codes have five fields

New IOCTL code has an extra bit for New IOCTL code has an extra bit for 64-bit64-bit

Device Device Type (16)Type (16)

Access Access (2)(2)

CustomCustom(1)(1)

Function Function (11)(11)

Method (2)Method (2)

Device Device Type (16)Type (16)

Access Access (2)(2)

CustomCustom(1)(1)

64-Bit64-Bit

(1)(1)FunctioFunction (10)n (10)

Method (2)Method (2)

Page 22: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

DMA SupportDMA Support

Drivers should use Drivers should use PHYSICAL_ADDRESSPHYSICAL_ADDRESS typedef to access physical addresses typedef to access physical addresses (64 bits long)(64 bits long)

Driver must treat all 64 bits as a valid Driver must treat all 64 bits as a valid physical address and not ignore top 32 bitsphysical address and not ignore top 32 bits

Drivers must use the Windows DMA APIsDrivers must use the Windows DMA APIsIoGetDmaAdapter(),IoGetDmaAdapter(),AllocateAdapterChannel(),AllocateAdapterChannel(),MapTransfer(),MapTransfer(),etc. etc.

Use new scatter/gather DMA APIsUse new scatter/gather DMA APIs

Devices with 64-bit addressing capability Devices with 64-bit addressing capability will significantly improve performancewill significantly improve performance

Page 23: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

64-Bit INF requirement64-Bit INF requirementGoal is to prevent installation of incorrect Goal is to prevent installation of incorrect driver binariesdriver binaries

Customers do not understand the difference in Customers do not understand the difference in platformsplatforms

Can use TargetOsVersion Can use TargetOsVersion Introduced in Windows XPIntroduced in Windows XPNot widely usedNot widely used

With Server 2003 SP1With Server 2003 SP1Manufacturer & Models Sections MUST be Manufacturer & Models Sections MUST be decorated for 64-bit platformsdecorated for 64-bit platforms[Manufacturer] %mycompany% = MyCompanyModels, [Manufacturer] %mycompany% = MyCompanyModels, NTamd64 [MyCompanyModels.NTamd64] %MyDev% = NTamd64 [MyCompanyModels.NTamd64] %MyDev% = mydevInstall, mydevHwidmydevInstall, mydevHwidLegacy IA64 INFs will continue to workLegacy IA64 INFs will continue to work

More information at More information at http://www.microsoft.com/whdc/driver/install/64INF_reqs.mshttp://www.microsoft.com/whdc/driver/install/64INF_reqs.mspxpx

Page 24: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Make your driver a WDM Make your driver a WDM driverdriver

Support Plug and Play and power Support Plug and Play and power managementmanagement

Most modern buses and devices support Most modern buses and devices support Plug and Play and power managementPlug and Play and power management

Key to supporting many desktop and mobile Key to supporting many desktop and mobile scenariosscenarios

Move from driver-centric to device-centric Move from driver-centric to device-centric modelmodel

Handle PnP/PM IRPs or follow miniport Handle PnP/PM IRPs or follow miniport guidelinesguidelines

More information in the DDK and at More information in the DDK and at http://www.microsoft.com/whdchttp://www.microsoft.com/whdc

Page 25: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Misc. Driver-Specific Issues Misc. Driver-Specific Issues BIOS callbacks are not allowed on BIOS callbacks are not allowed on X64X64IA-64 Systems must support ACPI 2.0 IA-64 Systems must support ACPI 2.0 64-bit Tables. More details at 64-bit Tables. More details at http://www.microsoft.com/whdc/systehttp://www.microsoft.com/whdc/system/platform/64bit/IA64_ACPI.mspxm/platform/64bit/IA64_ACPI.mspxGPT disks are supported by 64-bit GPT disks are supported by 64-bit WindowsWindowsI/O request length is limited to 32 bitsI/O request length is limited to 32 bits

Modifying IDT, GDT, System Service Modifying IDT, GDT, System Service Tables, process and thread structures Tables, process and thread structures is illegal is illegal

Enforced on X64 platforms Enforced on X64 platforms Results in a bugcheckResults in a bugcheck

Page 26: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

64-Bit Miniport Guidelines64-Bit Miniport Guidelines

Follow miniport-specific guidelines Follow miniport-specific guidelines given in the DDKgiven in the DDK

Watch out for change in PAGE_SIZE Watch out for change in PAGE_SIZE (8K on IA64, 4K on x64)(8K on IA64, 4K on x64)

IOCTL, PnP and DMA issues non-IOCTL, PnP and DMA issues non-existent for most miniportsexistent for most miniports

Pointers, polymorphic usage and Pointers, polymorphic usage and alignment issues apply to miniportsalignment issues apply to miniports

Page 27: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Pointer Size Related IssuesPointer Size Related Issues

Common across applications and Common across applications and driversdrivers

Application porting guidelines applicable Application porting guidelines applicable herehere

They areThey arePolymorphic data usage (pointer size Polymorphic data usage (pointer size related)related)

Alignment issuesAlignment issues

Constant and Macros arithmeticConstant and Macros arithmetic

Page 28: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Polymorphic Data Usage …Polymorphic Data Usage …

Don’t cast a pointer to any of: Don’t cast a pointer to any of: int, long, ULONG, DWORDint, long, ULONG, DWORD

Use Use UINT_PTRUINT_PTR and and INT_PTRINT_PTR

ImageBase = (PVOID)ImageBase = (PVOID) (( ((ULONGULONG)ImageBase | 1);)ImageBase | 1);

ImageBase = (PVOID)ImageBase = (PVOID) (( ((ULONG_PTRULONG_PTR)ImageBase | 1);)ImageBase | 1);

Should be re-written as:Should be re-written as:

Page 29: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

……Polymorphic Data UsagePolymorphic Data Usage

Use PtrToUlong() and PtrToLong() Use PtrToUlong() and PtrToLong() to truncate pointersto truncate pointers

Never cast an int or a ULONG that stores a Never cast an int or a ULONG that stores a truncated pointer back into a pointertruncated pointer back into a pointer

Be careful when computing buffer sizes; Be careful when computing buffer sizes; sizes may exceed capacity of ULONGsizes may exceed capacity of ULONG

Page 30: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

… … Polymorphic Data UsagePolymorphic Data Usage

Be careful when calling functions Be careful when calling functions that have pointer OUT parametersthat have pointer OUT parameters

void GetBufferAddress(OUT PULONG *ptr);void GetBufferAddress(OUT PULONG *ptr);{{

*ptr=0x1000100010001000;*ptr=0x1000100010001000;}}void foo()void foo(){{ ULONG bufAddress;ULONG bufAddress; //// // this call causes memory corruption// this call causes memory corruption //// GetBufferAddress((PULONG*)&bufAddress);GetBufferAddress((PULONG*)&bufAddress);}}

Page 31: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Alignment (1 of 4)Alignment (1 of 4)

IA-64 requires natural alignment for IA-64 requires natural alignment for memory references (e.g. 32-bit memory references (e.g. 32-bit accesses at a 4-byte boundary)accesses at a 4-byte boundary)

Misaligned memory references Misaligned memory references will raise an exception on IA-64 and will raise an exception on IA-64 and bugcheck the systembugcheck the system

x64 is more forgiving but alignment x64 is more forgiving but alignment required to get better performancerequired to get better performance

Use UNALIGNED macro to fix Use UNALIGNED macro to fix alignment problemsalignment problems

Page 32: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Alignment (2 Of 4)Alignment (2 Of 4)#pragma pack (1) /* also set by /Zp switch */#pragma pack (1) /* also set by /Zp switch */struct AlignSample {struct AlignSample {

ULONG size;ULONG size;void *ptr; void *ptr;

};};struct AlignSample s;struct AlignSample s;void foo(void *p) {void foo(void *p) {

*p = p;*p = p; // causes alignment fault// causes alignment fault......

}}foo((PVOID)&s.ptr);foo((PVOID)&s.ptr);

Page 33: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Alignment (3 Of 4)Alignment (3 Of 4)

Use UNALIGNED macro to fixUse UNALIGNED macro to fix

Better solution: Put 64-bit values and Better solution: Put 64-bit values and pointers at start of structurespointers at start of structures

void foo(void *p) {void foo(void *p) {

struct AlignSample s; struct AlignSample s;

*(UNALIGNED void *)&s.ptr = p; *(UNALIGNED void *)&s.ptr = p;

}}

Page 34: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Alignment (4 Of 4)Alignment (4 Of 4)

Be aware of alignment issues around Be aware of alignment issues around any structure-packing directivesany structure-packing directives

Be especially cautious of different Be especially cautious of different PACK levels used in the same headerPACK levels used in the same header

Note: RtlCopyMemory() and memcpy() Note: RtlCopyMemory() and memcpy() will not faultwill not fault

Page 35: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

More Coding IssuesMore Coding Issues

Carefully examine:Carefully examine:Explicit and implicit unions with pointersExplicit and implicit unions with pointers

Data structures stored on disk or Data structures stored on disk or exchanged with 32-bit processesexchanged with 32-bit processes

Security descriptorsSecurity descriptors

Code that deals with memory region Code that deals with memory region sizessizes

len = ptr2 – ptr1 len = ptr2 – ptr1

len could be greater than 2^32len could be greater than 2^32

Page 36: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Misc. Coding IssuesMisc. Coding Issues

Executive handles can be truncated to Executive handles can be truncated to 32-bit32-bit

Piecemeal size allocations:Piecemeal size allocations:struct foo {struct foo {

DWORD NumberOfPointers;DWORD NumberOfPointers;PVOID Pointers[1];PVOID Pointers[1];

} xx;} xx;Wrong:Wrong:malloc(sizeof(DWORD)+100*sizeof(PVOID));malloc(sizeof(DWORD)+100*sizeof(PVOID)); Correct:Correct:malloc(FIELD_OFFSET(struct foo,Pointers) malloc(FIELD_OFFSET(struct foo,Pointers) +100*sizeof(PVOID));+100*sizeof(PVOID));

Page 37: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

More Misc. Coding IssuesMore Misc. Coding Issues

Use care with hex constants, unsigned valuesUse care with hex constants, unsigned valuesFollowing assertion not true on 64-bit systemsFollowing assertion not true on 64-bit systems

~((UINT64)(PAGE_SIZE-1)) == (UINT64)~(PAGE_SIZE-1)~((UINT64)(PAGE_SIZE-1)) == (UINT64)~(PAGE_SIZE-1)

PAGE_SIZE = 0x1000UL // Unsigned Long - 32 bitsPAGE_SIZE = 0x1000UL // Unsigned Long - 32 bits

PAGE_SIZE - 1 = 0x00000fff PAGE_SIZE - 1 = 0x00000fff

LHS expression:LHS expression:// Unsigned expansion // Unsigned expansion

(UINT64)(PAGE_SIZE -1 ) = 0x0000000000000fff(UINT64)(PAGE_SIZE -1 ) = 0x0000000000000fff

~((UINT64)(PAGE_SIZE -1 ))= 0xfffffffffffff000~((UINT64)(PAGE_SIZE -1 ))= 0xfffffffffffff000

RHS expression:RHS expression:~(PAGE_SIZE-1) = 0xfffff000~(PAGE_SIZE-1) = 0xfffff000(UINT64)(~(PAGE_SIZE-1))=0x00000000fffff000(UINT64)(~(PAGE_SIZE-1))=0x00000000fffff000

HenceHence~((UINT64)(PAGE_SIZE-1))!= (UINT64)(~(PAGE_SIZE-1))~((UINT64)(PAGE_SIZE-1))!= (UINT64)(~(PAGE_SIZE-1))

Page 38: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Even More Coding IssuesEven More Coding Issues

Care with unsigned numbers as Care with unsigned numbers as subscripts:subscripts:

DWORD index = 0;DWORD index = 0;

CHAR *p;CHAR *p;

If (p[index – 1] == ‘0’) If (p[index – 1] == ‘0’) causes an access violation on IA-64!causes an access violation on IA-64!

On 32-bit machines:On 32-bit machines:p[index-1] == p[0xffffffff] == p[-1] p[index-1] == p[0xffffffff] == p[-1]

On 64-bit machines:On 64-bit machines:p[index-1] == p[0x00000000ffffffff] != p[-p[index-1] == p[0x00000000ffffffff] != p[-1]1]

Page 39: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Miscellaneous CleanupMiscellaneous Cleanup

-1 != 0xFFFFFFFF-1 != 0xFFFFFFFF0xFFFFFFFF != invalid handle0xFFFFFFFF != invalid handle

DWORD is always 32 bitsDWORD is always 32 bitsLook for DWORD variables used to store Look for DWORD variables used to store pointers or handlespointers or handles

Cast pointers to PCHAR for pointer Cast pointers to PCHAR for pointer arithmeticarithmeticptr = (PVOID)((PCHAR)ptr + ptr = (PVOID)((PCHAR)ptr + pageSize);pageSize);

Page 40: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Miscellaneous Cleanup Miscellaneous Cleanup (Contd.)(Contd.)

Use %I to print pointers in debug Use %I to print pointers in debug statementsstatements

Addresses >= 0x80000000 are not Addresses >= 0x80000000 are not necessarily kernel addressesnecessarily kernel addresses

Page 41: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Tools for developing driversTools for developing drivers

64-bit tools and development process 64-bit tools and development process very similar to 32 bitvery similar to 32 bit

DebuggerDebugger

Cross compilers in the DDKCross compilers in the DDK

Checked buildsChecked builds

Driver VerifierDriver Verifier

Page 42: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

SummarySummary

Driver Model and tools remain the Driver Model and tools remain the same for 32 bit and 64 bit same for 32 bit and 64 bit

Application porting guidelines apply Application porting guidelines apply to driversto drivers

Driver specific issues relate to Driver specific issues relate to IOCTLs, DMA and legacy DDIsIOCTLs, DMA and legacy DDIs

Page 43: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Additional InformationAdditional Information

Read 64-bit guide in the DDKRead 64-bit guide in the DDKhttp://msdn.microsoft.com/library/defaulthttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/kmarch/hh/kmarc.asp?url=/library/en-us/kmarch/hh/kmarch/Other_f910e5d8-a732-4faa-a8d2-d4deh/Other_f910e5d8-a732-4faa-a8d2-d4de021dc78d.xml.asp021dc78d.xml.asp

More HW related information More HW related information available at available at

http://www.microsoft.com/whdc/system/http://www.microsoft.com/whdc/system/platform/64bit/default.mspxplatform/64bit/default.mspx

Page 44: Moving Drivers To 64-Bit Nar Ganapathy Architect Windows Device Experience Group Microsoft Corporation

Call To ActionCall To Action

Develop WDM drivers that:Develop WDM drivers that:Support Plug and PlaySupport Plug and Play

Support Power ManagementSupport Power Management

Start coding with 64-bit safe programming Start coding with 64-bit safe programming practicespractices

Use 64-bit compiler to find problem areasUse 64-bit compiler to find problem areas

Make your devices address 64 bits of physical Make your devices address 64 bits of physical memorymemory