diff --git a/.github/Build-with-GitHub.md b/.github/Build-with-GitHub.md new file mode 100644 index 000000000..c4a10962f --- /dev/null +++ b/.github/Build-with-GitHub.md @@ -0,0 +1,35 @@ +# Using GitHub actions for building drivers + +If you use GitHub to host your code, you can leverage [GitHub Actions](https://docs.github.com/en/actions) to create automated workflows to build your driver projects. + +`windows-2022` runner (provided by `windows-latest`) is configured with Windows Driver Kit version 22H2 and Visual Studio 2022 off the box, so most solutions can be built by running `msbuild` directly. + +```yaml +name: Build driver solution +on: + push: + branches: + - main +jobs: + build: + strategy: + matrix: + configuration: [Debug, Release] + platform: [x64] + runs-on: windows-2022 + env: + Solution_Path: path\to\driver\solution.sln + steps: + - name: Check out repository code + uses: actions/checkout@v3 + + - name: Add MSBuild to PATH + uses: microsoft/setup-msbuild@v1.0.2 + + - name: Build solution + run: | + msbuild ${{ env.Solution_Path }} -p:Configuration:${{ env.Configuration }} -p:Platform:${{ env.Platform }} + env: + Configuration: ${{ matrix.configuration }} + Platform: ${{ matrix.platform }} +``` diff --git a/.github/scripts/Build-ChangedProjects.ps1 b/.github/scripts/Build-ChangedProjects.ps1 deleted file mode 100644 index a13e3501e..000000000 --- a/.github/scripts/Build-ChangedProjects.ps1 +++ /dev/null @@ -1,34 +0,0 @@ -param ( - [array]$ChangedFiles -) - -$root = (Get-Location).Path - -# To include in CI gate -$projectSet = @{} -foreach ($file in $ChangedFiles) -{ - if (-not (Test-Path $file)) { - Write-Output "`u{2754} Changed file $file cannot be found" - continue - } - $dir = (Get-Item $file).DirectoryName - while ((-not ($slnItems = (Get-ChildItem $dir '*.sln'))) -and ($dir -ne $root)) - { - $dir = (Get-Item $dir).Parent.FullName - } - if ($dir -eq $root) - { - Write-Output "`u{2754} Changed file $file does not match a project." - continue - } - $projectName = $dir.Replace($root, '').Trim('\').Replace('\', '.').ToLower() - Write-Output "`u{1F50E} Found project [$projectName] at $dir from changed file $file" - if (-not ($projectSet.ContainsKey($projectName))) - { - $projectSet[$projectName] = $dir - } -} - -.\Build-ProjectSet -ProjectSet $projectSet - diff --git a/.github/scripts/Build-ChangedSamples.ps1 b/.github/scripts/Build-ChangedSamples.ps1 new file mode 100644 index 000000000..b669a16a0 --- /dev/null +++ b/.github/scripts/Build-ChangedSamples.ps1 @@ -0,0 +1,60 @@ +[CmdletBinding()] +param ( + [array]$ChangedFiles +) + +$Verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $Verbose = $PsBoundParameters.Get_Item('Verbose') +} + +$root = (Get-Location).Path + +# Search for samples (directories) to build +$sampleSet = @{} +$buildAll = $false +foreach ($file in $ChangedFiles) { + if (-not (Test-Path $file)) { + Write-Verbose "`u{2754} Changed file $file cannot be found" + continue + } + $dir = (Get-Item $file).DirectoryName + $filename = Split-Path $file -Leaf + + # Files that can affect how every sample is built should trigger a full build + if ($filename -eq "Build-AllSamples.ps1" -or $filename -eq "Build-Sample.ps1") { + $buildAll = $true + } + if ($dir -like "$root\.github\scripts" -or $dir -like "$root\.github\scripts\*") { + $buildAll = $true + } + if ($dir -like "$root\.github\workflows" -or $dir -like "$root\.github\workflows\*") { + $buildAll = $true + } + if ($buildAll) + { + Write-Verbose "`u{2754} Full build triggered by change in file $file" + break + } + + while ((-not ($slnItems = (Get-ChildItem $dir '*.sln'))) -and ($dir -ne $root)) { + $dir = (Get-Item $dir).Parent.FullName + } + if ($dir -eq $root) { + Write-Verbose "`u{2754} Changed file $file does not match a sample" + continue + } + $sampleName = $dir.Replace($root, '').Trim('\').Replace('\', '.').ToLower() + Write-Verbose "`u{1F50E} Found sample [$sampleName] at $dir from changed file $file" + if (-not ($sampleSet.ContainsKey($sampleName))) { + $sampleSet[$sampleName] = $dir + } +} + +if ($buildAll) { + .\Build-AllSamples -Verbose:$Verbose -LogFilesDirectory (Join-Path $root "_logs") +} +else { + .\Build-SampleSet -SampleSet $sampleSet -Verbose:$Verbose -LogFilesDirectory (Join-Path $root "_logs") +} + diff --git a/.github/workflows/Code-Scanning.yml b/.github/workflows/Code-Scanning.yml new file mode 100644 index 000000000..c3094b4b1 --- /dev/null +++ b/.github/workflows/Code-Scanning.yml @@ -0,0 +1,60 @@ +# This workflow runs the latest CodeQL CLI and checks against CodeQL's Cpp library. +# This is the source for the GitHub Security Code Scanning job. + +name: "CodeQL Analysis" + +on: + push: + branches: + - main + - develop + pull_request: + # The branches below must be a subset of the branches above + branches: + - main + - develop + + # Allow manual scheduling + workflow_dispatch: + +jobs: + analyze: + name: Analysis + runs-on: windows-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'cpp' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: 'recursive' + + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + + - name: Add MSBuild to PATH + uses: microsoft/setup-msbuild@v1.0.2 + + - name: Retrieve and build all available solutions + id: build-all-samples + run: | + .\Build-AllSamples.ps1 -Verbose -ThrottleLimit 1 + env: + WDS_Configuration: Debug + WDS_Platform: x64 + WDS_WipeOutputs: ${{ true }} + + - name: Perform CodeQL analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/ci-pr.yml b/.github/workflows/ci-pr.yml index 931df9e4d..147bd4e2d 100644 --- a/.github/workflows/ci-pr.yml +++ b/.github/workflows/ci-pr.yml @@ -15,8 +15,6 @@ jobs: configuration: [Debug, Release] platform: [x64, arm64] runs-on: windows-2022 - env: - Solution_Path: general\echo\kmdf\kmdfecho.sln steps: - name: Check out repository code uses: actions/checkout@v3 @@ -28,13 +26,15 @@ jobs: - name: Get changed files id: get-changed-files - uses: tj-actions/changed-files@v27 + uses: tj-actions/changed-files@v35 + with: + separator: "," - name: Retrieve and build solutions from changed files - id: build-changed-projects + id: build-changed-samples run: | - $changedFiles = "${{ steps.get-changed-files.outputs.all_changed_files }}".Split(' ') - .\.github\scripts\Build-ChangedProjects.ps1 -ChangedFiles $changedFiles + $changedFiles = "${{ steps.get-changed-files.outputs.all_changed_files }}".Split(',') + .\.github\scripts\Build-ChangedSamples.ps1 -ChangedFiles $changedFiles -Verbose env: - Configuration: ${{ matrix.configuration }} - Platform: ${{ matrix.platform }} + WDS_Configuration: ${{ matrix.configuration }} + WDS_Platform: ${{ matrix.platform }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c07460a7..6b97cfff1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,8 +15,6 @@ jobs: configuration: [Debug, Release] platform: [x64, arm64] runs-on: windows-2022 - env: - Solution_Path: general\echo\kmdf\kmdfecho.sln steps: - name: Check out repository code uses: actions/checkout@v3 @@ -27,9 +25,9 @@ jobs: uses: microsoft/setup-msbuild@v1.0.2 - name: Retrieve and build all available solutions - id: build-all-projects + id: build-all-samples run: | - .\Build-AllProjects.ps1 + .\Build-AllSamples.ps1 -Verbose env: - Configuration: ${{ matrix.configuration }} - Platform: ${{ matrix.platform }} + WDS_Configuration: ${{ matrix.configuration }} + WDS_Platform: ${{ matrix.platform }} diff --git a/Build-AllProjects.ps1 b/Build-AllProjects.ps1 deleted file mode 100644 index 1c35d884e..000000000 --- a/Build-AllProjects.ps1 +++ /dev/null @@ -1,15 +0,0 @@ -$root = Get-Location -$solutionFiles = Get-ChildItem -Path $root -Recurse -Filter *.sln | Select-Object -ExpandProperty FullName - -# To include in CI gate -$projectSet = @{} -foreach ($file in $solutionFiles) -{ - $dir = (Get-Item $file).DirectoryName - $dir_norm = $dir.Replace($root, '').Trim('\').Replace('\', '.').ToLower() - Write-Output "`u{1F50E} Found project [$dir_norm] at $dir" - $projectSet[$dir_norm] = $dir -} - -.\Build-ProjectSet -ProjectSet $projectSet - diff --git a/Build-AllSamples.ps1 b/Build-AllSamples.ps1 new file mode 100644 index 000000000..24113c5fd --- /dev/null +++ b/Build-AllSamples.ps1 @@ -0,0 +1,68 @@ +<# +.SYNOPSIS +Builds all available sample solutions in the repository (excluding specific solutions). + +.DESCRIPTION +This script searches for all available Visual Studio Solutions (.sln files) and attempts to run MSBuild to build them for the specified configurations and platforms. + +.PARAMETER Samples +A regular expression matching the samples to be built. Default is '' that matches all samples. Examples include '^tools.' or '.dchu'. + +.PARAMETER Configurations +A list of configurations to build samples under. Values available are 'Debug' and 'Release'. By default, $env:WDS_Configuration will be used as the sole configuration to build for. If this environment variable is not set the default is 'Debug' and 'Release'. + +.PARAMETER Platforms +A list of platforms to build samples under (e.g. 'x64', 'arm64'). By default, $env:WDS_Platform will be used as the sole platform to build for. If this environment variable is not set the default is 'x64' and'arm64'. + +.PARAMETER LogFilesDirectory +Path to a directory where the log files will be written to. If not provided, outputs will be logged to the '_logs' directory within the current working directory. + +.PARAMETER ThrottleLimit +An integer indicating how many combinations to build in parallel. If 0 or not provided this defaults to 5 x number of logical processors. + +.INPUTS +None. + +.OUTPUTS +None. + +.EXAMPLE +.\Build-AllSamples + +.EXAMPLE +.\Build-AllSamples -Samples '^tools.' -Configurations 'Debug','Release' -Platforms 'x64','arm64' + +#> + +[CmdletBinding()] +param( + [string]$Samples = "", + [string[]]$Configurations = @(if ([string]::IsNullOrEmpty($env:WDS_Configuration)) { ('Debug', 'Release') } else { $env:WDS_Configuration }), + [string[]]$Platforms = @(if ([string]::IsNullOrEmpty($env:WDS_Platform)) { ('x64', 'arm64') } else { $env:WDS_Platform }), + [string]$LogFilesDirectory = (Join-Path (Get-Location) "_logs"), + [int]$ThrottleLimit +) + +$Verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $Verbose = $PsBoundParameters.Get_Item('Verbose') +} + +$root = Get-Location +$solutionFiles = Get-ChildItem -Path $root -Recurse -Filter *.sln | Select-Object -ExpandProperty FullName + +# To include in CI gate +$sampleSet = @{} +foreach ($file in $solutionFiles) { + $dir = (Get-Item $file).DirectoryName + $dir_norm = $dir.Replace($root, '').Trim('\').Replace('\', '.').ToLower() + if ($dir_norm -match ($Samples)) { + Write-Verbose "`u{1F50E} Found and included sample [$dir_norm] at $dir" + $sampleSet[$dir_norm] = $dir + } + else { + Write-Verbose "`u{1F50E} Found and excluded sample [$dir_norm] at $dir" + } +} + +.\Build-SampleSet -SampleSet $sampleSet -Configurations $Configurations -Platform $Platforms -LogFilesDirectory $LogFilesDirectory -Verbose:$Verbose -ThrottleLimit $ThrottleLimit diff --git a/Build-Project.ps1 b/Build-Project.ps1 deleted file mode 100644 index b01d13a8a..000000000 --- a/Build-Project.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -param( - $Directory, - [string]$ProjectName, - $LogFilesDirectory = "_logfiles", - [string]$Configuration = "Debug", - [string]$Platform = "x64" -) - -# TODO Validate $Directory and $LogFilesDirectory -New-Item -ItemType Directory -Force -Path $LogFilesDirectory | Out-Null - -if ([string]::IsNullOrWhitespace($ProjectName)) -{ - $ProjectName = (Resolve-Path $Directory).Path.Replace((Get-Location), '').Replace('\', '.').Trim('.').ToLower() -} - -$solutionFile = Get-ChildItem -Path $Directory -Filter *.sln | Select-Object -ExpandProperty FullName -First 1 - -$configurationIsSupported = $false -$inSolutionConfigurationPlatformsSection = $false -foreach ($line in Get-Content -Path $solutionFile) -{ - if (-not $inSolutionConfigurationPlatformsSection -and $line -match "\s*GlobalSection\(SolutionConfigurationPlatforms\).*") - { - $inSolutionConfigurationPlatformsSection = $true; - continue; - } - elseif ($line -match "\s*EndGlobalSection.*") - { - $inSolutionConfigurationPlatformsSection = $false; - continue; - } - - if ($inSolutionConfigurationPlatformsSection) - { - [regex]$regex = ".*=\s*(?(?.*)\|(?.*))\s*" - $match = $regex.Match($line) - if ([string]::IsNullOrWhiteSpace($match.Groups["ConfigString"].Value) -or [string]::IsNullOrWhiteSpace($match.Groups["Platform"].Value)) - { - Write-Warning "Could not parse configuration entry $line from file $solutionFile." - continue; - } - if ($match.Groups["Configuration"].Value.Trim() -eq $Configuration -and $match.Groups["Platform"].Value.Trim() -eq $Platform) - { - $configurationIsSupported = $true; - } - } -} - -if (-not $configurationIsSupported) -{ - Write-Output "[$ProjectName] `u{23E9} Skipped. Configuration $Configuration|$Platform not supported." - exit 0 -} - -$errorLogFilePath = "$LogFilesDirectory\$ProjectName.err" -$warnLogFilePath = "$LogFilesDirectory\$ProjectName.wrn" -Write-Output "[$ProjectName] `u{2692} Building project..." -msbuild $solutionFile -clp:Verbosity=m -t:clean,build -property:Configuration=$Configuration -property:Platform=$Platform -p:TargetVersion=Windows10 -p:InfVerif_AdditionalOptions="/msft /sw1205 /sw1324 /sw1420 /sw1421" -p:SignToolWS=/fdws -p:DriverCFlagAddOn=/wd4996 -flp1:errorsonly`;logfile=$errorLogFilePath -flp2:WarningsOnly`;logfile=$warnLogFilePath -noLogo -if ($LASTEXITCODE -ne 0) -{ - Write-Warning "`u{274C} Build failed. Log available at $errorLogFilePath" - exit 1 -} diff --git a/Build-ProjectSet.ps1 b/Build-ProjectSet.ps1 deleted file mode 100644 index 2557b5b98..000000000 --- a/Build-ProjectSet.ps1 +++ /dev/null @@ -1,65 +0,0 @@ -param( - [hashtable]$ProjectSet, - [string]$Configuration = $env:Configuration, - [string]$Platform = $env:Platform -) - -if ([string]::IsNullOrEmpty($Configuration)) -{ - $Configuration = "Debug" -} - -if ([string]::IsNullOrEmpty($Platform)) -{ - $Platform = "x64" -} - -$oldPreference = $ErrorActionPreference -$ErrorActionPreference = "stop" -try -{ - # Check that msbuild can be called before trying anything. - Get-Command "msbuild" | Out-Null -} -catch -{ - Write-Host "`u{274C} msbuild cannot be called from current environment. Check that msbuild is set in current path (for example, that it is called from a Visual Studio developer command)." - Write-Error "msbuild cannot be called from current environment." - exit 1 -} -finally -{ - $ErrorActionPreference = $oldPreference -} - - -$exclusionsSet = @{} -$failSet = @() -Import-Csv 'exclusions.csv' | ForEach-Object { - $exclusionsSet[$_.Path.Replace($root, '').Trim('\').Replace('\', '.').ToLower()] = $_.Reason -} - -$ProjectSet.GetEnumerator() | ForEach-Object { - $projectName = $_.Key - if ($exclusionsSet.ContainsKey($projectName)) - { - Write-Output "[$projectName] `u{23E9} Excluded and skipped. Reason: $($exclusionsSet[$projectName])" - return; - } - $directory = $_.Value - .\Build-Project -Directory $directory -ProjectName $ProjectName -Configuration $Configuration -Platform $Platform - if ($LASTEXITCODE -ne 0) - { - $failSet += $ProjectName - } -} - -if ($failSet.Count -gt 0) -{ - Write-Output "Some projects were built with errors:" - foreach ($failedProject in $failSet) - { - Write-Output "$failedProject" - } - Write-Error "Some projects were built with errors." -} \ No newline at end of file diff --git a/Build-Sample.ps1 b/Build-Sample.ps1 new file mode 100644 index 000000000..4f8f5b0b4 --- /dev/null +++ b/Build-Sample.ps1 @@ -0,0 +1,159 @@ +<# +.SYNOPSIS +Builds an specific directory containing a sample solution. + +.DESCRIPTION +This script attempts to build a directory containing a driver sample Solution for the specified configurations and platforms. + +.PARAMETER Directory +Path to a directory containing a valid Visual Studio Solution (.sln file). This is the solution that will be built. + +.PARAMETER SampleName +A friendly name to refer to the sample. Is unspecified, a name will be automatically generated one from the sample path. + +.PARAMETER Configuration +Configuration name that will be used to build the solution. Common available values are "Debug" and "Release". + +.PARAMETER Platform +Platform to build the solution for (e.g. "x64", "arm64"). + +.PARAMETER LogFilesDirectoy +Path to a directory where the log files will be written to. If not provided, outputs will be logged to the current working directory. + +.INPUTS +None. + +.OUTPUTS +Verbose output about the execution of this script will be provided only if -Verbose is provided. Otherwise, no output will be generated. + +.EXAMPLE +.\Build-Sample -Directory .\usb\kmdf_fx2 + +.EXAMPLE +.\Build-Sample -Directory .\usb\kmdf_fx2 -Configuration 'Release' -Platform 'x64' -Verbose -LogFilesDirectory .\_logs + +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true, + HelpMessage = 'Enter one directory path', + Position = 0)] + [string]$Directory, + [string]$SampleName, + [string]$Configuration = "Debug", + [string]$Platform = "x64", + $LogFilesDirectory = (Get-Location) +) + +$Verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $Verbose = $PsBoundParameters.Get_Item('Verbose') +} + +$oldPreference = $ErrorActionPreference +$ErrorActionPreference = "stop" +try +{ + # Check that msbuild can be called before trying anything. + Get-Command "msbuild" | Out-Null +} +catch +{ + Write-Verbose "`u{274C} msbuild cannot be called from current environment. Check that msbuild is set in current path (for example, that it is called from a Visual Studio developer command)." + Write-Error "msbuild cannot be called from current environment." + exit 1 +} +finally +{ + $ErrorActionPreference = $oldPreference +} + +if (-not (Test-Path -Path $Directory -PathType Container)) +{ + Write-Warning "`u{274C} A valid directory could not be found under $Directory" + exit 1 +} + +New-Item -ItemType Directory -Force -Path $LogFilesDirectory | Out-Null + +if (-not (Test-Path -Path $LogFilesDirectory -PathType Container)) +{ + Write-Warning "`u{274C} A valid directory for storing log files could not be created under $LogFilesDirectory" + # No exit here: process will continue but logs won't be available. +} + +if ([string]::IsNullOrWhitespace($SampleName)) +{ + $SampleName = (Resolve-Path $Directory).Path.Replace((Get-Location), '').Replace('\', '.').Trim('.').ToLower() +} + +$solutionFile = Get-ChildItem -Path $Directory -Filter *.sln | Select-Object -ExpandProperty FullName -First 1 + +if ($null -eq $solutionFile) +{ + Write-Warning "`u{274C} A solution could not be found under $Directory" + exit 1 +} + +$configurationIsSupported = $false +$inSolutionConfigurationPlatformsSection = $false +foreach ($line in Get-Content -Path $solutionFile) +{ + if (-not $inSolutionConfigurationPlatformsSection -and $line -match "\s*GlobalSection\(SolutionConfigurationPlatforms\).*") + { + $inSolutionConfigurationPlatformsSection = $true; + continue; + } + elseif ($line -match "\s*EndGlobalSection.*") + { + $inSolutionConfigurationPlatformsSection = $false; + continue; + } + + if ($inSolutionConfigurationPlatformsSection) + { + [regex]$regex = ".*=\s*(?(?.*)\|(?.*))\s*" + $match = $regex.Match($line) + if ([string]::IsNullOrWhiteSpace($match.Groups["ConfigString"].Value) -or [string]::IsNullOrWhiteSpace($match.Groups["Platform"].Value)) + { + Write-Warning "Could not parse configuration entry $line from file $solutionFile." + continue; + } + if ($match.Groups["Configuration"].Value.Trim() -eq $Configuration -and $match.Groups["Platform"].Value.Trim() -eq $Platform) + { + $configurationIsSupported = $true; + } + } +} + +if (-not $configurationIsSupported) +{ + Write-Verbose "[$SampleName] `u{23E9} Skipped. Configuration $Configuration|$Platform not supported." + exit 2 +} + +$errorLogFilePath = "$LogFilesDirectory\$SampleName.$Configuration.$Platform.err" +$warnLogFilePath = "$LogFilesDirectory\$SampleName.$Configuration.$Platform.wrn" +$OutLogFilePath = "$LogFilesDirectory\$SampleName.$Configuration.$Platform.out" + +Write-Verbose "Building Sample: $SampleName; Configuration: $Configuration; Platform: $Platform {" + +msbuild $solutionFile -clp:Verbosity=m -t:clean,build -property:Configuration=$Configuration -property:Platform=$Platform -p:TargetVersion=Windows10 -p:InfVerif_AdditionalOptions="/msft /sw1205 /sw1324 /sw1420 /sw1421" -p:SignToolWS=/fdws -p:DriverCFlagAddOn=/wd4996 -flp1:errorsonly`;logfile=$errorLogFilePath -flp2:WarningsOnly`;logfile=$warnLogFilePath -noLogo > $OutLogFilePath +if ($env:WDS_WipeOutputs -ne $null) +{ + Write-Verbose ("WipeOutputs: "+$Directory+" "+(((Get-Volume ($DriveLetter=(Get-Item ".").PSDrive.Name)).SizeRemaining/1GB))) + Get-ChildItem -path $Directory -Recurse -Include x64|Remove-Item -Recurse + Get-ChildItem -path $Directory -Recurse -Include arm64|Remove-Item -Recurse +} + +if ($LASTEXITCODE -ne 0) +{ + if ($Verbose) + { + Write-Warning "`u{274C} Build failed. Log available at $errorLogFilePath" + } + exit 1 +} + +Write-Verbose "Building Sample: $SampleName; Configuration: $Configuration; Platform: $Platform }" diff --git a/Build-SampleSet.ps1 b/Build-SampleSet.ps1 new file mode 100644 index 000000000..32821980a --- /dev/null +++ b/Build-SampleSet.ps1 @@ -0,0 +1,212 @@ +[CmdletBinding()] +param( + [hashtable]$SampleSet, + [string[]]$Configurations = @(if ([string]::IsNullOrEmpty($env:WDS_Configuration)) { "Debug" } else { $env:WDS_Configuration }), + [string[]]$Platforms = @(if ([string]::IsNullOrEmpty($env:WDS_Platform)) { "x64" } else { $env:WDS_Platform }), + $LogFilesDirectory = (Get-Location), + [int]$ThrottleLimit = 0 +) + +$ThrottleFactor = 5 +$LogicalProcessors = (Get-CIMInstance -Class 'CIM_Processor' -Verbose:$false).NumberOfLogicalProcessors + +if ($ThrottleLimit -eq 0) { + $ThrottleLimit = $ThrottleFactor * $LogicalProcessors +} + +$Verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $Verbose = $PsBoundParameters.Get_Item('Verbose') +} + +New-Item -ItemType Directory -Force -Path $LogFilesDirectory | Out-Null +$sampleBuilderFilePath = "$LogFilesDirectory\overview.htm" + + +Remove-Item -Recurse -Path $LogFilesDirectory 2>&1 | Out-Null +New-Item -ItemType Directory -Force -Path $LogFilesDirectory | Out-Null + +$oldPreference = $ErrorActionPreference +$ErrorActionPreference = "stop" +try { + # Check that msbuild can be called before trying anything. + Get-Command "msbuild" | Out-Null +} +catch { + Write-Host "`u{274C} msbuild cannot be called from current environment. Check that msbuild is set in current path (for example, that it is called from a Visual Studio developer command)." + Write-Error "msbuild cannot be called from current environment." + exit 1 +} +finally { + $ErrorActionPreference = $oldPreference +} + +# TODO: Make exclusion more granular; allow for configuration|platform exclusions +$exclusionsSet = @{} +Import-Csv 'exclusions.csv' | ForEach-Object { + $exclusionsSet[$_.Path.Replace($root, '').Trim('\').Replace('\', '.').ToLower()] = $_.Reason +} + +$jresult = @{ + SolutionsBuilt = 0 + SolutionsExcluded = 0 + SolutionsFailed = 0 + Results = @() + FailSet = @() + lock = [System.Threading.Mutex]::new($false) +} + +$SolutionsTotal = $sampleSet.Count * $Configurations.Count * $Platforms.Count + +Write-Output ("Samples: " + $sampleSet.Count) +Write-Output ("Configurations: " + $Configurations.Count + " (" + $Configurations + ")") +Write-Output ("Platforms: " + $Platforms.Count + " (" + $Platforms + ")") +Write-Output "Combinations: $SolutionsTotal" +Write-Output "LogicalProcessors: $LogicalProcessors" +Write-Output "ThrottleFactor: $ThrottleFactor" +Write-Output "ThrottleLimit: $ThrottleLimit" +Write-Output "WDS_WipeOutputs: $env:WDS_WipeOutputs" +Write-Output ("Disk Remaining (GB): " + (((Get-Volume ($DriveLetter = (Get-Item ".").PSDrive.Name)).SizeRemaining / 1GB))) +Write-Output "" +Write-Output "T: Combinations" +Write-Output "B: Built" +Write-Output "R: Build is running currently" +Write-Output "P: Build is pending an available build slot" +Write-Output "" +Write-Output "S: Built and result was 'Succeeded'" +Write-Output "E: Built and result was 'Excluded'" +Write-Output "U: Built and result was 'Unsupported' (Platform and Configuration combination)" +Write-Output "F: Built and result was 'Failed'" +Write-Output "" +Write-Output "Building all combinations..." + +$Results = @() + +$sw = [Diagnostics.Stopwatch]::StartNew() + +$SampleSet.GetEnumerator() | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel { + $LogFilesDirectory = $using:LogFilesDirectory + $exclusionsSet = $using:exclusionsSet + $Configurations = $using:Configurations + $Platforms = $using:Platforms + + $sampleName = $_.Key + $directory = $_.Value + + $ResultElement = new-object psobject + Add-Member -InputObject $ResultElement -MemberType NoteProperty -Name Sample -Value "$sampleName" + + foreach ($configuration in $Configurations) { + foreach ($platform in $Platforms) { + $thisunsupported = 0 + $thisfailed = 0 + $thisexcluded = 0 + $thissucceeded = 0 + $thisresult = "Not run" + $thisfailset = @() + + if ($exclusionsSet.ContainsKey($sampleName)) { + # Verbose + if ($thisexcluded -eq 0) { + Write-Verbose "[$sampleName] `u{23E9} Excluded and skipped. Reason: $($exclusionsSet[$sampleName])" + } + $thisexcluded += 1 + $thisresult = "Excluded" + } + else { + .\Build-Sample -Directory $directory -SampleName $sampleName -LogFilesDirectory $LogFilesDirectory -Configuration $configuration -Platform $platform -Verbose:$Verbose + if ($LASTEXITCODE -eq 0) { + $thissucceeded += 1 + $thisresult = "Succeeded" + } + elseif ($LASTEXITCODE -eq 1) { + $thisfailset += "$sampleName $configuration|$platform" + $thisfailed += 1 + $thisresult = "Failed" + } + else { + # ($LASTEXITCODE -eq 2) + $thisunsupported += 1 + $thisresult = "Unsupported" + } + } + Add-Member -InputObject $ResultElement -MemberType NoteProperty -Name "$configuration|$platform" -Value "$thisresult" + + $null = ($using:jresult).lock.WaitOne() + try { + ($using:jresult).SolutionsBuilt += 1 + ($using:jresult).SolutionsSucceeded += $thissucceeded + ($using:jresult).SolutionsExcluded += $thisexcluded + ($using:jresult).SolutionsUnsupported += $thisunsupported + ($using:jresult).SolutionsFailed += $thisfailed + ($using:jresult).FailSet += $thisfailset + $SolutionsTotal = $using:SolutionsTotal + $ThrottleLimit = $using:ThrottleLimit + $SolutionsBuilt = ($using:jresult).SolutionsBuilt + $SolutionsRemaining = $SolutionsTotal - $SolutionsBuilt + $SolutionsRunning = if ($SolutionsRemaining -ge $ThrottleLimit) { $ThrottleLimit } else { $SolutionsRemaining } + $SolutionsPending = if ($SolutionsRemaining -ge $ThrottleLimit) { ($SolutionsRemaining - $ThrottleLimit) } else { 0 } + $SolutionsBuiltPercent = [Math]::Round(100 * ($SolutionsBuilt / $using:SolutionsTotal)) + $TBRP = "T:" + ($SolutionsTotal) + "; B:" + (($using:jresult).SolutionsBuilt) + "; R:" + ($SolutionsRunning) + "; P:" + ($SolutionsPending) + $rstr = "S:" + (($using:jresult).SolutionsSucceeded) + "; E:" + (($using:jresult).SolutionsExcluded) + "; U:" + (($using:jresult).SolutionsUnsupported) + "; F:" + (($using:jresult).SolutionsFailed) + Write-Progress -Activity "Building combinations" -Status "$SolutionsBuilt of $using:SolutionsTotal combinations built ($SolutionsBuiltPercent%) | $TBRP | $rstr" -PercentComplete $SolutionsBuiltPercent + } + finally { + ($using:jresult).lock.ReleaseMutex() + } + } + } + $null = ($using:jresult).lock.WaitOne() + try { + ($using:jresult).Results += $ResultElement + } + finally { + ($using:jresult).lock.ReleaseMutex() + } +} + +$sw.Stop() + +if ($jresult.FailSet.Count -gt 0) { + Write-Output "Some combinations were built with errors:" + foreach ($failedSample in $jresult.FailSet) { + $failedSample -match "^(.*) (\w*)\|(\w*)$" | Out-Null + $failName = $Matches[1] + $failConfiguration = $Matches[2] + $failPlatform = $Matches[3] + Write-Output "Build errors in Sample $failName; Configuration: $failConfiguration; Platform: $failPlatform {" + Get-Content "$LogFilesDirectory\$failName.$failConfiguration.$failPlatform.err" | Write-Output + Write-Output "} $failedSample" + } + Write-Error "Some combinations were built with errors." +} + +# Display timer statistics to host +$min = $sw.Elapsed.Minutes +$seconds = $sw.Elapsed.Seconds + +$SolutionsSucceeded = $jresult.SolutionsSucceeded +$SolutionsExcluded = $jresult.SolutionsExcluded +$SolutionsUnsupported = $jresult.SolutionsUnsupported +$SolutionsFailed = $jresult.SolutionsFailed +$Results = $jresult.Results + +Write-Output "" +Write-Output "Built all combinations." +Write-Output "" +Write-Output "Elapsed time: $min minutes, $seconds seconds." +Write-Output ("Disk Remaining (GB): " + (((Get-Volume ($DriveLetter = (Get-Item ".").PSDrive.Name)).SizeRemaining / 1GB))) +Write-Output ("Samples: " + $sampleSet.Count) +Write-Output ("Configurations: " + $Configurations.Count + " (" + $Configurations + ")") +Write-Output ("Platforms: " + $Platforms.Count + " (" + $Platforms + ")") +Write-Output "Combinations: $SolutionsTotal" +Write-Output "Succeeded: $SolutionsSucceeded" +Write-Output "Excluded: $SolutionsExcluded" +Write-Output "Unsupported: $SolutionsUnsupported" +Write-Output "Failed: $SolutionsFailed" +Write-Output "Log files directory: $LogFilesDirectory" +Write-Output "Overview report: $sampleBuilderFilePath" +Write-Output "" + +$Results | Sort-Object { $_.Sample } | ConvertTo-Html -Title "Overview" | Out-File $sampleBuilderFilePath +Invoke-Item $sampleBuilderFilePath diff --git a/Building-Locally.md b/Building-Locally.md new file mode 100644 index 000000000..8f62a6099 --- /dev/null +++ b/Building-Locally.md @@ -0,0 +1,76 @@ +# How to build locally + +## Step 1: Install git and pwsh 7.3.0 +``` +winget install --id Microsoft.Powershell --source winget +winget install --id Git.Git --source winget` +``` + +## Step 2: Create a "driver build environment" + +There are multiple ways to achieve this. For example, [install Visual Studio and the Windows Driver Kit](https://learn.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk#download-and-install-the-windows-11-version-22h2-wdk). + +You can also just download and mount the EWDK as well and in the following example that is what we will do: + * Download the Windows 11, version 22H2 EWDK ISO image from the [official site](https://learn.microsoft.com/en-us/legal/windows/hardware/enterprise-wdk-license-2022) + * Mount ISO image + * Open a terminal + * `.\LaunchBuildEnv` + +## Step 3: Clone Windows Driver Samples and checkout main branch + +``` +cd path\to\your\repos +git clone --recurse-submodules https://github.com/microsoft/Windows-driver-samples.git +cd Windows-driver-samples +``` + +## Step 4: Check all samples builds with expected results for all flavors + +``` +pwsh +.\Build-AllSamples +``` +Above builds all samples for all configurations and platforms. + +You can refine, for example as follows: +``` +pwsh +.\Build-AllSamples -Samples '^tools.' -Configurations 'Debug','Release' -Platforms 'x64','arm64' +``` + +Expected output: +``` +Samples: 153 +Configurations: 2 (Debug Release) +Platforms: 2 (x64 arm64) +Combinations: 612 +Logical Processors: 12 +Throttle factor: 5 +Throttle limit: 60 + +T: Combinations +B: Built +R: Build is running currently +P: Build is pending an available build slot + +S: Built and result was 'Succeeded' +E: Built and result was 'Excluded' +U: Built and result was 'Unsupported' (Platform and Configuration combination) +F: Built and result was 'Failed' + +Building all combinations... + +Built all combinations. + +Elapsed time: 12 minutes, 34 seconds. +Samples: 153 +Configurations: 2 (Debug Release) +Platforms: 2 (x64 arm64) +Combinations: 612 +Succeeded: 326 +Excluded: 56 +Unsupported: 230 +Failed: 0 +Log files directory: .\_logs +Overview report: .\_logs\overview.htm +``` diff --git a/README.md b/README.md index 2e55d9809..efd1e633b 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,8 @@ If you're writing your first driver, use these exercises to get started. Each ex [Write a KMDF driver based on a template](https://docs.microsoft.com/windows-hardware/drivers/gettingstarted/writing-a-kmdf-driver-based-on-a-template) +[Use GitHub Actions to build a simple driver project](.github/Build-with-GitHub.md) + # Microsoft Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/TrEE/Miniport/TrEEMiniportSample.vcxproj b/TrEE/Miniport/TrEEMiniportSample.vcxproj index f2ec5ea29..7a2265b67 100644 --- a/TrEE/Miniport/TrEEMiniportSample.vcxproj +++ b/TrEE/Miniport/TrEEMiniportSample.vcxproj @@ -38,7 +38,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -62,7 +62,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -70,7 +70,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -78,7 +78,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/TrEE/OSService/TrEEOSServiceSample.vcxproj b/TrEE/OSService/TrEEOSServiceSample.vcxproj index d3afa66ac..7fd4726d1 100644 --- a/TrEE/OSService/TrEEOSServiceSample.vcxproj +++ b/TrEE/OSService/TrEEOSServiceSample.vcxproj @@ -38,7 +38,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -62,7 +62,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -70,7 +70,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -78,7 +78,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.inf b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.inf new file mode 100644 index 000000000..889f9bdb8 Binary files /dev/null and b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.inf differ diff --git a/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.sln b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.sln new file mode 100644 index 000000000..980e7ad6d --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.sln @@ -0,0 +1,88 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31409.214 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SamplesCommon", "SamplesCommon", "{0DF6D5E6-3B78-414B-B37B-85D9CA454487}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AudioCodec", "AudioCodec", "{0D3B6287-146E-4700-B2EE-11D520014FEA}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SamplesCommon", "..\..\Common\SamplesCommon.vcxproj", "{6A946D59-6690-4ED0-A77D-7D4C3D4B3241}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AudioCodec", "AudioCodec.vcxproj", "{C575002D-5FDE-43C7-AB19-EE846A20083A}" + ProjectSection(ProjectDependencies) = postProject + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241} = {6A946D59-6690-4ED0-A77D-7D4C3D4B3241} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM.ActiveCfg = Debug|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM.Build.0 = Debug|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM.Deploy.0 = Debug|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM64.Build.0 = Debug|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x64.ActiveCfg = Debug|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x64.Build.0 = Debug|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x64.Deploy.0 = Debug|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x86.ActiveCfg = Debug|Win32 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x86.Build.0 = Debug|Win32 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Debug|x86.Deploy.0 = Debug|Win32 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM.ActiveCfg = Release|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM.Build.0 = Release|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM.Deploy.0 = Release|ARM + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM64.ActiveCfg = Release|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM64.Build.0 = Release|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|ARM64.Deploy.0 = Release|ARM64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x64.ActiveCfg = Release|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x64.Build.0 = Release|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x64.Deploy.0 = Release|x64 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x86.ActiveCfg = Release|Win32 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x86.Build.0 = Release|Win32 + {C575002D-5FDE-43C7-AB19-EE846A20083A}.Release|x86.Deploy.0 = Release|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM.ActiveCfg = Debug|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM.Build.0 = Debug|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM.Deploy.0 = Debug|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM64.Build.0 = Debug|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x64.ActiveCfg = Debug|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x64.Build.0 = Debug|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x64.Deploy.0 = Debug|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x86.ActiveCfg = Debug|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x86.Build.0 = Debug|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Debug|x86.Deploy.0 = Debug|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM.ActiveCfg = Release|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM.Build.0 = Release|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM.Deploy.0 = Release|ARM + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM64.ActiveCfg = Release|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM64.Build.0 = Release|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|ARM64.Deploy.0 = Release|ARM64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x64.ActiveCfg = Release|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x64.Build.0 = Release|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x64.Deploy.0 = Release|x64 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x86.ActiveCfg = Release|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x86.Build.0 = Release|Win32 + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241}.Release|x86.Deploy.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241} = {0DF6D5E6-3B78-414B-B37B-85D9CA454487} + {C575002D-5FDE-43C7-AB19-EE846A20083A} = {0D3B6287-146E-4700-B2EE-11D520014FEA} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8E3043F2-1C76-4A4A-9C60-A645BD6CBF24} + EndGlobalSection +EndGlobal diff --git a/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj new file mode 100644 index 000000000..68389954d --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj @@ -0,0 +1,303 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM + + + Release + ARM + + + Debug + ARM64 + + + Release + ARM64 + + + + + + + + + + + + + + + + + 1 + 1 + 1 + 31 + {C575002D-5FDE-43C7-AB19-EE846A20083A} + {497e31cb-056b-4f31-abb8-447fd55ee5a5} + v4.5 + 12.0 + Debug + Win32 + AudioCodec + $(LatestTargetPlatformVersion) + + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Windows Driver + + + + + + + + + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=25;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + true + true + ..\..\common\trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR);..\..\common;..\..\inc;..\..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + $(DDK_LIB_PATH)\libcntpr.lib;wpprecorder.lib;acx\km\$(ACX_VERSION_MAJOR).$(ACX_VERSION_MINOR)\acxstub.lib;..\..\Common\$(IntDir)\SamplesCommon.lib;%(AdditionalDependencies) + + + + + + + + + \ No newline at end of file diff --git a/storage/sfloppy/src/sfloppy.vcxproj.Filters b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj.Filters similarity index 53% rename from storage/sfloppy/src/sfloppy.vcxproj.Filters rename to audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj.Filters index c1d47f3d3..0b882019e 100644 --- a/storage/sfloppy/src/sfloppy.vcxproj.Filters +++ b/audio/Acx/Samples/AudioCodec/Driver/AudioCodec.vcxproj.Filters @@ -2,35 +2,41 @@ - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {4BC320E9-22F6-4E58-8E7B-B87F90A2226B} + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd - {1B1144FD-B9FD-45E0-846D-0C0A89430459} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {BC1B1BDB-FAE7-4C16-A4B2-EBDC273AB7BC} + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + {8E41214B-6785-4CFE-B992-037D68949A14} inf;inv;inx;mof;mc; - {3AF8BBF9-34B1-4CEA-8BC6-305FB857F626} - - Source Files - - - - - Resource Files - + - + Driver Files + + + Header Files + + + + + Source Files + + + Source Files + + \ No newline at end of file diff --git a/audio/Acx/Samples/AudioCodec/Driver/Device.cpp b/audio/Acx/Samples/AudioCodec/Driver/Device.cpp new file mode 100644 index 000000000..7e9a0a3c6 --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/Device.cpp @@ -0,0 +1,439 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + Device.cpp - Device handling events for example driver. + +Abstract: + + This file contains the device entry points and callbacks. + +Environment: + + Kernel-mode Driver Framework + +--*/ + +#include +#include +#include "public.h" +#include +#include +#include +#include +#include "streamengine.h" +#include "DriverSettings.h" + +#ifndef __INTELLISENSE__ +#include "device.tmh" +#endif + +UNICODE_STRING g_RegistryPath = { 0 }; // This is used to store the registry settings path for the driver + +ULONG DeviceDriverTag = DRIVER_TAG; + +ULONG IdleTimeoutMsec = IDLE_TIMEOUT_MSEC; + +__drv_requiresIRQL(PASSIVE_LEVEL) +PAGED_CODE_SEG +NTSTATUS +CopyRegistrySettingsPath( + _In_ PUNICODE_STRING RegistryPath +) +/*++ + +Routine Description: + +Copies the following registry path to a global variable. + +\REGISTRY\MACHINE\SYSTEM\ControlSetxxx\Services\\Parameters + +Arguments: + +RegistryPath - Registry path passed to DriverEntry + +Returns: + +NTSTATUS - SUCCESS if able to configure the framework + +--*/ + +{ + PAGED_CODE(); + + // + // Initializing the unicode string, so that if it is not allocated it will not be deallocated too. + // + RtlInitUnicodeString(&g_RegistryPath, nullptr); + + g_RegistryPath.MaximumLength = RegistryPath->Length + sizeof(WCHAR); + + g_RegistryPath.Buffer = (PWCH)ExAllocatePool2(POOL_FLAG_PAGED, g_RegistryPath.MaximumLength, DRIVER_TAG); + + if (g_RegistryPath.Buffer == nullptr) + { + return STATUS_INSUFFICIENT_RESOURCES; + } + + RtlAppendUnicodeToString(&g_RegistryPath, RegistryPath->Buffer); + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +NTSTATUS +Codec_EvtBusDeviceAdd( + _In_ WDFDRIVER Driver, + _Inout_ PWDFDEVICE_INIT DeviceInit +) +/*++ + +Routine Description: + + EvtDeviceAdd is called by the framework in response to AddDevice + call from the PnP manager. We create and initialize a device object to + represent a new instance of the device. All the software resources + should be allocated in this callback. + +Arguments: + Driver - Handle to a framework driver object created in DriverEntry + + DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + WDF_DEVICE_PNP_CAPABILITIES pnpCaps; + ACX_DEVICEINIT_CONFIG devInitCfg; + ACX_DEVICE_CONFIG devCfg; + WDFDEVICE device = nullptr; + PCODEC_DEVICE_CONTEXT devCtx; + WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; + + PAGED_CODE(); + + UNREFERENCED_PARAMETER(Driver); + + // + // The driver calls this DDI in its AddDevice callback before creating the PnP device. + // ACX uses this call to add default/standard settings for the device to be created. + // + ACX_DEVICEINIT_CONFIG_INIT(&devInitCfg); + RETURN_IF_FAILED(AcxDeviceInitInitialize(DeviceInit, &devInitCfg)); + + // + // Initialize the pnpPowerCallbacks structure. Callback events for PNP + // and Power are specified here. If you don't supply any callbacks, + // the Framework will take appropriate default actions based on whether + // DeviceInit is initialized to be an FDO, a PDO or a filter device + // object. + // + WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); + pnpPowerCallbacks.EvtDevicePrepareHardware = Codec_EvtDevicePrepareHardware; + pnpPowerCallbacks.EvtDeviceReleaseHardware = Codec_EvtDeviceReleaseHardware; + pnpPowerCallbacks.EvtDeviceD0Entry = Codec_EvtDeviceD0Entry; + pnpPowerCallbacks.EvtDeviceD0Exit = Codec_EvtDeviceD0Exit; + WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks); + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_DEVICE_CONTEXT); + attributes.EvtCleanupCallback = Codec_EvtDeviceContextCleanup; + + RETURN_NTSTATUS_IF_FAILED(WdfDeviceCreate(&DeviceInit, &attributes, &device)); + + // + // Init Codec's device context. + // + devCtx = GetCodecDeviceContext(device); + ASSERT(devCtx != nullptr); + + devCtx->Render = nullptr; + devCtx->Capture = nullptr; + devCtx->ExcludeD3Cold = WdfFalse; + + // + // The driver calls this DDI in its AddDevice callback after creating the PnP + // device. ACX uses this call to apply any post device settings. + // + ACX_DEVICE_CONFIG_INIT(&devCfg); + RETURN_NTSTATUS_IF_FAILED(AcxDeviceInitialize(device, &devCfg)); + + // + // Tell the framework to set the SurpriseRemovalOK in the DeviceCaps so + // that you don't get the popup in usermode (on Win2K) when you surprise + // remove the device. + // + WDF_DEVICE_PNP_CAPABILITIES_INIT(&pnpCaps); + pnpCaps.SurpriseRemovalOK = WdfTrue; + WdfDeviceSetPnpCapabilities(device, &pnpCaps); + + // + // Create a render circuit and capture circuit and add them to the current + // device context. These circuits will be added to the device when the + // prepare hardware callback is called. + // + RETURN_NTSTATUS_IF_FAILED(CodecR_AddStaticRender(device, &CODEC_RENDER_COMPONENT_GUID, &renderCircuitName)); + + RETURN_NTSTATUS_IF_FAILED(CodecC_AddStaticCapture(device, &CODEC_CAPTURE_COMPONENT_GUID, &MIC_CUSTOM_NAME, &captureCircuitName)); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Codec_EvtDevicePrepareHardware( + _In_ WDFDEVICE Device, + _In_ WDFCMRESLIST ResourceList, + _In_ WDFCMRESLIST ResourceListTranslated +) +/*++ + +Routine Description: + + In this callback, the driver does whatever is necessary to make the + hardware ready to use. + +Arguments: + + Device - handle to a device + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + PCODEC_DEVICE_CONTEXT devCtx; + + UNREFERENCED_PARAMETER(ResourceList); + UNREFERENCED_PARAMETER(ResourceListTranslated); + + PAGED_CODE(); + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // NOTE: Download firmware here. + + // NOTE: Register streaming h/w resources here. + + // + // Set power policy data. + // + RETURN_NTSTATUS_IF_FAILED(Codec_SetPowerPolicy(Device)); + + // + // Setting up the data saving (CSaveData) and wave file reader (CWaveReader) + // utility classes which will be used by the virtual streaming engine. + // + RETURN_NTSTATUS_IF_FAILED(CSaveData::SetDeviceObject(WdfDeviceWdmGetDeviceObject(Device))); + + RETURN_NTSTATUS_IF_FAILED(CSaveData::InitializeWorkItems(WdfDeviceWdmGetDeviceObject(Device))); + + RETURN_NTSTATUS_IF_FAILED(CWaveReader::InitializeWorkItems(WdfDeviceWdmGetDeviceObject(Device))); + + // + // The driver uses this DDI to associate a circuit to a device. After + // this call the circuit is not visible until the device goes in D0. + // For a real driver there should be a check here to make sure the + // circuit has not been added already (there could be a situation where + // prepareHardware is called multiple times and releaseHardware is only + // called once). + // + + ASSERT(devCtx->Render); + RETURN_NTSTATUS_IF_FAILED(AcxDeviceAddCircuit(Device, devCtx->Render)); + + ASSERT(devCtx->Capture); + RETURN_NTSTATUS_IF_FAILED(AcxDeviceAddCircuit(Device, devCtx->Capture)); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Codec_EvtDeviceReleaseHardware( + _In_ WDFDEVICE Device, + _In_ WDFCMRESLIST ResourceListTranslated +) +/*++ + +Routine Description: + + In this callback, the driver releases the h/w resources allocated in the + prepare h/w callback. + +Arguments: + + Device - handle to a device + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status; + PCODEC_DEVICE_CONTEXT devCtx; + + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(ResourceListTranslated); + + PAGED_CODE(); + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // + // The driver uses this DDI to delete a circuit from the current device. + // + RETURN_NTSTATUS_IF_FAILED(AcxDeviceRemoveCircuit(Device, devCtx->Render)); + RETURN_NTSTATUS_IF_FAILED(AcxDeviceRemoveCircuit(Device, devCtx->Capture)); + + // NOTE: Release streaming h/w resources here. + + CSaveData::DestroyWorkItems(); + CWaveReader::DestroyWorkItems(); + + status = STATUS_SUCCESS; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Codec_EvtDeviceD0Entry( + _In_ WDFDEVICE Device, + _In_ WDF_POWER_DEVICE_STATE PreviousState +) +{ + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(PreviousState); + + PAGED_CODE(); + + return STATUS_SUCCESS; +} + +NTSTATUS +Codec_EvtDeviceD0Exit( + _In_ WDFDEVICE Device, + _In_ WDF_POWER_DEVICE_STATE TargetState +) +{ + NTSTATUS status = STATUS_SUCCESS; + POWER_ACTION powerAction; + + PAGED_CODE(); + + powerAction = WdfDeviceGetSystemPowerAction(Device); + + // + // Update the power policy D3-cold info for Connected Standby. + // + if (TargetState == WdfPowerDeviceD3 && powerAction == PowerActionNone) + { + PCODEC_DEVICE_CONTEXT devCtx; + WDF_TRI_STATE excludeD3Cold = WdfTrue; + ACX_DX_EXIT_LATENCY latency; + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // + // Get the current exit latency. + // + latency = AcxDeviceGetCurrentDxExitLatency(Device, + WdfDeviceGetSystemPowerAction(Device), + TargetState); + + // + // If the current exit latency for the ACX device is responsive + // (not instant or fast) then D3-cold does not need to be excluded. + // Otherwise, D3-cold should be excluded because if the hardware + // goes into this state it will take too long to go back into D0 + // and respond. + // + if (latency == AcxDxExitLatencyResponsive) + { + excludeD3Cold = WdfFalse; + } + + if (devCtx->ExcludeD3Cold != excludeD3Cold) + { + devCtx->ExcludeD3Cold = excludeD3Cold; + + RETURN_NTSTATUS_IF_FAILED(Codec_SetPowerPolicy(Device)); + } + } + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Codec_SetPowerPolicy( + _In_ WDFDEVICE Device +) +{ + NTSTATUS status = STATUS_SUCCESS; + PCODEC_DEVICE_CONTEXT devCtx; + + PAGED_CODE(); + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // + // Init the idle policy structure. + // + WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; + WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleCannotWakeFromS0); + idleSettings.IdleTimeout = IDLE_POWER_TIMEOUT; + idleSettings.IdleTimeoutType = SystemManagedIdleTimeoutWithHint; + idleSettings.ExcludeD3Cold = devCtx->ExcludeD3Cold; + + RETURN_NTSTATUS_IF_FAILED(WdfDeviceAssignS0IdleSettings(Device, &idleSettings)); + + return status; +} + +VOID +Codec_EvtDeviceContextCleanup( + _In_ WDFOBJECT WdfDevice +) +/*++ + +Routine Description: + + In this callback, it cleans up device context. + +Arguments: + + WdfDevice - WDF device object + +Return Value: + + nullptr + +--*/ +{ + WDFDEVICE device; + PCODEC_DEVICE_CONTEXT devCtx; + + device = (WDFDEVICE)WdfDevice; + devCtx = GetCodecDeviceContext(device); + ASSERT(devCtx != nullptr); + + if (devCtx->Capture) + { + CodecC_CircuitCleanup(devCtx->Capture); + } +} diff --git a/audio/Acx/Samples/AudioCodec/Driver/Driver.cpp b/audio/Acx/Samples/AudioCodec/Driver/Driver.cpp new file mode 100644 index 000000000..452b0d99e --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/Driver.cpp @@ -0,0 +1,129 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + Driver.cpp + +Abstract: + + This file contains the driver entry points and callbacks. + +Environment: + + Kernel-mode Driver Framework + +--*/ + +#include "public.h" +#include "cpp_utils.h" + +#ifndef __INTELLISENSE__ +#include "driver.tmh" +#endif + +_Use_decl_annotations_ +void AudioCodecDriverUnload( + _In_ WDFDRIVER Driver +) +{ + PAGED_CODE(); + + if (!Driver) + { + ASSERT(FALSE); + return; + } + + WPP_CLEANUP(WdfDriverWdmGetDriverObject(Driver)); + + if (g_RegistryPath.Buffer != nullptr) + { + ExFreePool(g_RegistryPath.Buffer); + RtlZeroMemory(&g_RegistryPath, sizeof(g_RegistryPath)); + } + + return; +} + +INIT_CODE_SEG +NTSTATUS +DriverEntry( + _In_ PDRIVER_OBJECT DriverObject, + _In_ PUNICODE_STRING RegistryPath +) +/*++ + +Routine Description: + DriverEntry initializes the driver and is the first routine called by the + system after the driver is loaded. DriverEntry specifies the other entry + points in the function driver, such as EvtDevice and DriverUnload. + +Parameters Description: + + DriverObject - represents the instance of the function driver that is loaded + into memory. DriverEntry must initialize members of DriverObject before it + returns to the caller. DriverObject is allocated by the system before the + driver is loaded, and it is released by the system after the system unloads + the function driver from memory. + + RegistryPath - represents the driver specific path in the Registry. + The function driver can use the path to store driver related data between + reboots. The path does not store hardware instance specific data. + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL otherwise. + +--*/ +{ + WDF_DRIVER_CONFIG wdfCfg; + ACX_DRIVER_CONFIG acxCfg; + WDFDRIVER driver; + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + + PAGED_CODE(); + WPP_INIT_TRACING(DriverObject, RegistryPath); + + auto exit = scope_exit([&status, &DriverObject]() { + if (!NT_SUCCESS(status)) + { + WPP_CLEANUP(DriverObject); + + if (g_RegistryPath.Buffer != nullptr) + { + ExFreePool(g_RegistryPath.Buffer); + RtlZeroMemory(&g_RegistryPath, sizeof(g_RegistryPath)); + } + } + }); + + RETURN_NTSTATUS_IF_FAILED(CopyRegistrySettingsPath(RegistryPath)); + + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + WDF_DRIVER_CONFIG_INIT(&wdfCfg, Codec_EvtBusDeviceAdd); + wdfCfg.EvtDriverUnload = AudioCodecDriverUnload; + + // + // Create a framework driver object to represent our driver. + // + RETURN_NTSTATUS_IF_FAILED(WdfDriverCreate(DriverObject, RegistryPath, &attributes, &wdfCfg, &driver)); + + // + // Initializing the ACX driver configuration struct which contains size and flags + // elements. + // + ACX_DRIVER_CONFIG_INIT(&acxCfg); + + // + // The driver calls this DDI in its DriverEntry callback after creating the WDF driver + // object. ACX uses this call to apply any post driver settings. + // + RETURN_NTSTATUS_IF_FAILED(AcxDriverInitialize(driver, &acxCfg)); + + return status; +} diff --git a/audio/Acx/Samples/AudioCodec/Driver/DriverSettings.h b/audio/Acx/Samples/AudioCodec/Driver/DriverSettings.h new file mode 100644 index 000000000..65aa7f5b9 --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/DriverSettings.h @@ -0,0 +1,54 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + DriverSettings.h + +Abstract: + + Contains guid definitions and other definitions used by the render and capture circuits + for this specific driver. Driver developers should replace these definitions with their + own. + +Environment: + + Kernel mode + +--*/ + +// Defining the component ID for the capture circuit. This ID uniquely identifies the circuit instance (vendor specific): +DEFINE_GUID(CODEC_CAPTURE_COMPONENT_GUID, 0xc3ee9ec6, 0x8e8c, 0x49e9, 0xaf, 0x4b, 0xa7, 0xfc, 0x28, 0xe9, 0xd2, 0xe7); + +// Defines a custom name for the capture circuit bridge pin: +DEFINE_GUID(MIC_CUSTOM_NAME, 0xd5649dc4, 0x2fa2, 0x418b, 0xb2, 0x78, 0x39, 0x7, 0x64, 0x6b, 0x3, 0xe); + +// Defining the component ID for the render circuit. This ID uniquely identifies the circuit instance (vendor specific): +DEFINE_GUID(CODEC_RENDER_COMPONENT_GUID, 0xd03deb75, 0xe5b2, 0x45f7, 0x91, 0xfa, 0xf7, 0xae, 0x42, 0xdd, 0xf, 0xe0); + +// This is always the definition for the system container guid: +DEFINE_GUID(SYSTEM_CONTAINER_GUID, 0x00000000, 0x0000, 0x0000, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF); + +// Driver developers should update this guid if the container is a device rather than a +// system. Otherwise, this GUID should stay the same: +DEFINE_GUID(DEVICE_CONTAINER_GUID, 0x00000000, 0x0000, 0x0000, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF); + +// AudioCodec driver tag: +#define DRIVER_TAG (ULONG) 'CduA' + +// The idle timeout in msec for power policy structure: +#define IDLE_TIMEOUT_MSEC (ULONG) 10000 + +// The WPP control GUID defined in Trace.h should also be updated to be unique. + +// This string must match the string defined in AudioCodec.inf for the microphone name: +DECLARE_CONST_UNICODE_STRING(captureCircuitName, L"Microphone0"); + +// This string must match the string defined in AudioCodec.inf for the speaker name: +DECLARE_CONST_UNICODE_STRING(renderCircuitName, L"Speaker0"); diff --git a/audio/Acx/Samples/AudioCodec/Driver/ReadMe.txt b/audio/Acx/Samples/AudioCodec/Driver/ReadMe.txt new file mode 100644 index 000000000..ebc61c6da --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/ReadMe.txt @@ -0,0 +1,42 @@ +======================================================================== + AudioCodec Project Overview +======================================================================== + +This file contains a summary of what you will find in each of the files that make up your project. + +AudioCodec.vcxproj + This is the main project file for projects generated using an Application Wizard. + It contains information about the version of the product that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +AudioCodec.vcxproj.filters + This is the filters file for VC++ projects generated using an Application Wizard. + It contains information about the association between the files in your project + and the filters. This association is used in the IDE to show grouping of files with + similar extensions under a specific node (for e.g. ".cpp" files are associated with the + "Source Files" filter). + +Driver.cpp & Driver.h + DriverEntry and WDFDRIVER related functionality and callbacks. Driver developers should + make changes to these files for their specific driver as necessary. + +Device.cpp & Device.h + WDFDEVICE related functionality and callbacks. Driver developers should make changes to + these files for their specific driver as necessary. + +Trace.h + Definitions for WPP tracing. + +DriverSettings.h + Contains guid definitions and other definitions used by the render and capture circuits + for this specific driver. Driver developers should replace these definitions with their + own. + +///////////////////////////////////////////////////////////////////////////// + +Learn more about Kernel Mode Driver Framework here: + +http://msdn.microsoft.com/en-us/library/ff544296(v=VS.85).aspx + +///////////////////////////////////////////////////////////////////////////// diff --git a/audio/Acx/Samples/AudioCodec/Driver/Resources.rc b/audio/Acx/Samples/AudioCodec/Driver/Resources.rc new file mode 100644 index 000000000..788fc416b --- /dev/null +++ b/audio/Acx/Samples/AudioCodec/Driver/Resources.rc @@ -0,0 +1,12 @@ +#include + +#include + +#define VER_FILETYPE VFT_DRV +#define VER_FILESUBTYPE VFT2_DRV_SYSTEM +#define VER_FILEDESCRIPTION_STR "Audio Codec Acx Sample Driver" +#define VER_INTERNALNAME_STR "AudioCodec.sys" +#define VER_ORIGINALFILENAME_STR "AudioCodec.sys" + +#include "common.ver" + diff --git a/audio/Acx/Samples/Common/CaptureCircuit.cpp b/audio/Acx/Samples/Common/CaptureCircuit.cpp new file mode 100644 index 000000000..ba205a907 --- /dev/null +++ b/audio/Acx/Samples/Common/CaptureCircuit.cpp @@ -0,0 +1,799 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + CaptureCircuit.cpp + +Abstract: + + Capture Circuit. This file contains routines to create and handle + capture circuit. + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "public.h" +#include +#include +#include +#include "AudioFormats.h" +#include "streamengine.h" +#include "cpp_utils.h" +#include "circuithelper.h" + +#ifndef __INTELLISENSE__ +#include "captureCircuit.tmh" +#endif + +// +// Controls how the custom name of the bridge pin is read. +// +BOOL g_UseCustomInfName = TRUE; + +PAGED_CODE_SEG +NTSTATUS +CodecC_EvtAcxPinSetDataFormat( + _In_ ACXPIN Pin, + _In_ ACXDATAFORMAT DataFormat +) +/*++ + +Routine Description: + + This ACX pin callback sets the device/mixed format. + +Return Value: + + NTSTATUS + +--*/ +{ + UNREFERENCED_PARAMETER(Pin); + UNREFERENCED_PARAMETER(DataFormat); + + PAGED_CODE(); + + // NOTE: update device/mixed format here. + + return STATUS_NOT_SUPPORTED; +} + +/////////////////////////////////////////////////////////// +// +// For more information on volume element see: https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/ksnodetype-volume +// +_Use_decl_annotations_ +NTSTATUS +CodecC_EvtVolumeAssignLevelCallback( + _In_ ACXVOLUME Volume, + _In_ ULONG Channel, + _In_ LONG VolumeLevel +) +{ + PAGED_CODE(); + + ASSERT(Volume); + PVOLUME_ELEMENT_CONTEXT volumeCtx = GetVolumeElementContext(Volume); + ASSERT(volumeCtx); + + if (Channel != ALL_CHANNELS_ID) + { + volumeCtx->VolumeLevel[Channel] = VolumeLevel; + } + else + { + for (ULONG i = 0; i < MAX_CHANNELS; ++i) + { + volumeCtx->VolumeLevel[i] = VolumeLevel; + } + } + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +NTSTATUS +CodecC_EvtVolumeRetrieveLevelCallback( + _In_ ACXVOLUME Volume, + _In_ ULONG Channel, + _Out_ LONG * VolumeLevel +) +{ + PAGED_CODE(); + + ASSERT(Volume); + PVOLUME_ELEMENT_CONTEXT volumeCtx = GetVolumeElementContext(Volume); + ASSERT(volumeCtx); + + if (Channel == ALL_CHANNELS_ID) + { + Channel = 0; + } + + *VolumeLevel = volumeCtx->VolumeLevel[Channel]; + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_CreateVolumeElement( + _In_ ACXCIRCUIT Circuit, + _Out_ ACXVOLUME* Element +) +/*++ + +Routine Description: + + This routine creates a volume element. + +Return Value: + + NT status value +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + ACX_VOLUME_CALLBACKS volumeCallbacks; + ACX_VOLUME_CONFIG volumeCfg; + VOLUME_ELEMENT_CONTEXT * volumeCtx; + + PAGED_CODE(); + + // + // The driver uses this DDI to assign its volume element callbacks. + // + ACX_VOLUME_CALLBACKS_INIT(&volumeCallbacks); + volumeCallbacks.EvtAcxVolumeAssignLevel = CodecC_EvtVolumeAssignLevelCallback; + volumeCallbacks.EvtAcxVolumeRetrieveLevel = CodecC_EvtVolumeRetrieveLevelCallback; + + // + // Create Volume element + // + ACX_VOLUME_CONFIG_INIT(&volumeCfg); + volumeCfg.ChannelsCount = MAX_CHANNELS; + volumeCfg.Minimum = VOLUME_LEVEL_MINIMUM; + volumeCfg.Maximum = VOLUME_LEVEL_MAXIMUM; + volumeCfg.SteppingDelta = VOLUME_STEPPING; + volumeCfg.Callbacks = &volumeCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, VOLUME_ELEMENT_CONTEXT); + attributes.ParentObject = Circuit; + + RETURN_NTSTATUS_IF_FAILED(AcxVolumeCreate(Circuit, &attributes, &volumeCfg, Element)); + + ASSERT(*Element != nullptr); + volumeCtx = GetVolumeElementContext(*Element); + ASSERT(volumeCtx); + + // + // (max + min)/2 puts it in the middle of the valid range, divide that by the stepping to get the nearest + // valid step, multiply that by stepping to put it back at a level value. + // + volumeCtx->VolumeLevel[0] = (VOLUME_LEVEL_MAXIMUM + VOLUME_LEVEL_MINIMUM) / 2 / VOLUME_STEPPING * VOLUME_STEPPING; + volumeCtx->VolumeLevel[1] = (VOLUME_LEVEL_MAXIMUM + VOLUME_LEVEL_MINIMUM) / 2 / VOLUME_STEPPING * VOLUME_STEPPING; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_EvtAcxPinRetrieveName( + _In_ ACXPIN Pin, + _Out_ PUNICODE_STRING Name +) +/*++ + +Routine Description: + + If g_UseCustomInfName is false then the ACX + pin callback EvtAcxPinRetrieveName calls this + function in order to retrieve the pin name. + +Return Value: + + NTSTATUS + +--*/ +{ + UNREFERENCED_PARAMETER(Pin); + + PAGED_CODE(); + + return RtlUnicodeStringPrintf(Name, L"CustomName2"); +} + +VOID +CodecC_EvtPinContextCleanup( + _In_ WDFOBJECT WdfPin +) +/*++ + +Routine Description: + + In this callback, it cleans up pin context. + +Arguments: + + WdfDevice - WDF device object + +Return Value: + + nullptr + +--*/ +{ + UNREFERENCED_PARAMETER(WdfPin); +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_CircuitCleanup( + _In_ ACXCIRCUIT Circuit +) +{ + PCODEC_CAPTURE_CIRCUIT_CONTEXT circuitCtx; + + PAGED_CODE(); + + // + // Remove the static capture circuit. + // + circuitCtx = GetCaptureCircuitContext(Circuit); + ASSERT(circuitCtx != nullptr); + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_AddStaticCapture( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName +) +/*++ + +Routine Description: + + Creates the static capture circuit (pictured below) + and adds it to the device context. This is called + when a new device is detected and the AddDevice + call is made by the pnp manager. + + ****************************************************** + * Capture Circuit * + * * + * +-----------------------+ * + * | | * + * | +-------------+ | * + * Host ------>| | Volume Node | |---> Bridge * + * Pin | +-------------+ | Pin * + * | | * + * +-----------------------+ * + * * + ****************************************************** + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + PCODEC_DEVICE_CONTEXT devCtx; + PCAPTURE_DEVICE_CONTEXT captureDevCtx; + ACXCIRCUIT captureCircuit = nullptr; + WDF_OBJECT_ATTRIBUTES attributes; + + PAGED_CODE(); + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // + // Alloc audio context to current device. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CAPTURE_DEVICE_CONTEXT); + RETURN_NTSTATUS_IF_FAILED(WdfObjectAllocateContext(Device, &attributes, (PVOID*)&captureDevCtx)); + ASSERT(captureDevCtx); + + // + // Create a capture circuit associated with this child device. + // + RETURN_NTSTATUS_IF_FAILED(CodecC_CreateCaptureCircuit(Device, ComponentGuid, MicCustomName, CircuitName, &captureCircuit)); + + devCtx->Capture = captureCircuit; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Capture_AllocateSupportedFormats( + _In_ WDFDEVICE Device, + _In_reads_bytes_(CodecCapturePinCount) ACXPIN Pin[], + _In_ ACXCIRCUIT Circuit, + _In_ size_t CodecCapturePinCount +) +{ + UNREFERENCED_PARAMETER(CodecCapturePinCount); + + NTSTATUS status = STATUS_SUCCESS; + ACXDATAFORMAT formatPcm44100c1; + ACXDATAFORMAT formatPcm48000c1; + ACXDATAFORMATLIST formatList; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + /////////////////////////////////////////////////////////// + // + // Allocate the formats this circuit supports. + // + + RETURN_NTSTATUS_IF_FAILED(AllocateFormat(Pcm44100c1, Circuit, Device, &formatPcm44100c1)); + RETURN_NTSTATUS_IF_FAILED(AllocateFormat(Pcm48000c1, Circuit, Device, &formatPcm48000c1)); + + /////////////////////////////////////////////////////////// + // + // Define supported formats for the host pin. + // + + // + // The raw processing mode list is associated with each single circuit + // by ACX. A driver uses this DDI to retrieve the built-in raw + // data-format list. + // + RETURN_NTSTATUS_IF_TRUE(CodecCaptureHostPin >= CodecCapturePinCount, STATUS_INVALID_PARAMETER); + formatList = AcxPinGetRawDataFormatList(Pin[CodecCaptureHostPin]); + RETURN_NTSTATUS_IF_TRUE(formatList == nullptr, STATUS_INSUFFICIENT_RESOURCES); + + // + // The driver uses this DDI to add data formats to the raw + // processing mode list associated with the current circuit. + // + RETURN_NTSTATUS_IF_FAILED(AcxDataFormatListAddDataFormat(formatList, formatPcm44100c1)); + RETURN_NTSTATUS_IF_FAILED(AcxDataFormatListAddDataFormat(formatList, formatPcm48000c1)); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_CreateCaptureCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName, + _Out_ ACXCIRCUIT* Circuit +) +/*++ + +Routine Description: + + This routine builds the CODEC capture circuit. + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status; + WDF_OBJECT_ATTRIBUTES attributes; + ACXCIRCUIT circuit; + CODEC_CAPTURE_CIRCUIT_CONTEXT* circuitCtx; + ACXPIN pin[CodecCapturePinCount]; + + PAGED_CODE(); + + // + // Init output value. + // + *Circuit = nullptr; + + /////////////////////////////////////////////////////////// + // + // Create a circuit. + // + { + PACXCIRCUIT_INIT circuitInit = nullptr; + ACX_CIRCUIT_PNPPOWER_CALLBACKS powerCallbacks; + + // + // The driver uses this DDI to allocate an ACXCIRCUIT_INIT + // structure. This opaque structure is used when creating + // a standalone audio circuit representing an audio device. + // + circuitInit = AcxCircuitInitAllocate(Device); + + // + // A driver uses this DDI to free the allocated + // ACXCIRCUIT_INIT structure when an error is detected. + // Normally the structures is deleted/cleared by ACX when + // an ACX circuit is created successfully. + // + auto circuitInitScope = scope_exit([&circuitInit]() { + if (circuitInit) { + AcxCircuitInitFree(circuitInit); + } + }); + + // + // The driver uses this DDI to specify the Component ID + // of the ACX circuit. This ID is a guid that uniquely + // identifies the circuit instance (vendor specific). + // + AcxCircuitInitSetComponentId(circuitInit, ComponentGuid); + + // + // The driver uses this DDI to specify the circuit name. + // For standalone circuits, this is the audio device name + // which is used by clients to open handles to the audio devices. + // + (VOID)AcxCircuitInitAssignName(circuitInit, CircuitName); + + // + // The driver uses this DDI to specify the circuit type. The + // circuit type can be AcxCircuitTypeRender, AcxCircuitTypeCapture, + // AcxCircuitTypeOther, or AcxCircuitTypeMaximum (for validation). + // + AcxCircuitInitSetCircuitType(circuitInit, AcxCircuitTypeCapture); + + // + // The driver uses this DDI to assign its (if any) power callbacks. + // + ACX_CIRCUIT_PNPPOWER_CALLBACKS_INIT(&powerCallbacks); + powerCallbacks.EvtAcxCircuitPowerUp = CodecC_EvtCircuitPowerUp; + powerCallbacks.EvtAcxCircuitPowerDown = CodecC_EvtCircuitPowerDown; + AcxCircuitInitSetAcxCircuitPnpPowerCallbacks(circuitInit, &powerCallbacks); + + // + // The driver uses this DDI to register for a stream-create callback. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitInitAssignAcxCreateStreamCallback(circuitInit, CodecC_EvtCircuitCreateStream)); + + // + // The driver uses this DDI to create a new ACX circuit. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_CAPTURE_CIRCUIT_CONTEXT); + RETURN_NTSTATUS_IF_FAILED(AcxCircuitCreate(Device, &attributes, &circuitInit, &circuit)); + + circuitInitScope.release(); + + circuitCtx = GetCaptureCircuitContext(circuit); + ASSERT(circuitCtx); + } + + // + // Post circuit creation initialization. + // + + /////////////////////////////////////////////////////////// + // + // Create volume element. + // + { + ACXELEMENT elements[CaptureElementCount] = { 0 }; + + RETURN_NTSTATUS_IF_FAILED(CodecC_CreateVolumeElement(circuit, (ACXVOLUME*)&elements[CaptureVolumeIndex])); + + // + // Saving the volume element in the circuit context. + // + circuitCtx->VolumeElement = (ACXVOLUME)elements[CaptureVolumeIndex]; + + // + // The driver uses this DDI post circuit creation to add ACXELEMENTs. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitAddElements(circuit, elements, SIZEOF_ARRAY(elements))); + } + + /////////////////////////////////////////////////////////// + // + // Create the pins for the circuit. + // + { + ACX_PIN_CALLBACKS pinCallbacks; + ACX_PIN_CONFIG pinCfg; + CODEC_PIN_CONTEXT* pinCtx; + + /////////////////////////////////////////////////////////// + // + // Create capture streaming pin. + // + ACX_PIN_CALLBACKS_INIT(&pinCallbacks); + pinCallbacks.EvtAcxPinSetDataFormat = CodecC_EvtAcxPinSetDataFormat; + + ACX_PIN_CONFIG_INIT(&pinCfg); + pinCfg.Type = AcxPinTypeSource; + pinCfg.Communication = AcxPinCommunicationSink; + pinCfg.Category = &KSCATEGORY_AUDIO; + pinCfg.PinCallbacks = &pinCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_PIN_CONTEXT); + attributes.EvtCleanupCallback = CodecC_EvtPinContextCleanup; + attributes.ParentObject = circuit; + + // + // The driver uses this DDI to create one or more pins on the circuits. + // + RETURN_NTSTATUS_IF_FAILED(AcxPinCreate(circuit, &attributes, &pinCfg, &(pin[CodecCaptureHostPin]))); + + ASSERT(pin[CodecCaptureHostPin] != nullptr); + pinCtx = GetCodecPinContext(pin[CodecCaptureHostPin]); + ASSERT(pinCtx); + pinCtx->CodecPinType = CodecPinTypeHost; + + /////////////////////////////////////////////////////////// + // + // Create capture endpoint pin. + // + ACX_PIN_CALLBACKS_INIT(&pinCallbacks); + ACX_PIN_CONFIG_INIT(&pinCfg); + + pinCfg.Type = AcxPinTypeSink; + pinCfg.Communication = AcxPinCommunicationNone; + pinCfg.Category = &KSNODETYPE_MICROPHONE; + pinCfg.PinCallbacks = &pinCallbacks; + + // Specify how to read the custom name. + if (g_UseCustomInfName) + { + pinCfg.Name = MicCustomName; + } + else + { + pinCallbacks.EvtAcxPinRetrieveName = CodecC_EvtAcxPinRetrieveName; + } + g_UseCustomInfName = !g_UseCustomInfName; + + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + attributes.ParentObject = circuit; + + // + // The driver uses this DDI to create one or more pins on the circuits. + // + RETURN_NTSTATUS_IF_FAILED(AcxPinCreate(circuit, &attributes, &pinCfg, &(pin[CodecCaptureBridgePin]))); + + ASSERT(pin[CodecCaptureBridgePin] != nullptr); + } + + /////////////////////////////////////////////////////////// + // + // Add audio jack to bridge pin. + // For more information on audio jack see: https://docs.microsoft.com/en-us/windows/win32/api/devicetopology/ns-devicetopology-ksjack_description + // + { + ACX_JACK_CONFIG jackCfg; + ACXJACK jack; + PJACK_CONTEXT jackCtx; + + ACX_JACK_CONFIG_INIT(&jackCfg); + jackCfg.Description.ChannelMapping = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; + jackCfg.Description.Color = RGB(0, 0, 0); + jackCfg.Description.ConnectionType = AcxConnTypeAtapiInternal; + jackCfg.Description.GeoLocation = AcxGeoLocFront; + jackCfg.Description.GenLocation = AcxGenLocPrimaryBox; + jackCfg.Description.PortConnection = AcxPortConnIntegratedDevice; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, JACK_CONTEXT); + attributes.ParentObject = pin[CodecCaptureBridgePin]; + + RETURN_NTSTATUS_IF_FAILED(AcxJackCreate(pin[CodecCaptureBridgePin], &attributes, &jackCfg, &jack)); + + ASSERT(jack != nullptr); + + jackCtx = GetJackContext(jack); + ASSERT(jackCtx); + jackCtx->Dummy = 0; + + RETURN_NTSTATUS_IF_FAILED(AcxPinAddJacks(pin[CodecCaptureBridgePin], &jack, 1)); + } + + RETURN_NTSTATUS_IF_FAILED(Capture_AllocateSupportedFormats(Device, pin, circuit, CodecCapturePinCount)); + + /////////////////////////////////////////////////////////// + // + // The driver uses this DDI post circuit creation to add ACXPINs. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitAddPins(circuit, pin, CodecCapturePinCount)); + + // + // Set output value. + // + *Circuit = circuit; + + // + // Done. + // + status = STATUS_SUCCESS; + + return status; +} + +_Use_decl_annotations_ +NTSTATUS +CodecC_EvtCircuitPowerUp( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ WDF_POWER_DEVICE_STATE PreviousState +) +{ + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(Circuit); + UNREFERENCED_PARAMETER(PreviousState); + + PAGED_CODE(); + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +NTSTATUS +CodecC_EvtCircuitPowerDown( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ WDF_POWER_DEVICE_STATE TargetState +) +{ + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(Circuit); + UNREFERENCED_PARAMETER(TargetState); + + PAGED_CODE(); + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_EvtCircuitCreateStream( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ ACXPIN Pin, + _In_ PACXSTREAM_INIT StreamInit, + _In_ ACXDATAFORMAT StreamFormat, + _In_ const GUID * SignalProcessingMode, + _In_ ACXOBJECTBAG VarArguments +) +/*++ + +Routine Description: + + This routine creates a stream for the specified circuit. + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status; + PCAPTURE_DEVICE_CONTEXT devCtx; + WDF_OBJECT_ATTRIBUTES attributes; + ACXSTREAM stream; + STREAMENGINE_CONTEXT * streamCtx; + ACX_STREAM_CALLBACKS streamCallbacks; + ACX_RT_STREAM_CALLBACKS rtCallbacks; + CCaptureStreamEngine * streamEngine = nullptr; + CODEC_CAPTURE_CIRCUIT_CONTEXT * circuitCtx; + CODEC_PIN_CONTEXT * pinCtx; + + auto streamEngineScope = scope_exit([&streamEngine]() { + + if (streamEngine) + { + delete streamEngine; + } + + }); + + PAGED_CODE(); + UNREFERENCED_PARAMETER(SignalProcessingMode); + UNREFERENCED_PARAMETER(VarArguments); + + ASSERT(IsEqualGUID(*SignalProcessingMode, AUDIO_SIGNALPROCESSINGMODE_RAW)); + + devCtx = GetCaptureDeviceContext(Device); + ASSERT(devCtx != nullptr); + + circuitCtx = GetCaptureCircuitContext(Circuit); + ASSERT(circuitCtx != nullptr); + + pinCtx = GetCodecPinContext(Pin); + ASSERT(pinCtx != nullptr); + + // + // Init streaming callbacks. + // + ACX_STREAM_CALLBACKS_INIT(&streamCallbacks); + streamCallbacks.EvtAcxStreamPrepareHardware = EvtStreamPrepareHardware; + streamCallbacks.EvtAcxStreamReleaseHardware = EvtStreamReleaseHardware; + streamCallbacks.EvtAcxStreamRun = EvtStreamRun; + streamCallbacks.EvtAcxStreamPause = EvtStreamPause; + + RETURN_NTSTATUS_IF_FAILED(AcxStreamInitAssignAcxStreamCallbacks(StreamInit, &streamCallbacks)); + + // + // Init RT streaming callbacks. + // + ACX_RT_STREAM_CALLBACKS_INIT(&rtCallbacks); + rtCallbacks.EvtAcxStreamGetHwLatency = EvtStreamGetHwLatency; + rtCallbacks.EvtAcxStreamAllocateRtPackets = EvtStreamAllocateRtPackets; + rtCallbacks.EvtAcxStreamFreeRtPackets = EvtStreamFreeRtPackets; + rtCallbacks.EvtAcxStreamGetCapturePacket = CodecC_EvtStreamGetCapturePacket; + rtCallbacks.EvtAcxStreamGetCurrentPacket = EvtStreamGetCurrentPacket; + rtCallbacks.EvtAcxStreamGetPresentationPosition = EvtStreamGetPresentationPosition; + + RETURN_NTSTATUS_IF_FAILED(AcxStreamInitAssignAcxRtStreamCallbacks(StreamInit, &rtCallbacks)); + + // + // Buffer notifications are supported. + // + AcxStreamInitSetAcxRtStreamSupportsNotifications(StreamInit); + + // + // Create the stream. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, STREAMENGINE_CONTEXT); + attributes.EvtDestroyCallback = EvtStreamDestroy; + RETURN_NTSTATUS_IF_FAILED(AcxRtStreamCreate(Device, Circuit, &attributes, &StreamInit, &stream)); + + streamCtx = GetStreamEngineContext(stream); + ASSERT(streamCtx); + + // + // Create the virtual streaming engine which will control + // streaming logic for the capture circuit. + // + streamEngine = new (POOL_FLAG_NON_PAGED, DeviceDriverTag) CCaptureStreamEngine(stream, StreamFormat); + RETURN_NTSTATUS_IF_TRUE(streamEngine == nullptr, STATUS_INSUFFICIENT_RESOURCES); + + streamCtx->StreamEngine = (PVOID)streamEngine; + + streamEngine = nullptr; + + // + // Done. + // + status = STATUS_SUCCESS; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CodecC_EvtStreamGetCapturePacket( + _In_ ACXSTREAM Stream, + _Out_ ULONG * LastCapturePacket, + _Out_ ULONGLONG * QPCPacketStart, + _Out_ BOOLEAN * MoreData +) +{ + PSTREAMENGINE_CONTEXT ctx; + CCaptureStreamEngine* streamEngine = nullptr; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = static_cast(ctx->StreamEngine); + + return streamEngine->GetCapturePacket(LastCapturePacket, QPCPacketStart, MoreData); +} + + diff --git a/audio/Acx/Samples/Common/CircuitHelper.cpp b/audio/Acx/Samples/Common/CircuitHelper.cpp new file mode 100644 index 000000000..bfff74b22 --- /dev/null +++ b/audio/Acx/Samples/Common/CircuitHelper.cpp @@ -0,0 +1,620 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + CircuitHelper.cpp + +Abstract: + + This module contains helper functions for circuits. + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "public.h" +#include "CircuitHelper.h" + +#ifndef __INTELLISENSE__ +#include "CircuitHelper.tmh" +#endif + +const ULONG _DSP_STREAM_PROPERTY_UI4_VALUE = 1; + +PAGED_CODE_SEG +NTSTATUS AllocateFormat( + _In_ KSDATAFORMAT_WAVEFORMATEXTENSIBLE WaveFormat, + _In_ ACXCIRCUIT Circuit, + _In_ WDFDEVICE Device, + _Out_ ACXDATAFORMAT* Format +) +{ + PAGED_CODE(); + + NTSTATUS status = STATUS_SUCCESS; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + ACX_DATAFORMAT_CONFIG formatCfg; + ACX_DATAFORMAT_CONFIG_INIT_KS(&formatCfg, &WaveFormat); + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, FORMAT_CONTEXT); + attributes.ParentObject = Circuit; + + // + // Creates an ACXDATAFORMAT handle for the given wave format. + // + RETURN_NTSTATUS_IF_FAILED(AcxDataFormatCreate(Device, &attributes, &formatCfg, Format)); + + ASSERT((*Format) != NULL); + FORMAT_CONTEXT* formatCtx; + formatCtx = GetFormatContext(*Format); + ASSERT(formatCtx); + UNREFERENCED_PARAMETER(formatCtx); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS CreateStreamBridge( + _In_ ACX_STREAM_BRIDGE_CONFIG StreamCfg, + _In_ ACXCIRCUIT Circuit, + _In_ ACXPIN Pin, + _In_ DSP_PIN_CONTEXT* PinCtx, + _In_ BOOL Render) +{ + PAGED_CODE(); + + NTSTATUS status = STATUS_SUCCESS; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + attributes.ParentObject = Pin; + + ACX_OBJECTBAG_CONFIG objBagCfg; + ACXOBJECTBAG objBag = NULL; + ACX_OBJECTBAG_CONFIG_INIT(&objBagCfg); + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + attributes.ParentObject = Circuit; + RETURN_NTSTATUS_IF_FAILED(AcxObjectBagCreate(&attributes, &objBagCfg, &objBag)); + + DECLARE_CONST_ACXOBJECTBAG_DRIVER_PROPERTY_NAME(msft, TestUI4); + RETURN_NTSTATUS_IF_FAILED(AcxObjectBagAddUI4(objBag, &TestUI4, _DSP_STREAM_PROPERTY_UI4_VALUE)); + + // + // Add a stream BRIDGE. + // + PCGUID inModes[] = { + &AUDIO_SIGNALPROCESSINGMODE_RAW, + &AUDIO_SIGNALPROCESSINGMODE_DEFAULT, + }; + + if (Render) + { + StreamCfg.InModesCount = SIZEOF_ARRAY(inModes); + StreamCfg.InModes = inModes; + } + + // + // Do not specify InModes for capture - this will prevent the ACX framework from adding created streams to this stream + // bridge automatically. We want to add the stream bridges manually since we don't want KWS streams added. + // + StreamCfg.OutMode = &AUDIO_SIGNALPROCESSINGMODE_RAW; + StreamCfg.OutStreamVarArguments = objBag; + + // + // Uncomment this line to reverse the change-state sequence notifications. + // + // streamCfg.Flags |= AcxStreamBridgeInvertChangeStateSequence; + + ACXSTREAMBRIDGE streamBridge = NULL; + RETURN_NTSTATUS_IF_FAILED(AcxStreamBridgeCreate(Circuit, &attributes, &StreamCfg, &streamBridge)); + + if (!Render) + { + PinCtx->HostStreamBridge = streamBridge; + } + + RETURN_NTSTATUS_IF_FAILED(AcxPinAddStreamBridges(Pin, &streamBridge, 1)); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS ConnectRenderCircuitElements( + _In_ ACXAUDIOENGINE AudioEngineElement, + _In_ ACXCIRCUIT Circuit +) +{ + PAGED_CODE(); + + NTSTATUS status = STATUS_SUCCESS; + + // + // Explicitly connect the circuit/elements. Note that driver doesn't + // need to perform this step when circuit/elements are connected in the + // same order as they were added to the circuit. By default ACX connects + // the elements starting from the sink circuit pin and ending with the + // source circuit pin for both render and capture devices. + // + // Circuit layout + // ----------------------------------------- + // | | + // | -------------------- | + // Host -0->|-----1->| |-0-------->|-3-> Bridge Pin + // | | Audio Engine | | + // Offload -1->|-----2->| Node |-3--| | + // | |------------------| | | + // | | | + // Loopback <-2-|<------------------------------ | | + // | | + // | | + // |---------------------------------------| + // + + ACX_CONNECTION connections[4]; + + ACX_CONNECTION_INIT(&connections[0], Circuit, AudioEngineElement); + connections[0].FromPin.Id = RenderHostPin; + connections[0].ToPin.Id = 1; + + ACX_CONNECTION_INIT(&connections[1], Circuit, AudioEngineElement); + connections[1].FromPin.Id = RenderOffloadPin; + connections[1].ToPin.Id = 2; + + ACX_CONNECTION_INIT(&connections[2], AudioEngineElement, Circuit); + connections[2].ToPin.Id = RenderLoopbackPin; + connections[2].FromPin.Id = 3; + + ACX_CONNECTION_INIT(&connections[3], AudioEngineElement, Circuit); + connections[3].ToPin.Id = RenderBridgePin; + connections[3].FromPin.Id = 0; + + // + // Add the connections linking circuit to elements. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitAddConnections(Circuit, connections, SIZEOF_ARRAY(connections))); + + return status; + +} + +PAGED_CODE_SEG +NTSTATUS +Codec_GetModeFromAttributeList( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _Out_ GUID * SignalProcessingMode + ) +{ + NTSTATUS status = STATUS_NO_MORE_ENTRIES; + PKSATTRIBUTE attributeHeader = NULL; + PAGED_CODE(); + *SignalProcessingMode = AUDIO_SIGNALPROCESSINGMODE_DEFAULT; + + status = FindKsAttributeById(Attributes, + AttributesSize, + &KSATTRIBUTEID_AUDIOSIGNALPROCESSING_MODE, + sizeof(KSATTRIBUTE_AUDIOSIGNALPROCESSING_MODE), + &attributeHeader); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + ASSERT(attributeHeader->Attribute == KSATTRIBUTEID_AUDIOSIGNALPROCESSING_MODE); + ASSERT(attributeHeader->Size == sizeof(KSATTRIBUTE_AUDIOSIGNALPROCESSING_MODE)); + + KSATTRIBUTE_AUDIOSIGNALPROCESSING_MODE* signalProcessingModeAttribute; + signalProcessingModeAttribute = (KSATTRIBUTE_AUDIOSIGNALPROCESSING_MODE*)attributeHeader; + *SignalProcessingMode = signalProcessingModeAttribute->SignalProcessingMode; + status = STATUS_SUCCESS; +exit: + return status; +} + +struct AFX_FIND_KSATTRIBUTE_BY_ID +{ + const _GUID * Id; + ULONG Size; + PKSATTRIBUTE Attribute; +}; + +PAGED_CODE_SEG +NTSTATUS +FindKsAttributeByIdVisitor( + _In_ PKSATTRIBUTE AttributeHeader, + _In_ PVOID Context, + _Out_ BOOLEAN * bContinue + ) +{ + NTSTATUS status = STATUS_SUCCESS; + AFX_FIND_KSATTRIBUTE_BY_ID * ctx = (AFX_FIND_KSATTRIBUTE_BY_ID *)Context; + PAGED_CODE(); + // Default: continue searching. + *bContinue = TRUE; + + if (IsEqualGUIDAligned(AttributeHeader->Attribute, *ctx->Id)) + { + // Validate its size. + if (AttributeHeader->Size < ctx->Size) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + + ctx->Attribute = AttributeHeader; + *bContinue = FALSE; + } +exit: + return status; +} + +PAGED_CODE_SEG +NTSTATUS +FindKsAttributeById( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _In_ const _GUID * AttributeId, + _In_ ULONG AttributeSize, + _Out_ PKSATTRIBUTE * AttributeHeader + ) +{ + PAGED_CODE(); + NTSTATUS status; + AFX_FIND_KSATTRIBUTE_BY_ID ctx = {0}; + *AttributeHeader = NULL; + ctx.Id = AttributeId; + ctx.Size = AttributeSize; + status = TraverseKsAttributeList(Attributes, AttributesSize, FindKsAttributeByIdVisitor, &ctx); + if (!NT_SUCCESS(status)) + { + goto exit; + } + if (ctx.Attribute == NULL) + { + status = STATUS_NO_MORE_ENTRIES; + goto exit; + } + *AttributeHeader = ctx.Attribute; +exit: + return status; +} + +PAGED_CODE_SEG +NTSTATUS +TraverseKsAttributeList( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _In_ PFN_KSATTRIBUTES_VISITOR Visitor, + _In_ PVOID Context + ) +{ + PAGED_CODE(); + NTSTATUS status = STATUS_SUCCESS; + ULONG cbRemaining = 0; + PKSATTRIBUTE attributeHeader = NULL; + ASSERT(Visitor); + // + // Note: multiple-item ptr must have a FILE_QUAD_ALIGNMENT only in relation to the Pin's format size. + // I.e., it is not guaranteed that the attributes are FILE_QUAD_ALIGNMENT in memory, unless the caller reallocates + // them before calling this function (which is currently not done by anyone in any driver/sample). + // + //ASSERT((ULONG_PTR)Attributes == (((ULONG_PTR)Attributes + FILE_QUAD_ALIGNMENT) & ~FILE_QUAD_ALIGNMENT)); + if (AttributesSize < sizeof(KSMULTIPLE_ITEM)) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + if (Attributes->Size < sizeof(KSMULTIPLE_ITEM)) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + if (AttributesSize < Attributes->Size) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + + cbRemaining = Attributes->Size; + // + // Init ptr / size of attributes of list. + // + cbRemaining -= sizeof(KSMULTIPLE_ITEM); + attributeHeader = (PKSATTRIBUTE)(Attributes + 1); + for (ULONG i = 0; i < Attributes->Count; i++) + { + BOOLEAN bContinue = TRUE; + size_t cbAttribute = 0; + + if (cbRemaining < sizeof(KSATTRIBUTE)) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + if (attributeHeader->Size < sizeof(KSATTRIBUTE)) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + if (cbRemaining < attributeHeader->Size) + { + status = STATUS_INVALID_PARAMETER; + goto exit; + } + // + // Invoke the descriptor enumeration routine. + // + status = Visitor(attributeHeader, Context, &bContinue); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + if (!bContinue) + { + break; + } + // + // Adjust pointer and buffer size to next attribute (QWORD aligned) + // + cbAttribute = CODEC_ALIGN_SIZE_UP_CONSTANT(attributeHeader->Size, FILE_QUAD_ALIGNMENT); + if (cbRemaining < cbAttribute) + { + // + // Out of buffer, check if this was the last attribute. + // + if (i + 1 != Attributes->Count) + { + // + // This was not the last attribute, nevertheless there is no more buffer, error out. + // + status = STATUS_INVALID_PARAMETER; + goto exit; + } + // This was the final attribute. Exit loop with success status. + break; + } + // Check next attribute. + attributeHeader = (PKSATTRIBUTE)(((PBYTE)attributeHeader) + cbAttribute); + cbRemaining -= (ULONG)cbAttribute; + } + // Normalize success code. + status = STATUS_SUCCESS; +exit: + return status; +} + +PAGED_CODE_SEG +NTSTATUS +EvtJackRetrievePresence( + _In_ ACXJACK Jack, + _In_ PBOOLEAN IsConnected +) +{ + PAGED_CODE(); + + UNREFERENCED_PARAMETER(Jack); + UNREFERENCED_PARAMETER(IsConnected); + + NTSTATUS status = STATUS_SUCCESS; + + // + // Because this is a sample we always return true (jack is present). A real driver should check + // if the device is actually present before returning true. + // + *IsConnected = true; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CreateAudioJack( + _In_ ULONG ChannelMapping, + _In_ ULONG Color, + _In_ ACX_JACK_CONNECTION_TYPE ConnectionType, + _In_ ACX_JACK_GEO_LOCATION GeoLocation, + _In_ ACX_JACK_GEN_LOCATION GenLocation, + _In_ ACX_JACK_PORT_CONNECTION PortConnection, + _In_ ULONG Flags, + _In_ ACXPIN BridgePin + ) +{ + PAGED_CODE(); + + NTSTATUS status = STATUS_SUCCESS; + ACX_JACK_CONFIG jackCfg; + ACXJACK jack; + PJACK_CONTEXT jackCtx; + ACX_JACK_CALLBACKS jackCallbacks; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + ACX_JACK_CONFIG_INIT(&jackCfg); + jackCfg.Description.ChannelMapping = ChannelMapping; + jackCfg.Description.Color = Color; + jackCfg.Description.ConnectionType = ConnectionType; + jackCfg.Description.GeoLocation = GeoLocation; + jackCfg.Description.GenLocation = GenLocation; + jackCfg.Description.PortConnection = PortConnection; + jackCfg.Flags = Flags; + + ACX_JACK_CALLBACKS_INIT(&jackCallbacks); + jackCallbacks.EvtAcxJackRetrievePresenceState = EvtJackRetrievePresence; + jackCfg.Callbacks = &jackCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, JACK_CONTEXT); + attributes.ParentObject = BridgePin; + + status = AcxJackCreate(BridgePin, &attributes, &jackCfg, &jack); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + ASSERT(jack != nullptr); + + jackCtx = GetJackContext(jack); + ASSERT(jackCtx); + jackCtx->Dummy = 0; + + status = AcxPinAddJacks(BridgePin, &jack, 1); + +exit: + return status; +} + +PAGED_CODE_SEG +VOID +CpuResourcesCallbackHelper +( + _In_ WDFOBJECT Object, + _In_ WDFREQUEST Request, + _In_ ACXELEMENT Element +) +{ + NTSTATUS ntStatus = STATUS_NOT_SUPPORTED; + ULONG_PTR outDataCb = 0; + ACX_REQUEST_PARAMETERS params; + ULONG minSize = sizeof(ULONG); + + PAGED_CODE(); + + ACX_REQUEST_PARAMETERS_INIT(¶ms); + AcxRequestGetParameters(Request, ¶ms); + + if ((params.Type != AcxRequestTypeProperty) || + (params.Parameters.Property.ItemType != AcxItemTypeElement)) + { + // Return to acx + (VOID) AcxCircuitDispatchAcxRequest((ACXCIRCUIT)Object, Request); + Request = NULL; + goto exit; + } + + if (Element == NULL) + { + ntStatus = STATUS_NOT_SUPPORTED; + goto exit; + } + + ULONG elementId = params.Parameters.Property.ItemId; + ULONG currentElementId = AcxElementGetId(Element); + ULONG valueCb = params.Parameters.Property.ValueCb; + + if (valueCb != 0) + { + if (params.Parameters.Property.Value == NULL) + { + ntStatus = STATUS_BUFFER_TOO_SMALL; + goto exit; + } + } + + // + // Check to see if the current node is the peakmeter node, if not then return the call to ACX + // + if (elementId != currentElementId) + { + (VOID) AcxCircuitDispatchAcxRequest((ACXCIRCUIT)Object, Request); + Request = NULL; + goto exit; + } + + if (params.Parameters.Property.Verb == AcxPropertyVerbGet) + { + + if (valueCb == 0) + { + outDataCb = minSize; + ntStatus = STATUS_BUFFER_OVERFLOW; + goto exit; + } + else if (valueCb < minSize) + { + outDataCb = 0; + ntStatus = STATUS_BUFFER_TOO_SMALL; + goto exit; + } + else + { + *((PULONG)params.Parameters.Property.Value) = KSAUDIO_CPU_RESOURCES_NOT_HOST_CPU; + params.Parameters.Property.ValueCb = sizeof(ULONG); + outDataCb = params.Parameters.Property.ValueCb; + ntStatus = STATUS_SUCCESS; + } + } + else if (params.Parameters.Property.Verb == AcxPropertyVerbBasicSupport) + { + if ((valueCb != sizeof(ULONG)) && (valueCb != sizeof(KSPROPERTY_DESCRIPTION))) + { + outDataCb = minSize; + ntStatus = STATUS_BUFFER_OVERFLOW; + goto exit; + } + + if (valueCb >= sizeof(KSPROPERTY_DESCRIPTION)) + { + // if return buffer can hold a KSPROPERTY_DESCRIPTION, return it + // + PKSPROPERTY_DESCRIPTION PropDesc = (PKSPROPERTY_DESCRIPTION)params.Parameters.Property.Value; + + PropDesc->AccessFlags = KSPROPERTY_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_GET; + PropDesc->DescriptionSize = sizeof(KSPROPERTY_DESCRIPTION); + PropDesc->PropTypeSet.Set = KSPROPTYPESETID_General; + PropDesc->PropTypeSet.Id = VT_UI4; + PropDesc->PropTypeSet.Flags = 0; + PropDesc->MembersListCount = 0; + PropDesc->Reserved = 0; + outDataCb = sizeof(KSPROPERTY_DESCRIPTION); + ntStatus = STATUS_SUCCESS; + } + else if (valueCb >= sizeof(ULONG)) + { + // if return buffer can hold a ULONG, return the access flags + // + *((PULONG)params.Parameters.Property.Value) = KSPROPERTY_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_GET; + outDataCb = minSize; + ntStatus = STATUS_SUCCESS; + } + else if (valueCb > 0) + { + outDataCb = 0; + ntStatus = STATUS_BUFFER_TOO_SMALL; + } + else + { + outDataCb = minSize; + ntStatus = STATUS_BUFFER_OVERFLOW; + } + } + else + { + // + // Just give it back to ACX. After this call the request is gone. + // + (VOID) AcxCircuitDispatchAcxRequest((ACXCIRCUIT)Object, Request); + Request = NULL; + goto exit; + } + +exit: + if (Request != NULL) + { + WdfRequestCompleteWithInformation(Request, ntStatus, outDataCb); + } +} // EvtAudioCpuResourcesCallback diff --git a/audio/Acx/Samples/Common/CircuitHelper.h b/audio/Acx/Samples/Common/CircuitHelper.h new file mode 100644 index 000000000..589381534 --- /dev/null +++ b/audio/Acx/Samples/Common/CircuitHelper.h @@ -0,0 +1,135 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + CircuitHelper.h + +Abstract: + + This module contains helper functions for endpoints. + +Environment: + + Kernel mode + +--*/ + +// size_t +// __inline +// CODEC_ALIGN_SIZE_DOWN_CONSTANT( +// IN size_t Length, +// IN size_t AlignTo +// ) +#define CODEC_ALIGN_SIZE_DOWN_CONSTANT(Length, AlignTo) ((Length) & ~((AlignTo)-1)) + +#define CODEC_ALIGN_SIZE_DOWN CODEC_ALIGN_SIZE_DOWN_CONSTANT + +// size_t +// __inline +// CODEC_ALIGN_SIZE_UP_CONSTANT( +// IN size_t Length, +// IN size_t AlignTo +// ) +#define CODEC_ALIGN_SIZE_UP_CONSTANT(Length, AlignTo) CODEC_ALIGN_SIZE_DOWN_CONSTANT((Length) + (AlignTo)-1, (AlignTo)) + +#define CODEC_ALIGN_SIZE_UP CODEC_ALIGN_SIZE_UP_CONSTANT + +PAGED_CODE_SEG +NTSTATUS +Codec_GetModeFromAttributeList( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _Out_ GUID * SignalProcessingMode + ); + +// +// Enumeration visitor callback. +// +typedef +NTSTATUS +(EVT_KSATTRIBUTES_VISITOR)( + _In_ PKSATTRIBUTE AttributeHeader, + _In_ PVOID Context, + _Out_ BOOLEAN * bContinue + ); + +typedef EVT_KSATTRIBUTES_VISITOR *PFN_KSATTRIBUTES_VISITOR; + +static +PAGED_CODE_SEG +EVT_KSATTRIBUTES_VISITOR FindKsAttributeByIdVisitor; + +PAGED_CODE_SEG +NTSTATUS +FindKsAttributeById( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _In_ const _GUID * AttributeId, + _In_ ULONG AttributeSize, + _Out_ PKSATTRIBUTE * AttributeHeader + ); + +PAGED_CODE_SEG +NTSTATUS +TraverseKsAttributeList( + _In_ const PKSMULTIPLE_ITEM Attributes, + _In_ ULONG AttributesSize, + _In_ PFN_KSATTRIBUTES_VISITOR Visitor, + _In_ PVOID Context + ); + +PAGED_CODE_SEG +NTSTATUS AllocateFormat( + _In_ KSDATAFORMAT_WAVEFORMATEXTENSIBLE WaveFormat, + _In_ ACXCIRCUIT Circuit, + _In_ WDFDEVICE Device, + _Out_ ACXDATAFORMAT* Format +); + +PAGED_CODE_SEG +NTSTATUS CreateStreamBridge( + _In_ ACX_STREAM_BRIDGE_CONFIG StreamCfg, + _In_ ACXCIRCUIT Circuit, + _In_ ACXPIN Pin, + _In_ DSP_PIN_CONTEXT* PinCtx, + _In_ BOOL Render +); + +PAGED_CODE_SEG +NTSTATUS ConnectRenderCircuitElements( + _In_ ACXAUDIOENGINE AudioEngineElement, + _In_ ACXCIRCUIT Circuit +); + +PAGED_CODE_SEG +NTSTATUS CreateAudioJack( + _In_ ULONG ChannelMapping, + _In_ ULONG Color, + _In_ ACX_JACK_CONNECTION_TYPE ConnectionType, + _In_ ACX_JACK_GEO_LOCATION GeoLocation, + _In_ ACX_JACK_GEN_LOCATION GenLocation, + _In_ ACX_JACK_PORT_CONNECTION PortConnection, + _In_ ULONG Flags, + _In_ ACXPIN BridgePin +); + +PAGED_CODE_SEG +NTSTATUS EvtJackRetrievePresence( + _In_ ACXJACK Jack, + _In_ PBOOLEAN IsConnected +); + +PAGED_CODE_SEG +VOID CpuResourcesCallbackHelper( + _In_ WDFOBJECT Object, + _In_ WDFREQUEST Request, + _In_ ACXELEMENT Element +); + diff --git a/audio/Acx/Samples/Common/KeywordDetector.cpp b/audio/Acx/Samples/Common/KeywordDetector.cpp new file mode 100644 index 000000000..f34767450 --- /dev/null +++ b/audio/Acx/Samples/Common/KeywordDetector.cpp @@ -0,0 +1,484 @@ +/*++ + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + KeywordDetector.cpp + +Abstract: + + Sample keyword detector management. + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "public.h" +#include +#include +#include +#include "streamengine.h" +#include "KeywordDetector.h" + +PAGED_CODE_SEG +CKeywordDetector::CKeywordDetector() + : + m_streamRunning(FALSE), + m_qpcStartCapture(0), + m_nLastQueuedPacket(-1), + m_SoundDetectorArmed1(FALSE), + m_SoundDetectorArmed2(FALSE), + m_SoundDetectorData1(0), + m_SoundDetectorData2(0), + m_ullKeywordStartTimestamp(0), + m_ullKeywordStopTimestamp(0) +{ + PAGED_CODE(); + + // Initialize our pool of packets and the list structures + KeInitializeSpinLock(&PacketPoolSpinLock); + KeInitializeSpinLock(&PacketFifoSpinLock); + ResetFifo(); +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::ReadKeywordTimestampRegistry() +{ + PAGED_CODE(); + + NTSTATUS ntStatus; + PDRIVER_OBJECT DriverObject; + HANDLE DriverKey; + + RTL_QUERY_REGISTRY_TABLE paramTable[] = { + // QueryRoutine Flags Name EntryContext DefaultType DefaultData DefaultLength + { NULL, RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK, L"KeywordDetectorStartTimestamp", &m_ullKeywordStartTimestamp, (REG_QWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_QWORD, &m_ullKeywordStartTimestamp, sizeof(ULONGLONG) }, + { NULL, RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK, L"KeywordDetectorStopTimestamp", &m_ullKeywordStopTimestamp, (REG_QWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_QWORD, &m_ullKeywordStopTimestamp, sizeof(ULONGLONG) }, + { NULL, 0, NULL, NULL, 0, NULL, 0 } + }; + + DriverObject = WdfDriverWdmGetDriverObject(WdfGetDriver()); + DriverKey = NULL; + ntStatus = IoOpenDriverRegistryKey(DriverObject, + DriverRegKeyParameters, + KEY_READ, + 0, + &DriverKey); + + if (!NT_SUCCESS(ntStatus)) + { + return ntStatus; + } + + ntStatus = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE, + (PCWSTR) DriverKey, + ¶mTable[0], + NULL, + NULL); + if (DriverKey) + { + ZwClose(DriverKey); + } + + return ntStatus; +} + + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::ResetDetector(_In_ GUID eventId) +{ + PAGED_CODE(); + + if (eventId == CONTOSO_KEYWORD1) + { + m_SoundDetectorData1 = 0; + m_SoundDetectorArmed1 = FALSE; + } + else if(eventId == CONTOSO_KEYWORD2) + { + m_SoundDetectorData2 = 0; + m_SoundDetectorArmed2 = FALSE; + } + else if(eventId == GUID_NULL) + { + // When DownloadDetectorData is called to set the pattern for multiple keywords + // at once, all keyword detectors must be reset. Also used during keyword detector + // initialization and cleanup to restore it back to initial state and power down. + m_SoundDetectorData1 = 0; + m_SoundDetectorArmed1 = FALSE; + m_SoundDetectorData2 = 0; + m_SoundDetectorArmed2 = FALSE; + } + else + { + return STATUS_INVALID_PARAMETER; + } + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::DownloadDetectorData(_In_ GUID eventId, _In_ LONGLONG Data) +{ + PAGED_CODE(); + + // reset the detector for this event Id + ResetDetector(eventId); + + // In this example, the driver supports detection data + // set with a single call for both detectors, or each + // detector set individually. + if (eventId == CONTOSO_KEYWORD1) + { + m_SoundDetectorData1 = Data; + } + else if(eventId == CONTOSO_KEYWORD2) + { + m_SoundDetectorData2 = Data; + } + else if(eventId == GUID_NULL) + { + // in this simplified example "Data" is set on both detectors, + // however in a real system "Data" could be a data structure which + // contains different values for each detector. + m_SoundDetectorData1 = m_SoundDetectorData2 = Data; + } + else + { + return STATUS_INVALID_PARAMETER; + } + + return STATUS_SUCCESS; +} + +// The following function is only applicable to single keyword detection systems, +// and assumes keyword detector #1. +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::GetDetectorData(_In_ GUID eventId, _Out_ LONGLONG *Data) +{ + PAGED_CODE(); + + if (eventId == CONTOSO_KEYWORD1) + { + *Data = m_SoundDetectorData1; + } + else if(eventId == CONTOSO_KEYWORD2) + { + *Data = m_SoundDetectorData2; + } + else + { + return STATUS_INVALID_PARAMETER; + } + + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +ULONGLONG CKeywordDetector::GetStartTimestamp() +{ + PAGED_CODE(); + + return m_ullKeywordStartTimestamp; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +ULONGLONG CKeywordDetector::GetStopTimestamp() +{ + PAGED_CODE(); + + return m_ullKeywordStopTimestamp; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +VOID CKeywordDetector::ResetFifo() +{ + PAGED_CODE(); + + m_qpcStartCapture = 0; + m_nLastQueuedPacket = (-1); + InitializeListHead(&PacketPoolHead); + InitializeListHead(&PacketFifoHead); + + for (int i = 0; i < ARRAYSIZE(PacketPool); i++) + { + InsertTailList(&PacketPoolHead, &PacketPool[i].ListEntry); + } + return; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::SetArmed(_In_ GUID eventId, _In_ BOOLEAN Arm) +{ + PAGED_CODE(); + + BOOL previousArming = FALSE; + NTSTATUS ntStatus = STATUS_SUCCESS; + + // the previous state is "armed" if either detector is armed. + // this reflects the fact that both detectors are sharing the + // same stream. + previousArming = m_SoundDetectorArmed1 || m_SoundDetectorArmed2; + + if (eventId == CONTOSO_KEYWORD1) + { + m_SoundDetectorArmed1 = Arm; + } + else if(eventId == CONTOSO_KEYWORD2) + { + m_SoundDetectorArmed2 = Arm; + } + else + { + return STATUS_INVALID_PARAMETER; + } + + if (Arm && !previousArming && m_qpcStartCapture == 0) + { + StartBufferingStream(); + } + else if (!Arm && previousArming && !m_streamRunning) + { + // if it's not actively streaming and everything has been disarmed, + // then stop buffering. + ResetFifo(); + } + + return ntStatus; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::GetArmed(_In_ GUID eventId, _Out_ BOOLEAN *Arm) +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (eventId == CONTOSO_KEYWORD1) + { + *Arm = m_SoundDetectorArmed1; + } + else if(eventId == CONTOSO_KEYWORD2) + { + *Arm = m_SoundDetectorArmed2; + } + else + { + return STATUS_INVALID_PARAMETER; + } + + return ntStatus; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +VOID CKeywordDetector::Run() +{ + PAGED_CODE(); + + if (m_qpcStartCapture == 0) + { + StartBufferingStream(); + } + + m_streamRunning = TRUE; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +VOID CKeywordDetector::Stop() +{ + PAGED_CODE(); + + ResetFifo(); + m_streamRunning = FALSE; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +VOID CKeywordDetector::StartBufferingStream() +{ + LARGE_INTEGER qpc; + LARGE_INTEGER qpcFrequency; + + PAGED_CODE(); + + qpc = KeQueryPerformanceCounter(&qpcFrequency); + m_qpcStartCapture = qpc.QuadPart; + m_qpcFrequency = qpcFrequency.QuadPart; + + return; +} + +PAGED_CODE_SEG +_IRQL_requires_max_(PASSIVE_LEVEL) +VOID CKeywordDetector::NotifyDetection() +{ + PAGED_CODE(); + + // A detection will only happen if armed and the + // stream is already running. If there isn't a client + // running, then set the stream start time to align + // with this detection. + if (!m_streamRunning) + { + StartBufferingStream(); + + // The following code is for testing purposes only. + // m_qpcFrequency is defined to be the number of ticks in 1 second. + // Use the stream start time (the current time retrieved in StartBufferStream) to + // mark when the keyword ended, and the start time minus 1 second worth of ticks + // to mark when the keyword started. Also, adjust the stream start time to align + // to this new keyword start time, so that the simulated stream contains the full keyword. + + m_ullKeywordStopTimestamp = m_qpcStartCapture; // stop time is the current time + m_qpcStartCapture = m_qpcStartCapture - m_qpcFrequency; // buffer start time is 1 second ago + m_ullKeywordStartTimestamp = m_qpcStartCapture; // buffer start time = keyword start time + + } + else + { + // The following code is for testing purposes only. + // If the stream is running, we cannot modify qpcStartCapture to be in + // the past, so instead make the keyword start & stop times fit within the + // time period that the keyword has been running. If it has been running + // for more than 1 second, then set the keyword start time to be 1 second back + // into the stream, as though we just figured out there was a keyword there. + // If it has been running less than one second, then the keyword size ends + // up being however long the stream has been running. + + LARGE_INTEGER qpc; + qpc = KeQueryPerformanceCounter(NULL); + + m_ullKeywordStopTimestamp = qpc.QuadPart; // stop time is the current time + + if (m_qpcStartCapture < (qpc.QuadPart - m_qpcFrequency)) + { + m_ullKeywordStartTimestamp = (qpc.QuadPart - m_qpcFrequency); + } + else + { + m_ullKeywordStartTimestamp = m_qpcStartCapture; + } + + } + + return; +} + +_IRQL_requires_min_(DISPATCH_LEVEL) +VOID CKeywordDetector::DpcRoutine(_In_ LONGLONG PerformanceCounter, _In_ LONGLONG PerformanceFrequency) +{ + LONGLONG currentPacket; + LONGLONG packetsToQueue; + + // TODO: the timer only runs when the stream is open, but really for KWS it should be building up a collection of burst data + // in the queue from 1.5 sec before the trigger happens. Is there some way to simulate that behavior here? Without doing that, + // there isn't really a burst that happens, just a trickle because while the timestamps will be right, the queue won't contain + // anything until the timer fires at the normal rate. + + if (m_qpcStartCapture <= 0) + { + return; + } + + currentPacket = (PerformanceCounter - m_qpcStartCapture) * (SamplesPerSecond / SamplesPerPacket) / PerformanceFrequency; + packetsToQueue = currentPacket - m_nLastQueuedPacket; + + while (packetsToQueue > 0) + { + LIST_ENTRY* packetListEntry; + PACKET_ENTRY* packetEntry; + + do + { + packetListEntry = ExInterlockedRemoveHeadList(&PacketPoolHead, &PacketPoolSpinLock); + if (packetListEntry != NULL) break; + + // Pool is empty, no room to buffer more, an overrun is occurring. Drop and reuse the + // oldest packet from head of fifo. + + // Since the pool is empty, the fifo should be full. However, although unlikely, the + // driver might empty the fifo before this routine removes a packet. In that case, the + // pool should have packets available again. Therefore this is a retry loop. + packetListEntry = ExInterlockedRemoveHeadList(&PacketFifoHead, &PacketFifoSpinLock); + if (packetListEntry != NULL) break; + } while (TRUE); + + packetEntry = CONTAINING_RECORD(packetListEntry, PACKET_ENTRY, ListEntry); + + packetEntry->PacketNumber = ++m_nLastQueuedPacket; + packetEntry->QpcWhenSampled = m_qpcStartCapture + (packetEntry->PacketNumber * PerformanceFrequency * SamplesPerPacket / SamplesPerSecond); + + // TODO: this should really put something real in the buffer. Use the sine tone generator maybe? + RtlZeroMemory(&packetEntry->Samples[0], sizeof(packetEntry->Samples)); + + ExInterlockedInsertTailList(&PacketFifoHead, packetListEntry, &PacketFifoSpinLock); + + packetsToQueue -= 1; + } +} + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS CKeywordDetector::GetReadPacket +( + _In_ ULONG PacketCount, + _In_ ULONG PacketSize, + _Out_writes_(PacketSize) PVOID *Packets, + _Out_ ULONG *PacketNumber, + _Out_ ULONG64 *PerformanceCounterValue, + _Out_ BOOLEAN *MoreData +) +{ + NTSTATUS ntStatus; + BYTE *packetData; + PACKET_ENTRY *packetEntry; + LIST_ENTRY *packetListEntry = NULL; + + packetListEntry = ExInterlockedRemoveHeadList(&PacketFifoHead, &PacketFifoSpinLock); + if (packetListEntry == NULL) + { + ntStatus = STATUS_DEVICE_NOT_READY; + goto Exit; + } + packetEntry = CONTAINING_RECORD(packetListEntry, PACKET_ENTRY, ListEntry); + + ntStatus = RtlLongLongToULong(packetEntry->PacketNumber, PacketNumber); + if (!NT_SUCCESS(ntStatus)) + { + goto Exit; + } + + packetData = (PBYTE) Packets[(*PacketNumber) % PacketCount]; + + *PerformanceCounterValue = packetEntry->QpcWhenSampled; + *MoreData = !IsListEmpty(&PacketFifoHead); + + // TODO: the packet size here needs to line up to the packet size allocated. + // Also, handle the first packet offset + RtlCopyMemory(packetData, packetEntry->Samples, min(sizeof(packetEntry->Samples), PacketSize)); + +Exit: + if (packetListEntry != NULL) + { + ExInterlockedInsertTailList(&PacketPoolHead, packetListEntry, &PacketPoolSpinLock); + } + + return ntStatus; +} diff --git a/audio/Acx/Samples/Common/KeywordDetector.h b/audio/Acx/Samples/Common/KeywordDetector.h new file mode 100644 index 000000000..2d5293b86 --- /dev/null +++ b/audio/Acx/Samples/Common/KeywordDetector.h @@ -0,0 +1,145 @@ +/*++ + +Copyright (c) Microsoft Corporation All Rights Reserved + +Module Name: + + KeywordDetector.h + +Abstract: + + Sample Keyword Detector. + + +--*/ + +#pragma once + +typedef struct +{ + SOUNDDETECTOR_PATTERNHEADER Header; + LONGLONG ContosoDetectorConfigurationData; +} CONTOSO_KEYWORDCONFIGURATION; + +typedef struct +{ + SOUNDDETECTOR_PATTERNHEADER Header; + LONGLONG ContosoDetectorResultData; + ULONGLONG KeywordStartTimestamp; + ULONGLONG KeywordStopTimestamp; + GUID EventId; +} CONTOSO_KEYWORDDETECTIONRESULT; + +DEFINE_GUID(CONTOSO_KEYWORDCONFIGURATION_IDENTIFIER2, +0x207f3d0c, 0x5c79, 0x496f, 0xa9, 0x4c, 0xd3, 0xd2, 0x93, 0x4d, 0xbf, 0xa9); + +// {A537F559-2D67-463B-B10E-BEB750A21F31} +DEFINE_GUID(CONTOSO_KEYWORD1, +0xa537f559, 0x2d67, 0x463b, 0xb1, 0xe, 0xbe, 0xb7, 0x50, 0xa2, 0x1f, 0x31); +// {655E417A-80A5-4A77-B3F1-512EAF67ABCF} +DEFINE_GUID(CONTOSO_KEYWORD2, +0x655e417a, 0x80a5, 0x4a77, 0xb3, 0xf1, 0x51, 0x2e, 0xaf, 0x67, 0xab, 0xcf); + +#define KEYWORDDETECTOR_POOLTAG 'KWS0' + +class CKeywordDetector +{ +public: + PAGED_CODE_SEG + CKeywordDetector(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS ResetDetector(_In_ GUID eventId); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS DownloadDetectorData(_In_ GUID eventId, _In_ LONGLONG Data); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS GetDetectorData(_In_ GUID eventId, _Out_ LONGLONG *Data); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + ULONGLONG GetStartTimestamp(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + ULONGLONG GetStopTimestamp(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS SetArmed(_In_ GUID eventId, _In_ BOOLEAN Arm); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID NotifyDetection(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS GetArmed(_In_ GUID eventId, _Out_ BOOLEAN *Arm); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID Run(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID Stop(); + + _IRQL_requires_min_(DISPATCH_LEVEL) + VOID DpcRoutine(_In_ LONGLONG PerformanceCounter, _In_ LONGLONG PerformanceFrequency); + + _IRQL_requires_max_(PASSIVE_LEVEL) + NTSTATUS GetReadPacket(_In_ ULONG PacketCount, _In_ ULONG PacketSize, _Out_writes_(PacketSize) PVOID *Packets, _Out_ ULONG *PacketNumber, _Out_ ULONGLONG *PerformanceCount, _Out_ BOOLEAN *MoreData); + +private: + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID ResetFifo(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS ReadKeywordTimestampRegistry(); + + _IRQL_requires_max_(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID StartBufferingStream(); + + // The Contoso keyword detector processes 10ms packets of 16KHz 16-bit PCM + // audio samples + static const int SamplesPerSecond = 16000; + static const int SamplesPerPacket = (10 * SamplesPerSecond / 1000); + + typedef struct + { + LIST_ENTRY ListEntry; + LONGLONG PacketNumber; + LONGLONG QpcWhenSampled; + UINT16 Samples[SamplesPerPacket]; + } PACKET_ENTRY; + + BOOLEAN m_streamRunning; + + BOOLEAN m_SoundDetectorArmed1; + BOOLEAN m_SoundDetectorArmed2; + LONGLONG m_SoundDetectorData1; + LONGLONG m_SoundDetectorData2; + + LONGLONG m_qpcStartCapture; + LONGLONG m_qpcFrequency; + LONGLONG m_nLastQueuedPacket; + + ULONGLONG m_ullKeywordStartTimestamp; + ULONGLONG m_ullKeywordStopTimestamp; + + KSPIN_LOCK PacketPoolSpinLock; + LIST_ENTRY PacketPoolHead; + PACKET_ENTRY PacketPool[1 * SamplesPerSecond / SamplesPerPacket]; // Enough storage for 1 second of audio data + + KSPIN_LOCK PacketFifoSpinLock; + LIST_ENTRY PacketFifoHead; + +}; + diff --git a/audio/Acx/Samples/Common/NewDelete.cpp b/audio/Acx/Samples/Common/NewDelete.cpp new file mode 100644 index 000000000..583d36c5c --- /dev/null +++ b/audio/Acx/Samples/Common/NewDelete.cpp @@ -0,0 +1,91 @@ +/*++ + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. +Module Name: + newdelete.cpp +Abstract: + Contains overloaded placement new and delete operators +Environment: + Kernel mode +--*/ + +#include "private.h" +#include "NewDelete.h" + +/***************************************************************************** + * ::new(POOL_FLAGS) + ***************************************************************************** + * New function for creating objects with a specified pool flags. + */ +PVOID operator new( + _In_ size_t size, + _In_ POOL_FLAGS poolFlags +) +{ + PVOID result = ExAllocatePool2(poolFlags, size, 'wNwS'); + + return result; +} + +/***************************************************************************** + * ::new(POOL_FLAGS, TAG) + ***************************************************************************** + * New function for creating objects with specified pool flags and allocation tag. + */ +PVOID operator new( + _In_ size_t size, + _In_ POOL_FLAGS poolFlags, + _In_ ULONG tag +) +{ + PVOID result = ExAllocatePool2(poolFlags, size, tag); + + return result; +} + +void __cdecl operator delete(PVOID buffer) +{ + if (buffer) + { + ExFreePool(buffer); + } +} + +void __cdecl operator delete(PVOID buffer, ULONG tag) +{ + if (buffer) + { + ExFreePoolWithTag(buffer, tag); + } +} + +void __cdecl operator delete(_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer, _In_ size_t cbSize) +{ + UNREFERENCED_PARAMETER(cbSize); + + if (buffer) + { + ExFreePool(buffer); + } +} + +void __cdecl operator delete[](_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer) +{ + if (buffer) + { + ExFreePool(buffer); + } +} + +void __cdecl operator delete[](_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer, _In_ size_t cbSize) +{ + UNREFERENCED_PARAMETER(cbSize); + + if (buffer) + { + ExFreePool(buffer); + } +} + diff --git a/audio/Acx/Samples/Common/NewDelete.h b/audio/Acx/Samples/Common/NewDelete.h new file mode 100644 index 000000000..fb660ff9c --- /dev/null +++ b/audio/Acx/Samples/Common/NewDelete.h @@ -0,0 +1,58 @@ +/*++ +Copyright (c) Microsoft Corporation. All rights reserved. + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. +Module Name: + NewDelete.h +Abstract: + Contains overloaded placement new and delete operators +Environment: + Kernel mode +--*/ + +/***************************************************************************** + * ::new(POOL_FLAGS) + ***************************************************************************** + * New function for creating objects with a specified pool flags. + */ +PVOID operator new( + _In_ size_t size, + _In_ POOL_FLAGS poolFlags +); + +/***************************************************************************** + * ::new(POOL_FLAGS, TAG) + ***************************************************************************** + * New function for creating objects with specified pool flags and allocation tag. + */ +PVOID operator new( + _In_ size_t size, + _In_ POOL_FLAGS poolFlags, + _In_ ULONG tag +); + +/***************************************************************************** + * ::delete() + ***************************************************************************** + * Delete function. + */ +void __cdecl operator delete(PVOID buffer); + +/***************************************************************************** + * ::delete() + ***************************************************************************** + * Delete function. + */ +void __cdecl operator delete(PVOID buffer, ULONG tag); + +void __cdecl operator delete[](PVOID pVoid, _In_ size_t cbSize); + +void __cdecl operator delete(_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer, _In_ size_t cbSize); + +void __cdecl operator delete[](_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer); + +void __cdecl operator delete[](_Pre_maybenull_ __drv_freesMem(Mem) PVOID buffer, _In_ size_t cbSize); + + diff --git a/audio/Acx/Samples/Common/Private.h b/audio/Acx/Samples/Common/Private.h new file mode 100644 index 000000000..da89ef785 --- /dev/null +++ b/audio/Acx/Samples/Common/Private.h @@ -0,0 +1,922 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Private.h + +Abstract: + + Contains structure definitions and function prototypes private to + the Common library. + +Environment: + + Kernel mode + +--*/ + +#ifndef _PRIVATE_H_ +#define _PRIVATE_H_ + + +#include +#include +#include "cpp_utils.h" +#include +#include +#include +#include "NewDelete.h" + +/* make prototypes usable from C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include "Trace.h" + +#include +#include + +#define PAGED_CODE_SEG __declspec(code_seg("PAGE")) +#define INIT_CODE_SEG __declspec(code_seg("INIT")) + +extern const GUID DSP_CIRCUIT_SPEAKER_GUID; +extern const GUID DSP_CIRCUIT_MICROPHONE_GUID; +extern const GUID DSP_CIRCUIT_UNIVERSALJACK_RENDER_GUID; +extern const GUID DSP_CIRCUIT_UNIVERSALJACK_CAPTURE_GUID; + +///////////////////////////////////////////////////////// +// +// Driver wide definitions +// + +// Copied from cfgmgr32.h +#if !defined(MAX_DEVICE_ID_LEN) +#define MAX_DEVICE_ID_LEN 200 +#endif + +// Number of millisecs per sec. +#define MS_PER_SEC 1000 + +// Number of hundred nanosecs per sec. +#define HNS_PER_SEC 10000000 + +#define REQUEST_TIMEOUT_SECONDS 5 + +#undef MIN +#undef MAX +#define MIN(a,b) ((a) > (b) ? (b) : (a)) +#define MAX(a,b) ((a) > (b) ? (a) : (b)) + +#ifndef BOOL +typedef int BOOL; +#endif + +#ifndef SIZEOF_ARRAY +#define SIZEOF_ARRAY(ar) (sizeof(ar)/sizeof((ar)[0])) +#endif // !defined(SIZEOF_ARRAY) + +#ifndef RGB +#define RGB(r, g, b) (DWORD)(r << 16 | g << 8 | b) +#endif + +#define ALL_CHANNELS_ID UINT32_MAX +#define MAX_CHANNELS 2 + +// +// Ks support. +// +#define KSPROPERTY_TYPE_ALL KSPROPERTY_TYPE_BASICSUPPORT | \ + KSPROPERTY_TYPE_GET | \ + KSPROPERTY_TYPE_SET + +// +// Define struct to hold signal processing mode and corresponding +// list of supported formats. +// +typedef struct +{ + GUID SignalProcessingMode; + KSDATAFORMAT_WAVEFORMATEXTENSIBLE* FormatList; + ULONG FormatListCount; +} SUPPORTED_FORMATS_LIST; + +// +// Define CAPTURE device context. +// +typedef struct _CAPTURE_DEVICE_CONTEXT { + ACXCIRCUIT Circuit; + BOOLEAN FirstTimePrepareHardware; +} CAPTURE_DEVICE_CONTEXT, * PCAPTURE_DEVICE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CAPTURE_DEVICE_CONTEXT, GetCaptureDeviceContext) + +// +// Define RENDER device context. +// +typedef struct _RENDER_DEVICE_CONTEXT { + ACXCIRCUIT Circuit; + BOOLEAN FirstTimePrepareHardware; +} RENDER_DEVICE_CONTEXT, * PRENDER_DEVICE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(RENDER_DEVICE_CONTEXT, GetRenderDeviceContext) + +// +// Define circuit/stream element context. +// +typedef struct _ELEMENT_CONTEXT { + BOOLEAN Dummy; +} ELEMENT_CONTEXT, *PELEMENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(ELEMENT_CONTEXT, GetElementContext) + +// +// Define circuit/stream element context. +// +typedef struct _MUTE_ELEMENT_CONTEXT { + BOOL MuteState[MAX_CHANNELS]; +} MUTE_ELEMENT_CONTEXT, *PMUTE_ELEMENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(MUTE_ELEMENT_CONTEXT, GetMuteElementContext) + +// +// Define circuit/stream element context. +// +typedef struct _VOLUME_ELEMENT_CONTEXT { + LONG VolumeLevel[MAX_CHANNELS]; +} VOLUME_ELEMENT_CONTEXT, *PVOLUME_ELEMENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(VOLUME_ELEMENT_CONTEXT, GetVolumeElementContext) + +#define VOLUME_STEPPING 0x8000 +#define VOLUME_LEVEL_MAXIMUM 0x00000000 +#define VOLUME_LEVEL_MINIMUM (-96 * 0x10000) + +// +// Define mute timer context. +// +typedef struct _MUTE_TIMER_CONTEXT { + ACXELEMENT MuteElement; + ACXEVENT Event; +} MUTE_TIMER_CONTEXT, *PMUTE_TIMER_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(MUTE_TIMER_CONTEXT, GetMuteTimerContext) + +// +// Define format context. +// +typedef struct _FORMAT_CONTEXT { + BOOLEAN Dummy; +} FORMAT_CONTEXT, *PFORMAT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FORMAT_CONTEXT, GetFormatContext) + +// +// Define jack context. +// +typedef struct _JACK_CONTEXT { + ULONG Dummy; +} JACK_CONTEXT, * PJACK_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(JACK_CONTEXT, GetJackContext) + +// +// Define audio engine context. +// +typedef struct _ENGINE_CONTEXT { + ACXDATAFORMAT MixFormat; +} ENGINE_CONTEXT, * PENGINE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(ENGINE_CONTEXT, GetEngineContext) + +// +// Define stream audio engine context. +// +typedef struct _STREAMAUDIOENGINE_CONTEXT { + BOOLEAN Dummy; +} STREAMAUDIOENGINE_CONTEXT, * PSTREAMAUDIOENGINE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(STREAMAUDIOENGINE_CONTEXT, GetStreamAudioEngineContext) + +// +// Define keyword spotter context +// +typedef struct _KEYWORDSPOTTER_CONTEXT { + ACXPNPEVENT Event; + PVOID KeywordDetector; +} KEYWORDSPOTTER_CONTEXT, * PKEYWORDSPOTTER_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(KEYWORDSPOTTER_CONTEXT, GetKeywordSpotterContext) + +// +// Define pnp event context. +// +typedef struct _PNPEVENT_CONTEXT { + BOOLEAN Dummy; +} PNPEVENT_CONTEXT, * PPNPEVENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PNPEVENT_CONTEXT, GetPnpEventContext) + +// +// Define peakmeter element context. +// +typedef struct _PEAKMETER_ELEMENT_CONTEXT { + LONG PeakMeterLevel[MAX_CHANNELS]; +} PEAKMETER_ELEMENT_CONTEXT, * PPEAKMETER_ELEMENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PEAKMETER_ELEMENT_CONTEXT, GetPeakMeterElementContext) + +// +// Define DSP circuit's peakmeter element context. +// +typedef struct _DSP_PEAKMETER_ELEMENT_CONTEXT +{ + PVOID peakMeter; +} DSP_PEAKMETER_ELEMENT_CONTEXT, *PDSP_PEAKMETER_ELEMENT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_PEAKMETER_ELEMENT_CONTEXT, GetDspPeakMeterElementContext) + +// +// Define stream engine context. +// +typedef struct _STREAMENGINE_CONTEXT { + PVOID StreamEngine; +} STREAMENGINE_CONTEXT, * PSTREAMENGINE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(STREAMENGINE_CONTEXT, GetStreamEngineContext) + +#define PEAKMETER_STEPPING_DELTA 0x1000 +#define PEAKMETER_MAXIMUM LONG_MAX +#define PEAKMETER_MINIMUM LONG_MIN + +///////////////////////////////////////////////////////////// +// Codec driver defintions +// + +typedef enum _CODEC_PIN_TYPE { + CodecPinTypeHost, + CodecPinTypeOffload, + CodecPinTypeLoopback, + CodecPinTypeKeyword, + CodecPinTypeDevice +} CODEC_PIN_TYPE, * PCODEC_PIN_TYPE; + +typedef struct _CODEC_PIN_CONTEXT { + CODEC_PIN_TYPE CodecPinType; +} CODEC_PIN_CONTEXT, * PCODEC_PIN_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CODEC_PIN_CONTEXT, GetCodecPinContext) + +/////////////////////////////////////////////////////////// +// Dsp driver definitions +// + +typedef enum { + CaptureHostPin = 0, + CaptureBridgePin = 1, + CaptureKWSPin = 2, + CapturePinCount = 3 +} CAPTURE_PIN_TYPE; + +typedef enum { + RenderHostPin = 0, + RenderOffloadPin = 1, + RenderLoopbackPin = 2, + RenderBridgePin = 3, + RenderPinCount = 4 +} RENDER_PIN_TYPE; + +typedef struct _DSP_PIN_CONTEXT { + ACXTARGETCIRCUIT TargetCircuit; + ULONG TargetPinId; + RENDER_PIN_TYPE RenderPinType; + CAPTURE_PIN_TYPE CapturePinType; + + // The stream bridge below will only be valid for the Capture circuit Bridge Pin + + // Host stream bridge will be used to ensure host stream creations are passed + // to the downlevel circuits. Since the HostStreamBridge won't have InModes set, + // the ACX framework will not add streams automatically. We will add streams for + // non KWS pin. + ACXSTREAMBRIDGE HostStreamBridge; +} DSP_PIN_CONTEXT, * PDSP_PIN_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_PIN_CONTEXT, GetDspPinContext) + +///////////////////////////////////////////////////////////// +// Multicircuit Dsp driver definitions +// + +// +// Circuit context for multi circuit dsp circuits. +// +typedef struct _DSP_CIRCUIT_CONTEXT +{ + ACXAUDIOENGINE AudioEngineElement; + ACXPEAKMETER PeakMeterElement; + PVOID peakMeter; + ACXKEYWORDSPOTTER KeywordSpotter; + BOOLEAN IsRenderCircuit; +} DSP_CIRCUIT_CONTEXT, *PDSP_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_CIRCUIT_CONTEXT, GetDspCircuitContext) + +typedef struct _DSP_ENGINE_CONTEXT +{ + ACXDATAFORMAT MixFormat; + BOOLEAN GFxEnabled; +} DSP_ENGINE_CONTEXT, *PDSP_ENGINE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_ENGINE_CONTEXT, GetDspEngineContext) + +typedef struct _DSP_STREAMAUDIOENGINE_CONTEXT +{ + BOOLEAN LFxEnabled; +} DSP_STREAMAUDIOENGINE_CONTEXT, *PDSP_STREAMAUDIOENGINE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_STREAMAUDIOENGINE_CONTEXT, GetDspStreamAudioEngineContext) + +///////////////////////////////////////////////////////// +// +// Codec Render (speaker) definitions +// + +// +// Define render circuit context. +// +typedef struct _CODEC_RENDER_CIRCUIT_CONTEXT { + ACXVOLUME VolumeElement; + ACXMUTE MuteElement; + ACXPEAKMETER PeakMeterElement; + ACXAUDIOENGINE AudioEngineElement; +} CODEC_RENDER_CIRCUIT_CONTEXT, * PCODEC_RENDER_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CODEC_RENDER_CIRCUIT_CONTEXT, GetRenderCircuitContext) + +typedef enum { + CodecRenderHostPin = 0, + CodecRenderBridgePin = 1, + CodecRenderPinCount = 2 +} CODEC_RENDER_PINS; + +typedef enum { + RenderVolumeIndex = 0, + RenderMuteIndex = 1, + RenderElementCount = 2 +} CODEC_RENDER_ELEMENTS; + +// Render callbacks. + +EVT_ACX_CIRCUIT_CREATE_STREAM CodecR_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP CodecR_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN CodecR_EvtCircuitPowerDown; +EVT_ACX_STREAM_SET_RENDER_PACKET CodecR_EvtStreamSetRenderPacket; +EVT_ACX_STREAM_GET_CAPTURE_PACKET CodecR_EvtStreamGetLoopbackPacket; +EVT_ACX_PIN_SET_DATAFORMAT CodecR_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CodecR_EvtPinContextCleanup; +EVT_ACX_MUTE_ASSIGN_STATE CodecR_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE CodecR_EvtMuteRetrieveState; +EVT_ACX_VOLUME_ASSIGN_LEVEL CodecR_EvtVolumeAssignLevel; +EVT_ACX_VOLUME_RETRIEVE_LEVEL CodecR_EvtVolumeRetrieveLevel; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL CodecR_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_RAMPED_VOLUME_ASSIGN_LEVEL CodecR_EvtRampedVolumeAssignLevel; +EVT_ACX_AUDIOENGINE_RETRIEVE_BUFFER_SIZE_LIMITS CodecR_EvtAcxAudioEngineRetrieveBufferSizeLimits; +EVT_ACX_AUDIOENGINE_RETRIEVE_EFFECTS_STATE CodecR_EvtAcxAudioEngineRetrieveEffectsState; +EVT_ACX_AUDIOENGINE_ASSIGN_EFFECTS_STATE CodecR_EvtAcxAudioEngineAssignEffectsState; +EVT_ACX_AUDIOENGINE_ASSIGN_ENGINE_FORMAT CodecR_EvtAcxAudioEngineAssignEngineDeviceFormat; +EVT_ACX_AUDIOENGINE_RETRIEVE_ENGINE_FORMAT CodecR_EvtAcxAudioEngineRetrieveEngineMixFormat; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_EFFECTS_STATE CodecR_EvtAcxStreamAudioEngineRetrieveEffectsState; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_EFFECTS_STATE CodecR_EvtAcxStreamAudioEngineAssignEffectsState; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_PRESENTATION_POSITION CodecR_EvtAcxStreamAudioEngineRetrievePresentationPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_CURRENT_WRITE_POSITION CodecR_EvtAcxStreamAudioEngineAssignCurrentWritePosition; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_LINEAR_BUFFER_POSITION CodecR_EvtAcxStreamAudioEngineRetrieveLinearBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LAST_BUFFER_POSITION CodecR_EvtAcxStreamAudioEngineAssignLastBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LOOPBACK_PROTECTION CodecR_EvtAcxStreamAudioEngineAssignLoopbackProtection; + +PAGED_CODE_SEG +NTSTATUS +CodecR_CreateRenderCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// Codec Capture (microphone) definitions +// + +// +// Define capture circuit context. +// +typedef struct _CODEC_CAPTURE_CIRCUIT_CONTEXT { + ACXVOLUME BoostElement; + ACXVOLUME VolumeElement; + ACXKEYWORDSPOTTER KeywordSpotter; +} CODEC_CAPTURE_CIRCUIT_CONTEXT, * PCODEC_CAPTURE_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CODEC_CAPTURE_CIRCUIT_CONTEXT, GetCaptureCircuitContext) + +typedef enum { + CodecCaptureHostPin = 0, + CodecCaptureBridgePin = 1, + CodecCapturePinCount = 2 +} CODEC_CAPTURE_PINS; + +typedef enum { + CaptureVolumeIndex = 0, + CaptureElementCount = 1 +} CAPTURE_ELEMENTS; + +// Capture callbacks. + +EVT_ACX_CIRCUIT_CREATE_STREAM CodecC_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP CodecC_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN CodecC_EvtCircuitPowerDown; +EVT_ACX_VOLUME_ASSIGN_LEVEL CodecC_EvtVolumeAssignLevelCallback; +EVT_ACX_VOLUME_RETRIEVE_LEVEL CodecC_EvtVolumeRetrieveLevelCallback; +EVT_ACX_VOLUME_ASSIGN_LEVEL CodecC_EvtBoostAssignLevelCallback; +EVT_ACX_VOLUME_RETRIEVE_LEVEL CodecC_EvtBoostRetrieveLevelCallback; +EVT_ACX_STREAM_GET_CAPTURE_PACKET CodecC_EvtStreamGetCapturePacket; +EVT_ACX_PIN_SET_DATAFORMAT CodecC_EvtAcxPinSetDataFormat; +EVT_ACX_PIN_RETRIEVE_NAME CodecC_EvtAcxPinRetrieveName; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CodecC_EvtPinContextCleanup; +EVT_ACX_KEYWORDSPOTTER_RETRIEVE_ARM CodecC_EvtAcxKeywordSpotterRetrieveArm; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_ARM CodecC_EvtAcxKeywordSpotterAssignArm; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_PATTERNS CodecC_EvtAcxKeywordSpotterAssignPatterns; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_RESET CodecC_EvtAcxKeywordSpotterAssignReset; + +PAGED_CODE_SEG +NTSTATUS +CodecC_CreateCaptureCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// MicArray definitions +// + +// +// Define MicArray circuit context. +// +typedef struct _MICARRAY_CIRCUIT_CONTEXT { + ACXMUTE MuteElement; + ACXVOLUME VolumeElement; + ACXPEAKMETER PeakMeterElement; + ACXKEYWORDSPOTTER KeywordSpotter; +} MICARRAY_CIRCUIT_CONTEXT, * PMICARRAY_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(MICARRAY_CIRCUIT_CONTEXT, GetMicArrayCircuitContext) + +typedef enum { + MicArrayVolumeIndex = 0, + MicArrayMuteIndex = 1, + MicArrayPeakmeterIndex = 2, + MicArrayKWSIndex = 3, + MicArrayElementCount = 4 +} MICARRAY_ELEMENTS; + +// MicArray callbacks. + +EVT_ACX_MUTE_ASSIGN_STATE MicArray_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE MicArray_EvtMuteRetrieveState; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL MicArray_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_CIRCUIT_CREATE_STREAM MicArray_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP MicArray_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN MicArray_EvtCircuitPowerDown; +EVT_ACX_VOLUME_ASSIGN_LEVEL MicArray_EvtVolumeAssignLevelCallback; +EVT_ACX_VOLUME_RETRIEVE_LEVEL MicArray_EvtVolumeRetrieveLevelCallback; +EVT_ACX_STREAM_GET_CAPTURE_PACKET MicArray_EvtStreamGetCapturePacket; +EVT_ACX_PIN_SET_DATAFORMAT MicArray_EvtAcxPinSetDataFormat; +EVT_ACX_PIN_RETRIEVE_NAME MicArray_EvtAcxPinRetrieveName; +EVT_WDF_DEVICE_CONTEXT_CLEANUP MicArray_EvtPinContextCleanup; +EVT_ACX_KEYWORDSPOTTER_RETRIEVE_ARM MicArray_EvtAcxKeywordSpotterRetrieveArm; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_ARM MicArray_EvtAcxKeywordSpotterAssignArm; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_PATTERNS MicArray_EvtAcxKeywordSpotterAssignPatterns; +EVT_ACX_KEYWORDSPOTTER_ASSIGN_RESET MicArray_EvtAcxKeywordSpotterAssignReset; +EVT_ACX_PIN_CONNECTED MicArray_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED MicArray_EvtPinDisconnected; +EVT_WDF_DEVICE_CONTEXT_CLEANUP MicArray_EvtDeviceContextCleanup; +EVT_ACX_OBJECT_PROCESS_REQUEST MicArray_EvtPinProposeDataFormat2Callback; +EVT_ACX_OBJECT_PREPROCESS_REQUEST MicArray_EvtAudioCpuResourcesCallback; + +PAGED_CODE_SEG +NTSTATUS +MicArray_CreateCaptureCircuit( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ GUID MicCustomName, + _In_ UNICODE_STRING CircuitName, + _Out_ ACXCIRCUIT * Circuit +); + +PAGED_CODE_SEG +NTSTATUS +MicArray_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +///////////////////////////////////////////////////////// +// +// Microphone (external: headphone) definitions +// + +// +// Define MicrophoneHp circuit context. +// +typedef struct _MICROPHONEHP_CIRCUIT_CONTEXT { + ACXMUTE MuteElement; + ACXVOLUME VolumeElement; + ACXPEAKMETER PeakMeterElement; +} MICROPHONEHP_CIRCUIT_CONTEXT, * PMICROPHONEHP_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(MICROPHONEHP_CIRCUIT_CONTEXT, GetMicrophoneHpCircuitContext) + +typedef enum { + MicrophoneHpVolumeIndex = 0, + MicrophoneHpMuteIndex = 1, + MicrophoneHpPeakmeterIndex = 2, + MicrophoneHpElementCount = 3 +} MICROPHONEHP_ELEMENTS; + +// MicrophoneHp callbacks. + +EVT_ACX_MUTE_ASSIGN_STATE MicrophoneHp_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE MicrophoneHp_EvtMuteRetrieveState; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL MicrophoneHp_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_CIRCUIT_CREATE_STREAM MicrophoneHp_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP MicrophoneHp_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN MicrophoneHp_EvtCircuitPowerDown; +EVT_ACX_VOLUME_ASSIGN_LEVEL MicrophoneHp_EvtVolumeAssignLevelCallback; +EVT_ACX_VOLUME_RETRIEVE_LEVEL MicrophoneHp_EvtVolumeRetrieveLevelCallback; +EVT_ACX_STREAM_GET_CAPTURE_PACKET MicrophoneHp_EvtStreamGetCapturePacket; +EVT_ACX_PIN_SET_DATAFORMAT MicrophoneHp_EvtAcxPinSetDataFormat; +EVT_ACX_PIN_RETRIEVE_NAME MicrophoneHp_EvtAcxPinRetrieveName; +EVT_WDF_DEVICE_CONTEXT_CLEANUP MicrophoneHp_EvtPinContextCleanup; +EVT_ACX_PIN_CONNECTED MicrophoneHp_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED MicrophoneHp_EvtPinDisconnected; +EVT_ACX_OBJECT_PREPROCESS_REQUEST MicrophoneHp_EvtAudioCpuResourcesCallback; + +PAGED_CODE_SEG +NTSTATUS +MicrophoneHp_CreateCaptureCircuit( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ GUID MicCustomName, + _In_ UNICODE_STRING CircuitName, + _Out_ ACXCIRCUIT * Circuit +); + +PAGED_CODE_SEG +NTSTATUS +MicrophoneHp_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +///////////////////////////////////////////////////////// +// +// Speaker definitions +// + +// +// Define circuit context for Speaker and SpeakerHp. +// +typedef struct _DSP_RENDER_CIRCUIT_CONTEXT { + ACXPEAKMETER PeakMeterElement; + ACXAUDIOENGINE AudioEngineElement; + PVOID PeakMeter; +} DSP_RENDER_CIRCUIT_CONTEXT, * PDSP_RENDER_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_RENDER_CIRCUIT_CONTEXT, GetSpeakerCircuitContext) + +// Speaker callbacks. + +EVT_ACX_CIRCUIT_CREATE_STREAM Speaker_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP Speaker_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN Speaker_EvtCircuitPowerDown; +EVT_ACX_STREAM_SET_RENDER_PACKET Speaker_EvtStreamSetRenderPacket; +EVT_ACX_STREAM_GET_CAPTURE_PACKET Speaker_EvtStreamGetLoopbackPacket; +EVT_ACX_PIN_SET_DATAFORMAT Speaker_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP Speaker_EvtPinContextCleanup; +EVT_ACX_PIN_CONNECTED Speaker_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED Speaker_EvtPinDisconnected; + +//Render Audio Engine callbacks. + +EVT_ACX_MUTE_ASSIGN_STATE Speaker_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE Speaker_EvtMuteRetrieveState; +EVT_ACX_VOLUME_RETRIEVE_LEVEL Speaker_EvtVolumeRetrieveLevel; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL Speaker_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_RAMPED_VOLUME_ASSIGN_LEVEL Speaker_EvtRampedVolumeAssignLevel; +EVT_ACX_AUDIOENGINE_RETRIEVE_BUFFER_SIZE_LIMITS Speaker_EvtAcxAudioEngineRetrieveBufferSizeLimits; +EVT_ACX_AUDIOENGINE_RETRIEVE_EFFECTS_STATE Speaker_EvtAcxAudioEngineRetrieveEffectsState; +EVT_ACX_AUDIOENGINE_ASSIGN_EFFECTS_STATE Speaker_EvtAcxAudioEngineAssignEffectsState; +EVT_ACX_AUDIOENGINE_ASSIGN_ENGINE_FORMAT Speaker_EvtAcxAudioEngineAssignEngineDeviceFormat; +EVT_ACX_AUDIOENGINE_RETRIEVE_ENGINE_FORMAT Speaker_EvtAcxAudioEngineRetrieveEngineMixFormat; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_EFFECTS_STATE Speaker_EvtAcxStreamAudioEngineRetrieveEffectsState; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_EFFECTS_STATE Speaker_EvtAcxStreamAudioEngineAssignEffectsState; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_PRESENTATION_POSITION Speaker_EvtAcxStreamAudioEngineRetrievePresentationPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_CURRENT_WRITE_POSITION Speaker_EvtAcxStreamAudioEngineAssignCurrentWritePosition; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_LINEAR_BUFFER_POSITION Speaker_EvtAcxStreamAudioEngineRetrieveLinearBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LAST_BUFFER_POSITION Speaker_EvtAcxStreamAudioEngineAssignLastBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LOOPBACK_PROTECTION Speaker_EvtAcxStreamAudioEngineAssignLoopbackProtection; + +PAGED_CODE_SEG +NTSTATUS +Speaker_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +Speaker_CreateRenderCircuit( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ UNICODE_STRING CircuitName, + _In_ BOOLEAN IsHeadphones, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// HDMI definitions +// + +// +// Define HDMI circuit context. +// +typedef struct _DSP_HDMI_CIRCUIT_CONTEXT { + ACXVOLUME VolumeElement; + ACXMUTE MuteElement; + ACXPEAKMETER PeakmeterElement; +} DSP_HDMI_CIRCUIT_CONTEXT, * PDSP_HDMI_CIRCUIT_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_HDMI_CIRCUIT_CONTEXT, GetHDMICircuitContext) + +typedef enum { + HDMIVolumeIndex = 0, + HDMIMuteIndex = 1, + HDMIPeakmeterIndex = 2, + HDMIElementCount = 3 +} HDMI_ELEMENTS; + +typedef enum { + HDMIHostPin = 0, + HDMILoopbackPin = 1, + HDMIBridgePin = 2, + HDMIPinCount = 3 +} HDMI_PIN_TYPE; + +typedef struct _HDMI_PIN_CONTEXT { + ACXTARGETCIRCUIT TargetCircuit; + ULONG TargetPinId; + HDMI_PIN_TYPE PinType; + CAPTURE_PIN_TYPE CapturePinType; +} HDMI_PIN_CONTEXT, * PHDMI_PIN_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(HDMI_PIN_CONTEXT, GetHDMIPinContext) + +typedef struct _HDMI_STREAM_CONTEXT { + HDMI_PIN_TYPE PinType; + CAPTURE_PIN_TYPE CapturePinType; +} HDMI_STREAM_CONTEXT, * PHDMI_STREAM_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(HDMI_STREAM_CONTEXT, GetHDMIStreamContext) + +// HDMI callbacks. +EVT_ACX_CIRCUIT_CREATE_STREAM HDMI_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP HDMI_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN HDMI_EvtCircuitPowerDown; +EVT_ACX_STREAM_SET_RENDER_PACKET HDMI_EvtStreamSetRenderPacket; +EVT_ACX_STREAM_GET_CAPTURE_PACKET HDMI_EvtStreamGetLoopbackPacket; +EVT_ACX_PIN_SET_DATAFORMAT HDMI_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP HDMI_EvtPinContextCleanup; +EVT_ACX_PIN_CONNECTED HDMI_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED HDMI_EvtPinDisconnected; +EVT_WDF_DEVICE_CONTEXT_CLEANUP HDMI_EvtDeviceContextCleanup; +EVT_ACX_MUTE_ASSIGN_STATE HDMI_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE HDMI_EvtMuteRetrieveState; +EVT_ACX_VOLUME_ASSIGN_LEVEL HDMI_EvtRampedVolumeAssignLevel; +EVT_ACX_VOLUME_RETRIEVE_LEVEL HDMI_EvtVolumeRetrieveLevel; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL HDMI_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_OBJECT_PREPROCESS_REQUEST HDMI_EvtAudioCpuResourcesCallback; + +PAGED_CODE_SEG +NTSTATUS +HDMI_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +HDMI_CreateRenderCircuit( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ UNICODE_STRING CircuitName, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// Multi circuit codec Render (speaker) definitions +// + +// Uses the same circuit context, render pin, and render element definitions as Codec Render. + +// Render callbacks. +EVT_ACX_CIRCUIT_CREATE_STREAM RenderMC_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP RenderMC_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN RenderMC_EvtCircuitPowerDown; +EVT_ACX_PIN_SET_DATAFORMAT RenderMC_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP RenderMC_EvtPinContextCleanup; +EVT_ACX_MUTE_ASSIGN_STATE RenderMC_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE RenderMC_EvtMuteRetrieveState; +EVT_ACX_VOLUME_RETRIEVE_LEVEL RenderMC_EvtVolumeRetrieveLevel; +EVT_ACX_RAMPED_VOLUME_ASSIGN_LEVEL RenderMC_EvtRampedVolumeAssignLevel; + +PAGED_CODE_SEG +NTSTATUS +RenderMC_CreateRenderCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName, + _In_ const UNICODE_STRING * Uri, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// Multi circuit codec Capture (microphone) definitions +// + +// Uses the same circuit context, render pin, and render element definitions as Codec Capture. + +// Capture callbacks. +EVT_ACX_CIRCUIT_CREATE_STREAM CaptureMC_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP CaptureMC_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN CaptureMC_EvtCircuitPowerDown; +EVT_ACX_STREAM_GET_CAPTURE_PACKET CaptureMC_EvtStreamGetCapturePacket; +EVT_ACX_PIN_SET_DATAFORMAT CaptureMC_EvtAcxPinSetDataFormat; +EVT_ACX_PIN_RETRIEVE_NAME CaptureMC_EvtAcxPinRetrieveName; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CaptureMC_EvtPinContextCleanup; + +PAGED_CODE_SEG +NTSTATUS +CaptureMC_CreateCaptureCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName, + _In_ const UNICODE_STRING * Uri, + _Out_ ACXCIRCUIT * Circuit +); + +///////////////////////////////////////////////////////// +// +// Multi circuit dsp Render (speaker) definitions +// + +// Uses the same circuit context, render pin, and render element definitions as Codec Render. + +// Render callbacks. +EVT_ACX_CIRCUIT_COMPOSITE_CIRCUIT_INITIALIZE RenderMCDsp_EvtCircuitCompositeCircuitInitialize; +EVT_ACX_CIRCUIT_COMPOSITE_INITIALIZE RenderMCDsp_EvtCircuitCompositeInitialize; +EVT_WDF_DEVICE_CONTEXT_CLEANUP RenderMCDsp_EvtCircuitContextCleanup; +EVT_WDF_DEVICE_PREPARE_HARDWARE RenderMCDsp_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE RenderMCDsp_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_SELF_MANAGED_IO_INIT RenderMCDsp_EvtDeviceSelfManagedIoInit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP RenderMCDsp_EvtDeviceContextCleanup; +EVT_ACX_CIRCUIT_CREATE_STREAM RenderMCDsp_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP RenderMCDsp_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN RenderMCDsp_EvtCircuitPowerDown; +EVT_ACX_STREAM_SET_RENDER_PACKET RenderMCDsp_EvtStreamSetRenderPacket; +EVT_ACX_PIN_SET_DATAFORMAT RenderMCDsp_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP RenderMCDsp_EvtPinContextCleanup; +EVT_ACX_PIN_CONNECTED RenderMCDsp_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED RenderMCDsp_EvtPinDisconnected; + +// Render Audio Engine +EVT_ACX_MUTE_ASSIGN_STATE DspR_EvtMuteAssignState; +EVT_ACX_MUTE_RETRIEVE_STATE DspR_EvtMuteRetrieveState; +EVT_ACX_VOLUME_RETRIEVE_LEVEL DspR_EvtVolumeRetrieveLevel; +EVT_ACX_PEAKMETER_RETRIEVE_LEVEL DspR_EvtPeakMeterRetrieveLevelCallback; +EVT_ACX_RAMPED_VOLUME_ASSIGN_LEVEL DspR_EvtRampedVolumeAssignLevel; +EVT_ACX_AUDIOENGINE_RETRIEVE_BUFFER_SIZE_LIMITS DspR_EvtAcxAudioEngineRetrieveBufferSizeLimits; +EVT_ACX_AUDIOENGINE_RETRIEVE_EFFECTS_STATE DspR_EvtAcxAudioEngineRetrieveEffectsState; +EVT_ACX_AUDIOENGINE_ASSIGN_EFFECTS_STATE DspR_EvtAcxAudioEngineAssignEffectsState; +EVT_ACX_AUDIOENGINE_RETRIEVE_ENGINE_FORMAT DspR_EvtAcxAudioEngineRetrieveEngineMixFormat; +EVT_ACX_AUDIOENGINE_ASSIGN_ENGINE_FORMAT DspR_EvtAcxAudioEngineAssignEngineDeviceFormat; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_EFFECTS_STATE DspR_EvtAcxStreamAudioEngineRetrieveEffectsState; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_EFFECTS_STATE DspR_EvtAcxStreamAudioEngineAssignEffectsState; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_PRESENTATION_POSITION DspR_EvtAcxStreamAudioEngineRetrievePresentationPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_CURRENT_WRITE_POSITION DspR_EvtAcxStreamAudioEngineAssignCurrentWritePosition; +EVT_ACX_STREAMAUDIOENGINE_RETRIEVE_LINEAR_BUFFER_POSITION DspR_EvtAcxStreamAudioEngineRetrieveLinearBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LAST_BUFFER_POSITION DspR_EvtAcxStreamAudioEngineAssignLastBufferPosition; +EVT_ACX_STREAMAUDIOENGINE_ASSIGN_LOOPBACK_PROTECTION DspR_EvtAcxStreamAudioEngineAssignLoopbackProtection; + +PAGED_CODE_SEG +NTSTATUS +RenderMCDsp_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS CreateRenderCircuit( + _In_ PACXCIRCUIT_INIT CircuitInit, + _In_ UNICODE_STRING CircuitName, + _In_ WDFDEVICE Device, + _Out_ ACXCIRCUIT* Circuit +); + +PAGED_CODE_SEG +NTSTATUS CreateRenderMCDspPin( + _In_ ACX_PIN_TYPE PinType, + _In_ ACXCIRCUIT Circuit, + _In_ ACX_PIN_COMMUNICATION Communication, + _In_ const GUID* Category, + _In_ ACX_PIN_CALLBACKS* PinCallbacks, + _In_ bool Mic, + _Out_ ACXPIN* Pin +); + +PAGED_CODE_SEG +NTSTATUS CreateAudioEngine( + _In_ ACXCIRCUIT Circuit, + _In_reads_(PinCount) ACXPIN* Pins, + _In_ ULONG PinCount, + _Out_ ACXAUDIOENGINE* AudioEngineElement +); + +///////////////////////////////////////////////////////// +// +// Multi circuit dsp Capture (microphone) definitions +// + +// Uses the same circuit context, capture pin and capture element definitions as Codec Capture. + +// Capture callbacks. +EVT_ACX_CIRCUIT_COMPOSITE_CIRCUIT_INITIALIZE CaptureMCDsp_EvtCircuitCompositeCircuitInitialize; +EVT_ACX_CIRCUIT_COMPOSITE_INITIALIZE CaptureMCDsp_EvtCircuitCompositeInitialize; +EVT_WDF_DEVICE_PREPARE_HARDWARE CaptureMCDsp_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE CaptureMCDsp_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_SELF_MANAGED_IO_INIT CaptureMCDsp_EvtDeviceSelfManagedIoInit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CaptureMCDsp_EvtDeviceContextCleanup; +EVT_ACX_CIRCUIT_CREATE_STREAM CaptureMCDsp_EvtCircuitCreateStream; +EVT_ACX_CIRCUIT_POWER_UP CaptureMCDsp_EvtCircuitPowerUp; +EVT_ACX_CIRCUIT_POWER_DOWN CaptureMCDsp_EvtCircuitPowerDown; +EVT_ACX_STREAM_GET_CAPTURE_PACKET CaptureMCDsp_EvtStreamGetCapturePacket; +EVT_ACX_PIN_SET_DATAFORMAT CaptureMCDsp_EvtAcxPinSetDataFormat; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CaptureMCDsp_EvtPinContextCleanup; +EVT_ACX_PIN_CONNECTED CaptureMCDsp_EvtPinConnected; +EVT_ACX_PIN_DISCONNECTED CaptureMCDsp_EvtPinDisconnected; + +PAGED_CODE_SEG +NTSTATUS +CaptureMCDsp_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS CreateCaptureCircuit( + _In_ PACXCIRCUIT_INIT CircuitInit, + _In_ UNICODE_STRING CircuitName, + _In_ WDFDEVICE Device, + _Out_ ACXCIRCUIT* Circuit +); + +PAGED_CODE_SEG +NTSTATUS CreateCaptureMCDspPin( + _In_ ACX_PIN_TYPE PinType, + _In_ ACXCIRCUIT Circuit, + _In_ ACX_PIN_COMMUNICATION Communication, + _In_ const GUID* Category, + _In_ ACX_PIN_CALLBACKS* PinCallbacks, + _In_ bool Mic, + _Out_ ACXPIN* Pin +); + +/* make internal prototypes usable from C++ */ +#ifdef __cplusplus +} +#endif + + + +#endif // _PRIVATE_H_ diff --git a/audio/Acx/Samples/Common/RenderCircuit.cpp b/audio/Acx/Samples/Common/RenderCircuit.cpp new file mode 100644 index 000000000..2f5abd130 --- /dev/null +++ b/audio/Acx/Samples/Common/RenderCircuit.cpp @@ -0,0 +1,807 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + RenderCircuit.cpp + +Abstract: + + Render Circuit. This file contains routines to create and handle + render circuit with no offload. + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "public.h" +#include +#include +#include +#include "AudioFormats.h" +#include "streamengine.h" +#include "cpp_utils.h" +#include "circuithelper.h" + +#ifndef __INTELLISENSE__ +#include "renderCircuit.tmh" +#endif + +PAGED_CODE_SEG +NTSTATUS +CodecR_EvtAcxPinSetDataFormat( + _In_ ACXPIN Pin, + _In_ ACXDATAFORMAT DataFormat +) +/*++ + +Routine Description: + + This ACX pin callback sets the device/mixed format. + +Return Value: + + NTSTATUS + +--*/ +{ + UNREFERENCED_PARAMETER(Pin); + UNREFERENCED_PARAMETER(DataFormat); + + PAGED_CODE(); + + // NOTE: update device/mixed format here. + + return STATUS_NOT_SUPPORTED; +} + +/////////////////////////////////////////////////////////// +// +// For more information on mute element see: https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/ksnodetype-mute +// +_Use_decl_annotations_ +NTSTATUS +NTAPI +CodecR_EvtMuteAssignState( + _In_ ACXMUTE Mute, + _In_ ULONG Channel, + _In_ ULONG State +) +{ + PMUTE_ELEMENT_CONTEXT muteCtx; + ULONG i; + + PAGED_CODE(); + + muteCtx = GetMuteElementContext(Mute); + ASSERT(muteCtx); + + // + // Use first channel for all channels setting. + // + if (Channel != ALL_CHANNELS_ID) + { + muteCtx->MuteState[Channel] = State; + } + else + { + for (i = 0; i < MAX_CHANNELS; ++i) + { + muteCtx->MuteState[i] = State; + } + } + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +NTSTATUS +NTAPI +CodecR_EvtMuteRetrieveState( + _In_ ACXMUTE Mute, + _In_ ULONG Channel, + _Out_ ULONG * State +) +{ + PMUTE_ELEMENT_CONTEXT muteCtx; + + PAGED_CODE(); + + muteCtx = GetMuteElementContext(Mute); + ASSERT(muteCtx); + + // + // Use first channel for all channels setting. + // + if (Channel != ALL_CHANNELS_ID) + { + *State = muteCtx->MuteState[Channel]; + } + else + { + *State = muteCtx->MuteState[0]; + } + + return STATUS_SUCCESS; +} + +/////////////////////////////////////////////////////////// +// +// For more information on volume element see: https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/ksnodetype-volume +// +_Use_decl_annotations_ +NTSTATUS +NTAPI +CodecR_EvtRampedVolumeAssignLevel( + _In_ ACXVOLUME Volume, + _In_ ULONG Channel, + _In_ LONG VolumeLevel, + _In_ ACX_VOLUME_CURVE_TYPE CurveType, + _In_ ULONGLONG CurveDuration +) +{ + PVOLUME_ELEMENT_CONTEXT volumeCtx; + ULONG i; + + PAGED_CODE(); + + UNREFERENCED_PARAMETER(CurveType); + UNREFERENCED_PARAMETER(CurveDuration); + + volumeCtx = GetVolumeElementContext(Volume); + ASSERT(volumeCtx); + + if (Channel != ALL_CHANNELS_ID) + { + volumeCtx->VolumeLevel[Channel] = VolumeLevel; + } + else + { + for (i = 0; i < MAX_CHANNELS; ++i) + { + volumeCtx->VolumeLevel[i] = VolumeLevel; + } + } + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +NTSTATUS +NTAPI +CodecR_EvtVolumeRetrieveLevel( + _In_ ACXVOLUME Volume, + _In_ ULONG Channel, + _Out_ LONG * VolumeLevel +) +{ + PVOLUME_ELEMENT_CONTEXT volumeCtx; + + PAGED_CODE(); + + volumeCtx = GetVolumeElementContext(Volume); + ASSERT(volumeCtx); + + if (Channel != ALL_CHANNELS_ID) + { + *VolumeLevel = volumeCtx->VolumeLevel[Channel]; + } + else + { + *VolumeLevel = volumeCtx->VolumeLevel[0]; + } + + return STATUS_SUCCESS; +} + +VOID +CodecR_EvtPinContextCleanup( + _In_ WDFOBJECT WdfPin +) +/*++ + +Routine Description: + + In this callback, it cleans up pin context. + +Arguments: + + WdfDevice - WDF device object + +Return Value: + + nullptr + +--*/ +{ + + UNREFERENCED_PARAMETER(WdfPin); +} + +PAGED_CODE_SEG +NTSTATUS +CodecR_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName +) +/*++ + +Routine Description: + + Creates the static render circuit (pictured below) and + adds it to the device context. This is called when a + new device is detected and the AddDevice call is made + by the pnp manager. + + *************************************************************************** + * Render Circuit * + * * + * +--------------------------------------------+ * + * | | * + * | +-------------+ +-------------+ | * + * Host ------>| | Volume Node | | Mute Node | |---> Bridge * + * Pin | +-------------+ +-------------+ | Pin * + * | | * + * +--------------------------------------------+ * + * * + *************************************************************************** + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + PCODEC_DEVICE_CONTEXT devCtx; + PRENDER_DEVICE_CONTEXT renderDevCtx; + ACXCIRCUIT renderCircuit = nullptr; + WDF_OBJECT_ATTRIBUTES attributes; + + PAGED_CODE(); + + devCtx = GetCodecDeviceContext(Device); + ASSERT(devCtx != nullptr); + + // + // Alloc audio context to current device. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, RENDER_DEVICE_CONTEXT); + RETURN_NTSTATUS_IF_FAILED(WdfObjectAllocateContext(Device, &attributes, (PVOID*)&renderDevCtx)); + ASSERT(renderDevCtx); + + // + // Create a render circuit associated with this child device. + // + RETURN_NTSTATUS_IF_FAILED(CodecR_CreateRenderCircuit(Device, ComponentGuid, CircuitName, &renderCircuit)); + + devCtx->Render = renderCircuit; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +Render_AllocateSupportedFormats( + _In_ WDFDEVICE Device, + _In_reads_bytes_(CodecRenderPinCount) ACXPIN Pin[], + _In_ ACXCIRCUIT Circuit, + _In_ size_t CodecRenderPinCount +) +{ + UNREFERENCED_PARAMETER(CodecRenderPinCount); + + NTSTATUS status = STATUS_SUCCESS; + ACXDATAFORMAT formatPcm44100c2; + ACXDATAFORMAT formatPcm48000c2; + ACXDATAFORMATLIST formatList; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + /////////////////////////////////////////////////////////// + // + // Allocate the formats this circuit supports. + // + + RETURN_NTSTATUS_IF_FAILED(AllocateFormat(Pcm44100c2, Circuit, Device, &formatPcm44100c2)); + RETURN_NTSTATUS_IF_FAILED(AllocateFormat(Pcm48000c2, Circuit, Device, &formatPcm48000c2)); + + /////////////////////////////////////////////////////////// + // + // Define supported formats for the host pin. + // + + // + // The raw processing mode list is associated with each single circuit + // by ACX. The driver uses this DDI to retrieve the built-in raw + // data-format list. + // + RETURN_NTSTATUS_IF_TRUE(CodecRenderHostPin >= CodecRenderPinCount, STATUS_INVALID_PARAMETER); + formatList = AcxPinGetRawDataFormatList(Pin[CodecRenderHostPin]); + RETURN_NTSTATUS_IF_TRUE(formatList == nullptr, STATUS_INSUFFICIENT_RESOURCES); + + // + // The driver uses this DDI to add data formats to the raw + // processing mode list associated with the current circuit. + // + RETURN_NTSTATUS_IF_FAILED(AcxDataFormatListAddDataFormat(formatList, formatPcm44100c2)); + RETURN_NTSTATUS_IF_FAILED(AcxDataFormatListAddDataFormat(formatList, formatPcm48000c2)); + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CodecR_CreateRenderCircuit( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName, + _Out_ ACXCIRCUIT* Circuit +) +/*++ + +Routine Description: + + This routine builds the CODEC render circuit. + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + ACXCIRCUIT circuit; + CODEC_RENDER_CIRCUIT_CONTEXT* circuitCtx; + ACXPIN pin[CodecRenderPinCount]; + + PAGED_CODE(); + + // + // Init output value. + // + *Circuit = nullptr; + + /////////////////////////////////////////////////////////// + // + // Create a circuit. + // + { + PACXCIRCUIT_INIT circuitInit = nullptr; + ACX_CIRCUIT_PNPPOWER_CALLBACKS powerCallbacks; + + // + // The driver uses this DDI to allocate an ACXCIRCUIT_INIT + // structure. This opaque structure is used when creating + // a standalone audio circuit representing an audio device. + // + circuitInit = AcxCircuitInitAllocate(Device); + + // + // The driver uses this DDI to free the allocated + // ACXCIRCUIT_INIT structure when an error is detected. + // Normally the structures is deleted/cleared by ACX when + // an ACX circuit is created successfully. + // + auto circuitInitScope = scope_exit([&circuitInit]() { + if (circuitInit) { + AcxCircuitInitFree(circuitInit); + } + }); + + // + // The driver uses this DDI to specify the Component ID + // of the ACX circuit. This ID is a guid that uniquely + // identifies the circuit instance (vendor specific). + // + AcxCircuitInitSetComponentId(circuitInit, ComponentGuid); + + // + // The driver uses this DDI to specify the circuit name. + // For standalone circuits, this is the audio device name + // which is used by clients to open handles to the audio devices. + // + (VOID)AcxCircuitInitAssignName(circuitInit, CircuitName); + + // + // The driver uses this DDI to specify the circuit type. The + // circuit type can be AcxCircuitTypeRender, AcxCircuitTypeCapture, + // AcxCircuitTypeOther, or AcxCircuitTypeMaximum (for validation). + // + AcxCircuitInitSetCircuitType(circuitInit, AcxCircuitTypeRender); + + // + // The driver uses this DDI to assign its (if any) power callbacks. + // + ACX_CIRCUIT_PNPPOWER_CALLBACKS_INIT(&powerCallbacks); + powerCallbacks.EvtAcxCircuitPowerUp = CodecR_EvtCircuitPowerUp; + powerCallbacks.EvtAcxCircuitPowerDown = CodecR_EvtCircuitPowerDown; + AcxCircuitInitSetAcxCircuitPnpPowerCallbacks(circuitInit, &powerCallbacks); + + // + // The driver uses this DDI to register for a stream-create callback. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitInitAssignAcxCreateStreamCallback(circuitInit, CodecR_EvtCircuitCreateStream)); + + // + // The driver uses this DDI to create a new ACX circuit. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_RENDER_CIRCUIT_CONTEXT); + RETURN_NTSTATUS_IF_FAILED(AcxCircuitCreate(Device, &attributes, &circuitInit, &circuit)); + + circuitInitScope.release(); + + circuitCtx = GetRenderCircuitContext(circuit); + ASSERT(circuitCtx); + } + + // + // Post circuit creation initialization. + // + + /////////////////////////////////////////////////////////// + // + // Create mute and volume elements. + // + { + ACXELEMENT elements[RenderElementCount] = { 0 }; + + // + // The driver uses this DDI to assign its volume element callbacks. + // + ACX_VOLUME_CALLBACKS volumeCallbacks; + ACX_VOLUME_CALLBACKS_INIT(&volumeCallbacks); + volumeCallbacks.EvtAcxRampedVolumeAssignLevel = CodecR_EvtRampedVolumeAssignLevel; + volumeCallbacks.EvtAcxVolumeRetrieveLevel = CodecR_EvtVolumeRetrieveLevel; + + // + // Create Volume element + // + ACX_VOLUME_CONFIG volumeCfg; + ACX_VOLUME_CONFIG_INIT(&volumeCfg); + volumeCfg.ChannelsCount = MAX_CHANNELS; + volumeCfg.Minimum = VOLUME_LEVEL_MINIMUM; + volumeCfg.Maximum = VOLUME_LEVEL_MAXIMUM; + volumeCfg.SteppingDelta = VOLUME_STEPPING; + volumeCfg.Name = &KSAUDFNAME_VOLUME_CONTROL; + volumeCfg.Callbacks = &volumeCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, VOLUME_ELEMENT_CONTEXT); + attributes.ParentObject = circuit; + + RETURN_NTSTATUS_IF_FAILED(AcxVolumeCreate(circuit, &attributes, &volumeCfg, (ACXVOLUME*)&elements[RenderVolumeIndex])); + + // + // The driver uses this DDI to assign its mute element callbacks. + // + ACX_MUTE_CALLBACKS muteCallbacks; + ACX_MUTE_CALLBACKS_INIT(&muteCallbacks); + muteCallbacks.EvtAcxMuteAssignState = CodecR_EvtMuteAssignState; + muteCallbacks.EvtAcxMuteRetrieveState = CodecR_EvtMuteRetrieveState; + + // + // Create Mute element + // + ACX_MUTE_CONFIG muteCfg; + ACX_MUTE_CONFIG_INIT(&muteCfg); + muteCfg.ChannelsCount = MAX_CHANNELS; + muteCfg.Name = &KSAUDFNAME_WAVE_MUTE; + muteCfg.Callbacks = &muteCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, MUTE_ELEMENT_CONTEXT); + attributes.ParentObject = circuit; + + RETURN_NTSTATUS_IF_FAILED(AcxMuteCreate(circuit, &attributes, &muteCfg, (ACXMUTE*)&elements[RenderMuteIndex])); + + // + // Saving the volume and mute elements in the circuit context. + // + circuitCtx->VolumeElement = (ACXVOLUME)elements[RenderVolumeIndex]; + circuitCtx->MuteElement = (ACXMUTE)elements[RenderMuteIndex]; + + // + // The driver uses this DDI post circuit creation to add ACXELEMENTs. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitAddElements(circuit, elements, SIZEOF_ARRAY(elements))); + } + + /////////////////////////////////////////////////////////// + // + // Create the pins for the circuit. + // + { + ACX_PIN_CONFIG pinCfg; + CODEC_PIN_CONTEXT* pinCtx; + ACX_PIN_CALLBACKS pinCallbacks; + + /////////////////////////////////////////////////////////// + // + // Create Render Pin. + // + + ACX_PIN_CALLBACKS_INIT(&pinCallbacks); + pinCallbacks.EvtAcxPinSetDataFormat = CodecR_EvtAcxPinSetDataFormat; + + ACX_PIN_CONFIG_INIT(&pinCfg); + pinCfg.Type = AcxPinTypeSink; + pinCfg.Communication = AcxPinCommunicationSink; + pinCfg.Category = &KSCATEGORY_AUDIO; + pinCfg.PinCallbacks = &pinCallbacks; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_PIN_CONTEXT); + attributes.EvtCleanupCallback = CodecR_EvtPinContextCleanup; + attributes.ParentObject = circuit; + + // + // The driver uses this DDI to create one or more pins on the circuits. + // + RETURN_NTSTATUS_IF_FAILED(AcxPinCreate(circuit, &attributes, &pinCfg, &pin[CodecRenderHostPin])); + + ASSERT(pin[CodecRenderHostPin] != nullptr); + pinCtx = GetCodecPinContext(pin[CodecRenderHostPin]); + ASSERT(pinCtx); + pinCtx->CodecPinType = CodecPinTypeHost; + + /////////////////////////////////////////////////////////// + // + // Create Device Bridge Pin. + // + + ACX_PIN_CONFIG_INIT(&pinCfg); + pinCfg.Type = AcxPinTypeSource; + pinCfg.Communication = AcxPinCommunicationNone; + pinCfg.Category = &KSNODETYPE_SPEAKER; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CODEC_PIN_CONTEXT); + attributes.EvtCleanupCallback = CodecR_EvtPinContextCleanup; + attributes.ParentObject = circuit; + + // + // The driver uses this DDI to create one or more pins on the circuits. + // + RETURN_NTSTATUS_IF_FAILED(AcxPinCreate(circuit, &attributes, &pinCfg, &pin[CodecRenderBridgePin])); + + ASSERT(pin[CodecRenderBridgePin] != nullptr); + pinCtx = GetCodecPinContext(pin[CodecRenderBridgePin]); + ASSERT(pinCtx); + pinCtx->CodecPinType = CodecPinTypeDevice; + } + + /////////////////////////////////////////////////////////// + // + // Add audio jack to bridge pin. + // For more information on audio jack see: https://docs.microsoft.com/en-us/windows/win32/api/devicetopology/ns-devicetopology-ksjack_description + // + { + ACX_JACK_CONFIG jackCfg; + ACXJACK jack; + PJACK_CONTEXT jackCtx; + + ACX_JACK_CONFIG_INIT(&jackCfg); + jackCfg.Description.ChannelMapping = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; + jackCfg.Description.Color = RGB(0, 0, 0); + jackCfg.Description.ConnectionType = AcxConnTypeAtapiInternal; + jackCfg.Description.GeoLocation = AcxGeoLocFront; + jackCfg.Description.GenLocation = AcxGenLocPrimaryBox; + jackCfg.Description.PortConnection = AcxPortConnIntegratedDevice; + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, JACK_CONTEXT); + attributes.ParentObject = pin[CodecRenderBridgePin]; + + RETURN_NTSTATUS_IF_FAILED(AcxJackCreate(pin[CodecRenderBridgePin], &attributes, &jackCfg, &jack)); + + ASSERT(jack != nullptr); + + jackCtx = GetJackContext(jack); + ASSERT(jackCtx); + jackCtx->Dummy = 0; + + RETURN_NTSTATUS_IF_FAILED(AcxPinAddJacks(pin[CodecRenderBridgePin], &jack, 1)); + } + + RETURN_NTSTATUS_IF_FAILED(Render_AllocateSupportedFormats(Device, pin, circuit, CodecRenderPinCount)); + + /////////////////////////////////////////////////////////// + // + // The driver uses this DDI post circuit creation to add ACXPINs. + // + RETURN_NTSTATUS_IF_FAILED(AcxCircuitAddPins(circuit, pin, CodecRenderPinCount)); + + // + // Set output value. + // + *Circuit = circuit; + + // + // Done. + // + status = STATUS_SUCCESS; + + return status; +} + +_Use_decl_annotations_ +NTSTATUS +CodecR_EvtCircuitPowerUp( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ WDF_POWER_DEVICE_STATE PreviousState +) +{ + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(Circuit); + UNREFERENCED_PARAMETER(PreviousState); + + PAGED_CODE(); + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +NTSTATUS +CodecR_EvtCircuitPowerDown( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ WDF_POWER_DEVICE_STATE TargetState +) +{ + UNREFERENCED_PARAMETER(Device); + UNREFERENCED_PARAMETER(Circuit); + UNREFERENCED_PARAMETER(TargetState); + + PAGED_CODE(); + + return STATUS_SUCCESS; +} + +PAGED_CODE_SEG +NTSTATUS +CodecR_EvtCircuitCreateStream( + _In_ WDFDEVICE Device, + _In_ ACXCIRCUIT Circuit, + _In_ ACXPIN Pin, + _In_ PACXSTREAM_INIT StreamInit, + _In_ ACXDATAFORMAT StreamFormat, + _In_ const GUID* SignalProcessingMode, + _In_ ACXOBJECTBAG VarArguments +) +/*++ + +Routine Description: + + This routine creates a stream for the specified circuit. + +Return Value: + + NT status value + +--*/ +{ + NTSTATUS status; + PRENDER_DEVICE_CONTEXT devCtx; + WDF_OBJECT_ATTRIBUTES attributes; + ACXSTREAM stream; + STREAMENGINE_CONTEXT * streamCtx; + ACX_STREAM_CALLBACKS streamCallbacks; + ACX_RT_STREAM_CALLBACKS rtCallbacks; + CRenderStreamEngine* renderStreamEngine = nullptr; + CODEC_PIN_TYPE codecPinType; + PCODEC_PIN_CONTEXT pinCtx; + ACX_PIN_TYPE pinType; + CODEC_RENDER_CIRCUIT_CONTEXT* circuitCtx; + + auto streamEngineScope = scope_exit([&renderStreamEngine]() { + + delete renderStreamEngine; + + }); + + PAGED_CODE(); + UNREFERENCED_PARAMETER(SignalProcessingMode); + UNREFERENCED_PARAMETER(VarArguments); + + ASSERT(IsEqualGUID(*SignalProcessingMode, AUDIO_SIGNALPROCESSINGMODE_RAW)); + + ASSERT(Circuit != nullptr); + circuitCtx = GetRenderCircuitContext(Circuit); + ASSERT(circuitCtx); + + devCtx = GetRenderDeviceContext(Device); + ASSERT(devCtx != nullptr); + UNREFERENCED_PARAMETER(devCtx); + + pinCtx = GetCodecPinContext(Pin); + codecPinType = pinCtx->CodecPinType; + + pinType = AcxPinGetType(Pin); + + // + // Init streaming callbacks. + // + ACX_STREAM_CALLBACKS_INIT(&streamCallbacks); + streamCallbacks.EvtAcxStreamPrepareHardware = EvtStreamPrepareHardware; + streamCallbacks.EvtAcxStreamReleaseHardware = EvtStreamReleaseHardware; + streamCallbacks.EvtAcxStreamRun = EvtStreamRun; + streamCallbacks.EvtAcxStreamPause = EvtStreamPause; + + RETURN_NTSTATUS_IF_FAILED(AcxStreamInitAssignAcxStreamCallbacks(StreamInit, &streamCallbacks)); + + // + // Init RT streaming callbacks. + // + ACX_RT_STREAM_CALLBACKS_INIT(&rtCallbacks); + rtCallbacks.EvtAcxStreamGetHwLatency = EvtStreamGetHwLatency; + rtCallbacks.EvtAcxStreamAllocateRtPackets = EvtStreamAllocateRtPackets; + rtCallbacks.EvtAcxStreamFreeRtPackets = EvtStreamFreeRtPackets; + rtCallbacks.EvtAcxStreamSetRenderPacket = CodecR_EvtStreamSetRenderPacket; + rtCallbacks.EvtAcxStreamGetCurrentPacket = EvtStreamGetCurrentPacket; + rtCallbacks.EvtAcxStreamGetPresentationPosition = EvtStreamGetPresentationPosition; + + RETURN_NTSTATUS_IF_FAILED(AcxStreamInitAssignAcxRtStreamCallbacks(StreamInit, &rtCallbacks)); + + // + // Buffer notifications are supported. + // + AcxStreamInitSetAcxRtStreamSupportsNotifications(StreamInit); + + // + // Create the stream. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, STREAMENGINE_CONTEXT); + attributes.EvtDestroyCallback = EvtStreamDestroy; + RETURN_NTSTATUS_IF_FAILED(AcxRtStreamCreate(Device, Circuit, &attributes, &StreamInit, &stream)); + + // + // Create the virtual streaming engine which will control + // streaming logic for the render circuit. + // + renderStreamEngine = new (POOL_FLAG_NON_PAGED, DeviceDriverTag) CRenderStreamEngine(stream, StreamFormat, FALSE, NULL); + RETURN_NTSTATUS_IF_TRUE(renderStreamEngine == nullptr, STATUS_INSUFFICIENT_RESOURCES); + + streamCtx = GetStreamEngineContext(stream); + ASSERT(streamCtx); + streamCtx->StreamEngine = (PVOID)renderStreamEngine; + + renderStreamEngine = nullptr; + + // + // Done. + // + status = STATUS_SUCCESS; + + return status; +} + +PAGED_CODE_SEG +NTSTATUS +CodecR_EvtStreamSetRenderPacket( + _In_ ACXSTREAM Stream, + _In_ ULONG Packet, + _In_ ULONG Flags, + _In_ ULONG EosPacketLength +) +{ + PSTREAMENGINE_CONTEXT ctx; + CRenderStreamEngine* streamEngine = nullptr; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = static_cast(ctx->StreamEngine); + + return streamEngine->SetRenderPacket(Packet, Flags, EosPacketLength); +} + diff --git a/audio/Acx/Samples/Common/SamplesCommon.vcxproj b/audio/Acx/Samples/Common/SamplesCommon.vcxproj new file mode 100644 index 000000000..85e164d7f --- /dev/null +++ b/audio/Acx/Samples/Common/SamplesCommon.vcxproj @@ -0,0 +1,304 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM + + + Release + ARM + + + Debug + ARM64 + + + Release + ARM64 + + + + {6A946D59-6690-4ED0-A77D-7D4C3D4B3241} + {497e31cb-056b-4f31-abb8-447fd55ee5a5} + v4.5 + 12.0 + Debug + Win32 + SamplesCommon + $(LatestTargetPlatformVersion) + + + + Windows10 + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + Windows10 + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + Windows Driver + 1 + 31 + + + + + + + + + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + DbgengKernelDebugger + $(IntDir) + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + true + true + trace_macros.h + true + $(SDK_INC_PATH);$(DDK_INC_PATH)\acx\km\1.1;..\inc;..\shared;%(AdditionalIncludeDirectories) + ACX_VERSION_MAJOR=1;ACX_VERSION_MINOR=1;KMDF_VERSION_MAJOR=1;KMDF_VERSION_MINOR=31;%(PreprocessorDefinitions) + + + sha256 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/audio/Acx/Samples/Common/SaveData.cpp b/audio/Acx/Samples/Common/SaveData.cpp new file mode 100644 index 000000000..72e98850d --- /dev/null +++ b/audio/Acx/Samples/Common/SaveData.cpp @@ -0,0 +1,1103 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SaveData.cpp + +Abstract: + + Implementation of data saving class for ACX driver samples. + + To save the playback data to disk, this class maintains a circular data + buffer, associated frame structures and worker items to save frames to + disk. + Each frame structure represents a portion of buffer. When that portion + of frame is full, a workitem is scheduled to save it to disk. + + + +--*/ +#pragma warning (disable : 4127) +#pragma warning (disable : 26165) + + +#include "private.h" +#include +#include +#include +#include +#include "savedata.h" +#include // This is for using RtlStringCbPrintf + +#define SAVEDATA_POOLTAG 'TDVS' +#define SAVEDATA_POOLTAG1 '1DVS' +#define SAVEDATA_POOLTAG2 '2DVS' +#define SAVEDATA_POOLTAG3 '3DVS' +#define SAVEDATA_POOLTAG4 '4DVS' +#define SAVEDATA_POOLTAG5 '5DVS' +#define SAVEDATA_POOLTAG6 '6DVS' +#define SAVEDATA_POOLTAG7 '7DVS' + +//============================================================================= +// Defines +//============================================================================= +#define RIFF_TAG 0x46464952; +#define WAVE_TAG 0x45564157; +#define FMT__TAG 0x20746D66; +#define DATA_TAG 0x61746164; + +#define DEFAULT_FRAME_COUNT 4 +#define DEFAULT_FRAME_SIZE PAGE_SIZE * 4 +#define DEFAULT_BUFFER_SIZE DEFAULT_FRAME_SIZE * DEFAULT_FRAME_COUNT + +#define DEFAULT_FILE_FOLDER1 L"\\DriverData\\Audio_Samples" +#define DEFAULT_FILE_FOLDER2 L"\\DriverData\\Audio_Samples\\AudioCodec" +#define DEFAULT_FILE_NAME L"\\DriverData\\Audio_Samples\\AudioCodec\\STREAM" +#define OFFLOAD_FILE_NAME L"OFFLOAD" +#define HOST_FILE_NAME L"HOST" + +#define MAX_WORKER_ITEM_COUNT 15 + + +PSAVEWORKER_PARAM CSaveData::m_pWorkItems = NULL; +PDEVICE_OBJECT CSaveData::m_pDeviceObject = NULL; + +//============================================================================= +// Statics +//============================================================================= +ULONG CSaveData::m_ulStreamId = 0; +ULONG CSaveData::m_ulOffloadStreamId = 0; + +//============================================================================= +// CSaveData +//============================================================================= + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +CSaveData::CSaveData() +: m_pDataBuffer(NULL), + m_FileHandle(NULL), + m_ulFrameCount(DEFAULT_FRAME_COUNT), + m_ulBufferSize(DEFAULT_BUFFER_SIZE), + m_ulFrameSize(DEFAULT_FRAME_SIZE), + m_ulBufferOffset(0), + m_ulFrameIndex(0), + m_fFrameUsed(NULL), + m_waveFormat(NULL), + m_pFilePtr(NULL), + m_fWriteDisabled(FALSE), + m_bInitialized(FALSE) +{ + PAGED_CODE(); + + m_FileHeader.dwRiff = RIFF_TAG; + m_FileHeader.dwFileSize = 0; + m_FileHeader.dwWave = WAVE_TAG; + m_FileHeader.dwFormat = FMT__TAG; + m_FileHeader.dwFormatLength = sizeof(WAVEFORMATEX); + + m_DataHeader.dwData = DATA_TAG; + m_DataHeader.dwDataLength = 0; + + RtlZeroMemory(&m_objectAttributes, sizeof(m_objectAttributes)); +} // CSaveData + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +CSaveData::~CSaveData() +{ + PAGED_CODE(); + Cleanup(); +} // CSaveData + +void +_Use_decl_annotations_ +PAGED_CODE_SEG +CSaveData::Cleanup +( + void +) +{ + PAGED_CODE(); + + // Update the wave header in data file with real file size. + // + if(m_pFilePtr) + { + // RIFF header, whose size is the whole file size minus RIFF header. + m_FileHeader.dwFileSize = + (DWORD)m_pFilePtr->QuadPart - 2 * sizeof(DWORD); + // The data length is the size of all the audio that was written. + // It gets calculated by taking: + m_DataHeader.dwDataLength = (DWORD)m_pFilePtr->QuadPart - // the whole file size, + sizeof(m_FileHeader) - // minus the file header, + m_FileHeader.dwFormatLength - // minus the format, + sizeof(m_DataHeader); // minus the data header itself. + + if (STATUS_SUCCESS == KeWaitForSingleObject + ( + &m_FileSync, + Executive, + KernelMode, + FALSE, + NULL + )) + { + if (NT_SUCCESS(FileOpen(FALSE))) + { + FileWriteHeader(); + + FileClose(); + } + + KeReleaseMutex(&m_FileSync, FALSE); + } + + m_FileHeader.dwRiff = RIFF_TAG; + m_FileHeader.dwFileSize = 0; + m_FileHeader.dwWave = WAVE_TAG; + m_FileHeader.dwFormat = FMT__TAG; + m_FileHeader.dwFormatLength = sizeof(WAVEFORMATEX); + + m_DataHeader.dwData = DATA_TAG; + m_DataHeader.dwDataLength = 0; + m_pFilePtr = NULL; + } + + if (m_waveFormat) + { + ExFreePoolWithTag(m_waveFormat, SAVEDATA_POOLTAG1); + m_waveFormat = NULL; + } + + if (m_fFrameUsed) + { + ExFreePoolWithTag(m_fFrameUsed, SAVEDATA_POOLTAG2); + m_fFrameUsed = NULL; + } + + if (m_FileName.Buffer) + { + ExFreePoolWithTag(m_FileName.Buffer, SAVEDATA_POOLTAG3); + m_FileName.Buffer = NULL; + } + + if (m_pDataBuffer) + { + ExFreePoolWithTag(m_pDataBuffer, SAVEDATA_POOLTAG4); + m_pDataBuffer = NULL; + } +} + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +void +CSaveData::DestroyWorkItems +( + void +) +{ + PAGED_CODE(); + + if (m_pWorkItems) + { + for (int i = 0; i < MAX_WORKER_ITEM_COUNT; i++) + { + if (m_pWorkItems[i].WorkItem!=NULL) + { + IoFreeWorkItem(m_pWorkItems[i].WorkItem); + m_pWorkItems[i].WorkItem = NULL; + } + } + ExFreePoolWithTag(m_pWorkItems, SAVEDATA_POOLTAG); + m_pWorkItems = NULL; + } + +} // DestroyWorkItems + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +void +CSaveData::Disable +( + _In_ BOOL fDisable +) +{ + PAGED_CODE(); + + m_fWriteDisabled = fDisable; +} // Disable + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::FileClose(void) +{ + PAGED_CODE(); + + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (m_FileHandle) + { + ntStatus = ZwClose(m_FileHandle); + m_FileHandle = NULL; + } + + return ntStatus; +} // FileClose + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::FileOpen +( + _In_ BOOL fOverWrite +) +{ + PAGED_CODE(); + + NTSTATUS ntStatus = STATUS_SUCCESS; + IO_STATUS_BLOCK ioStatusBlock; + + if( FALSE == m_bInitialized ) + { + return STATUS_UNSUCCESSFUL; + } + + if(!m_FileHandle) + { + ntStatus = + ZwCreateFile + ( + &m_FileHandle, + GENERIC_WRITE | SYNCHRONIZE, + &m_objectAttributes, + &ioStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL, + 0, + fOverWrite ? FILE_OVERWRITE_IF : FILE_OPEN_IF, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0 + ); + } + + return ntStatus; +} // FileOpen + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::FileWrite +( + _In_reads_bytes_(ulDataSize) PBYTE pData, + _In_ ULONG ulDataSize +) +{ + PAGED_CODE(); + + ASSERT(pData); + ASSERT(m_pFilePtr); + + NTSTATUS ntStatus; + + if (m_FileHandle) + { + IO_STATUS_BLOCK ioStatusBlock; + + ntStatus = ZwWriteFile( m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + pData, + ulDataSize, + m_pFilePtr, + NULL); + + if (NT_SUCCESS(ntStatus)) + { + ASSERT(ioStatusBlock.Information == ulDataSize); + + m_pFilePtr->QuadPart += ulDataSize; + } + } + else + { + ntStatus = STATUS_INVALID_HANDLE; + } + + return ntStatus; +} // FileWrite + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::FileWriteHeader(void) +{ + PAGED_CODE(); + + NTSTATUS ntStatus; + + if (m_FileHandle && m_waveFormat) + { + IO_STATUS_BLOCK ioStatusBlock; + + m_pFilePtr->QuadPart = 0; + + m_FileHeader.dwFormatLength = (m_waveFormat->wFormatTag == WAVE_FORMAT_PCM) ? + sizeof( PCMWAVEFORMAT ) : + sizeof( WAVEFORMATEX ) + m_waveFormat->cbSize; + + ntStatus = ZwWriteFile( m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + &m_FileHeader, + sizeof(m_FileHeader), + m_pFilePtr, + NULL); + + if (NT_SUCCESS(ntStatus)) + { + m_pFilePtr->QuadPart += sizeof(m_FileHeader); + + ntStatus = ZwWriteFile( m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + m_waveFormat, + m_FileHeader.dwFormatLength, + m_pFilePtr, + NULL); + } + + if (NT_SUCCESS(ntStatus)) + { + m_pFilePtr->QuadPart += m_FileHeader.dwFormatLength; + + ntStatus = ZwWriteFile( m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + &m_DataHeader, + sizeof(m_DataHeader), + m_pFilePtr, + NULL); + } + + if (NT_SUCCESS(ntStatus)) + { + m_pFilePtr->QuadPart += sizeof(m_DataHeader); + } + } + else + { + ntStatus = STATUS_INVALID_HANDLE; + } + + + return ntStatus; +} // FileWriteHeader + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::SetDeviceObject +( + _In_ PDEVICE_OBJECT DeviceObject +) +{ + PAGED_CODE(); + + ASSERT(DeviceObject); + + NTSTATUS ntStatus = STATUS_SUCCESS; + + m_pDeviceObject = DeviceObject; + return ntStatus; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +PDEVICE_OBJECT +CSaveData::GetDeviceObject +( + void +) +{ + PAGED_CODE(); + + return m_pDeviceObject; +} + +//============================================================================= +_Use_decl_annotations_ +PSAVEWORKER_PARAM +CSaveData::GetNewWorkItem +( + void +) +{ + LARGE_INTEGER timeOut = { 0 }; + NTSTATUS ntStatus; + + for (int i = 0; i < MAX_WORKER_ITEM_COUNT; i++) + { + ntStatus = + KeWaitForSingleObject + ( + &m_pWorkItems[i].EventDone, + Executive, + KernelMode, + FALSE, + &timeOut + ); + if (STATUS_SUCCESS == ntStatus) + { + if (m_pWorkItems[i].WorkItem) + return &(m_pWorkItems[i]); + else + return NULL; + } + } + + return NULL; +} // GetNewWorkItem + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::Initialize +( + _In_ BOOL _bOffloaded +) +{ + PAGED_CODE(); + + NTSTATUS ntStatus = STATUS_SUCCESS; + WCHAR szTemp[MAX_PATH]; + size_t cLen = 0; + IO_STATUS_BLOCK ioStatusBlock = {0}; + HANDLE fileHandle; + OBJECT_ATTRIBUTES objectAttributes; + UNICODE_STRING fileName; + + if (_bOffloaded) + { + m_ulOffloadStreamId++; + } + else + { + m_ulStreamId++; + } + + RtlInitUnicodeString(&fileName, DEFAULT_FILE_FOLDER1); + InitializeObjectAttributes( + &objectAttributes, + &fileName, + OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, + NULL, + NULL); + + // Create the folder. + ntStatus = ZwCreateFile( + &fileHandle, + 0, + &objectAttributes, + &ioStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL, + 0, + FILE_OPEN_IF, + FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + if (NT_SUCCESS(ntStatus)) + { + ZwClose(fileHandle); + fileHandle = NULL; + + RtlInitUnicodeString(&fileName, DEFAULT_FILE_FOLDER2); + InitializeObjectAttributes( + &objectAttributes, + &fileName, + OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, + NULL, + NULL); + + // Create the folder. + ntStatus = ZwCreateFile( + &fileHandle, + 0, + &objectAttributes, + &ioStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL, + 0, + FILE_OPEN_IF, + FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + if (NT_SUCCESS(ntStatus)) + { + ZwClose(fileHandle); + fileHandle = NULL; + } + } + + if (NT_SUCCESS(ntStatus)) + { + // Allocate data file name. + // + RtlStringCchPrintfW(szTemp, MAX_PATH, L"%s_%s_%d.wav", DEFAULT_FILE_NAME, _bOffloaded ? OFFLOAD_FILE_NAME : HOST_FILE_NAME, _bOffloaded ? m_ulOffloadStreamId : m_ulStreamId); + m_FileName.Length = 0; + ntStatus = RtlStringCchLengthW (szTemp, sizeof(szTemp)/sizeof(szTemp[0]), &cLen); + } + + if (NT_SUCCESS(ntStatus)) + { + m_FileName.MaximumLength = (USHORT)((cLen * sizeof(WCHAR)) + sizeof(WCHAR));//convert to wchar and add room for NULL + m_FileName.Buffer = (PWSTR) + ExAllocatePool2 + ( + POOL_FLAG_PAGED, + m_FileName.MaximumLength, + SAVEDATA_POOLTAG3 + ); + if (!m_FileName.Buffer) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + } + + // Allocate memory for data buffer. + // + if (NT_SUCCESS(ntStatus)) + { + RtlStringCbCopyW(m_FileName.Buffer, m_FileName.MaximumLength, szTemp); + m_FileName.Length = (USHORT)wcslen(m_FileName.Buffer) * sizeof(WCHAR); + + m_pDataBuffer = (PBYTE) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + m_ulBufferSize, + SAVEDATA_POOLTAG4 + ); + if (!m_pDataBuffer) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + } + + // Allocate memory for frame usage flags and m_pFilePtr. + // + if (NT_SUCCESS(ntStatus)) + { + m_fFrameUsed = (PBOOL) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + m_ulFrameCount * sizeof(BOOL) + + sizeof(LARGE_INTEGER), + SAVEDATA_POOLTAG2 + ); + if (!m_fFrameUsed) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + } + + // Initialize the spinlock to synchronize access to the frames + // + KeInitializeSpinLock ( &m_FrameInUseSpinLock ) ; + + // Initialize the file mutex + // + KeInitializeMutex( &m_FileSync, 1 ) ; + + // Open the data file. + // + if (NT_SUCCESS(ntStatus)) + { + // m_fFrameUsed has additional memory to hold m_pFilePtr + // + m_pFilePtr = (PLARGE_INTEGER) + (((PBYTE) m_fFrameUsed) + m_ulFrameCount * sizeof(BOOL)); + + // Create data file. + InitializeObjectAttributes + ( + &m_objectAttributes, + &m_FileName, + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, + NULL + ); + + m_bInitialized = TRUE; + + // Write wave header information to data file. + ntStatus = KeWaitForSingleObject + ( + &m_FileSync, + Executive, + KernelMode, + FALSE, + NULL + ); + + if (STATUS_SUCCESS == ntStatus) + { + ntStatus = FileOpen(TRUE); + if (NT_SUCCESS(ntStatus)) + { + ntStatus = FileWriteHeader(); + + FileClose(); + } + + KeReleaseMutex( &m_FileSync, FALSE ); + } + } + + return ntStatus; +} // Initialize + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::InitializeWorkItems +( + _In_ PDEVICE_OBJECT DeviceObject +) +{ + PAGED_CODE(); + + ASSERT(DeviceObject); + + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (m_pWorkItems != NULL) + { + return ntStatus; + } + + m_pWorkItems = (PSAVEWORKER_PARAM) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + sizeof(SAVEWORKER_PARAM) * MAX_WORKER_ITEM_COUNT, + SAVEDATA_POOLTAG + ); + if (m_pWorkItems) + { + for (int i = 0; i < MAX_WORKER_ITEM_COUNT; i++) + { + + m_pWorkItems[i].WorkItem = IoAllocateWorkItem(DeviceObject); + if(m_pWorkItems[i].WorkItem == NULL) + { + return STATUS_INSUFFICIENT_RESOURCES; + } + KeInitializeEvent + ( + &m_pWorkItems[i].EventDone, + NotificationEvent, + TRUE + ); + } + } + else + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + + return ntStatus; +} // InitializeWorkItems + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +VOID +SaveFrameWorkerCallback +( + _In_ PDEVICE_OBJECT pDeviceObject, + _In_opt_ PVOID Context +) +{ + UNREFERENCED_PARAMETER(pDeviceObject); + + PAGED_CODE(); + + ASSERT(Context); + + PSAVEWORKER_PARAM pParam = (PSAVEWORKER_PARAM) Context; + PCSaveData pSaveData; + + if (NULL == pParam) + { + // This is completely unexpected, assert here. + // + ASSERT(pParam); + return; + } + + ASSERT(pParam->pSaveData); + ASSERT(pParam->pSaveData->m_fFrameUsed); + + if (pParam->WorkItem) + { + pSaveData = pParam->pSaveData; + + if (STATUS_SUCCESS == KeWaitForSingleObject + ( + &pSaveData->m_FileSync, + Executive, + KernelMode, + FALSE, + NULL + )) + { + if (NT_SUCCESS(pSaveData->FileOpen(FALSE))) + { + pSaveData->FileWrite(pParam->pData, pParam->ulDataSize); + pSaveData->FileClose(); + } + InterlockedExchange( (LONG *)&(pSaveData->m_fFrameUsed[pParam->ulFrameNo]), FALSE ); + + KeReleaseMutex( &pSaveData->m_FileSync, FALSE ); + } + } + + KeSetEvent(&pParam->EventDone, 0, FALSE); +} // SaveFrameWorkerCallback + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::SetDataFormat +( + _In_ PKSDATAFORMAT pDataFormat +) +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + + ASSERT(pDataFormat); + + PWAVEFORMATEX pwfx = NULL; + + if (IsEqualGUIDAligned(pDataFormat->Specifier, + KSDATAFORMAT_SPECIFIER_DSOUND)) + { + pwfx = + &(((PKSDATAFORMAT_DSOUND) pDataFormat)->BufferDesc.WaveFormatEx); + } + else if (IsEqualGUIDAligned(pDataFormat->Specifier, + KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)) + { + pwfx = &((PKSDATAFORMAT_WAVEFORMATEX) pDataFormat)->WaveFormatEx; + } + + if (pwfx) + { + // Free the previously allocated waveformat + if (m_waveFormat) + { + ExFreePoolWithTag(m_waveFormat, SAVEDATA_POOLTAG1); + } + + m_waveFormat = (PWAVEFORMATEX) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + (pwfx->wFormatTag == WAVE_FORMAT_PCM) ? + sizeof( PCMWAVEFORMAT ) : + sizeof( WAVEFORMATEX ) + pwfx->cbSize, + SAVEDATA_POOLTAG1 + ); + + if(m_waveFormat) + { + RtlCopyMemory( m_waveFormat, + pwfx, + (pwfx->wFormatTag == WAVE_FORMAT_PCM) ? + sizeof( PCMWAVEFORMAT ) : + sizeof( WAVEFORMATEX ) + pwfx->cbSize); + } + else + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + } + return ntStatus; +} // SetDataFormat + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CSaveData::SetMaxWriteSize +( + _In_ ULONG ulMaxWriteSize +) +{ + PAGED_CODE(); + + NTSTATUS ntStatus = STATUS_SUCCESS; + ULONG bufferSize = 0; + PBYTE buffer = NULL; + + // + // Compute new buffer size. + // + ntStatus = RtlULongMult(ulMaxWriteSize, DEFAULT_FRAME_COUNT, &bufferSize); + if (!NT_SUCCESS(ntStatus)) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + goto Done; + } + + // + // Alloc memory for buffer. + // + buffer = (PBYTE) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + bufferSize, + SAVEDATA_POOLTAG4 + ); + if (!buffer) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + goto Done; + } + + // + // Free old one. + // + if (m_pDataBuffer) + { + ExFreePoolWithTag(m_pDataBuffer, SAVEDATA_POOLTAG4); + m_pDataBuffer = NULL; + } + + // + // Init new buffer settings. + // + m_pDataBuffer = buffer; + m_ulBufferSize = bufferSize; + m_ulFrameSize = ulMaxWriteSize; + + ntStatus = STATUS_SUCCESS; + +Done: + return ntStatus; +} // SetDataFormat + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +void +CSaveData::ReadData +( + _Inout_updates_bytes_all_(ulByteCount) PBYTE pBuffer, + _In_ ULONG ulByteCount +) +{ + UNREFERENCED_PARAMETER(pBuffer); + UNREFERENCED_PARAMETER(ulByteCount); + + PAGED_CODE(); + + // Not implemented yet. +} // ReadData + +//============================================================================= +_Use_decl_annotations_ +void +CSaveData::SaveFrame +( + _In_ ULONG ulFrameNo, + _In_ ULONG ulDataSize +) +{ + PSAVEWORKER_PARAM pParam = NULL; + + pParam = GetNewWorkItem(); + if (pParam) + { + pParam->pSaveData = this; + pParam->ulFrameNo = ulFrameNo; + pParam->ulDataSize = ulDataSize; + pParam->pData = m_pDataBuffer + ulFrameNo * m_ulFrameSize; + KeResetEvent(&pParam->EventDone); + IoQueueWorkItem(pParam->WorkItem, SaveFrameWorkerCallback, + CriticalWorkQueue, (PVOID)pParam); + } +} // SaveFrame + +//============================================================================= +void +_Use_decl_annotations_ +PAGED_CODE_SEG +CSaveData::WaitAllWorkItems +( + void +) +{ + PAGED_CODE(); + + // Save the last partially-filled frame + if (m_ulBufferOffset > m_ulFrameIndex * m_ulFrameSize) + { + ULONG size; + + size = m_ulBufferOffset - m_ulFrameIndex * m_ulFrameSize; + SaveFrame(m_ulFrameIndex, size); + } + + for (int i = 0; i < MAX_WORKER_ITEM_COUNT; i++) + { + KeWaitForSingleObject + ( + &(m_pWorkItems[i].EventDone), + Executive, + KernelMode, + FALSE, + NULL + ); + } +} // WaitAllWorkItems + +//============================================================================= +_Use_decl_annotations_ +void +CSaveData::WriteData +( + _In_reads_bytes_(ulByteCount) PBYTE pBuffer, + _In_ ULONG ulByteCount +) +{ + ASSERT(pBuffer); + + BOOL fSaveFrame = FALSE; + ULONG ulSaveFrameIndex = 0; + KIRQL oldIrql; + + // If stream writing is disabled, then exit. + // + if (m_fWriteDisabled) + { + return; + } + + if( 0 == ulByteCount ) + { + return; + } + + // The logic below assumes that write size is <= than frame size. + if (ulByteCount > m_ulFrameSize) + { + ulByteCount = m_ulFrameSize; + } + + // Check to see if this frame is available. + KeAcquireSpinLock(&m_FrameInUseSpinLock, &oldIrql); + if (!m_fFrameUsed[m_ulFrameIndex]) + { + KeReleaseSpinLock(&m_FrameInUseSpinLock, oldIrql ); + + ULONG ulWriteBytes = ulByteCount; + + if( (m_ulBufferSize - m_ulBufferOffset) < ulWriteBytes ) + { + ulWriteBytes = m_ulBufferSize - m_ulBufferOffset; + } + + RtlCopyMemory(m_pDataBuffer + m_ulBufferOffset, pBuffer, ulWriteBytes); + m_ulBufferOffset += ulWriteBytes; + + // Check to see if we need to save this frame + if (m_ulBufferOffset >= ((m_ulFrameIndex + 1) * m_ulFrameSize)) + { + fSaveFrame = TRUE; + } + + // Loop the buffer, if we reached the end. + if (m_ulBufferOffset == m_ulBufferSize) + { + fSaveFrame = TRUE; + m_ulBufferOffset = 0; + } + + if (fSaveFrame) + { + InterlockedExchange( (LONG *)&(m_fFrameUsed[m_ulFrameIndex]), TRUE ); + ulSaveFrameIndex = m_ulFrameIndex; + m_ulFrameIndex = (m_ulFrameIndex + 1) % m_ulFrameCount; + } + + // Write the left over if the next frame is available. + if (ulWriteBytes != ulByteCount) + { + KeAcquireSpinLock(&m_FrameInUseSpinLock, &oldIrql ); + if (!m_fFrameUsed[m_ulFrameIndex]) + { + KeReleaseSpinLock(&m_FrameInUseSpinLock, oldIrql ); + RtlCopyMemory + ( + m_pDataBuffer + m_ulBufferOffset, + pBuffer + ulWriteBytes, + ulByteCount - ulWriteBytes + ); + + m_ulBufferOffset += ulByteCount - ulWriteBytes; + } + else + { + KeReleaseSpinLock(&m_FrameInUseSpinLock, oldIrql); + } + } + + if (fSaveFrame) + { + SaveFrame(ulSaveFrameIndex, m_ulFrameSize); + } + } + else + { + KeReleaseSpinLock(&m_FrameInUseSpinLock, oldIrql ); + } + +} // WriteData + + diff --git a/audio/Acx/Samples/Common/SaveData.h b/audio/Acx/Samples/Common/SaveData.h new file mode 100644 index 000000000..9138352f0 --- /dev/null +++ b/audio/Acx/Samples/Common/SaveData.h @@ -0,0 +1,259 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SaveData.h + +Abstract: + + Declaration of data saving class for ACX driver samples. This class supplies services +to save data to disk. + + +--*/ + +#pragma once + +//----------------------------------------------------------------------------- +// Forward declaration +//----------------------------------------------------------------------------- +class CSaveData; +typedef CSaveData *PCSaveData; + + +//----------------------------------------------------------------------------- +// Structs +//----------------------------------------------------------------------------- + +// Parameter to workitem. +#include +typedef struct _SAVEWORKER_PARAM { + PIO_WORKITEM WorkItem; + ULONG ulFrameNo; + ULONG ulDataSize; + PBYTE pData; + PCSaveData pSaveData; + KEVENT EventDone; +} SAVEWORKER_PARAM; +typedef SAVEWORKER_PARAM *PSAVEWORKER_PARAM; +#include + +// wave file header. +#include +typedef struct _OUTPUT_FILE_HEADER +{ + DWORD dwRiff; + DWORD dwFileSize; + DWORD dwWave; + DWORD dwFormat; + DWORD dwFormatLength; +} OUTPUT_FILE_HEADER; +typedef OUTPUT_FILE_HEADER *POUTPUT_FILE_HEADER; + +typedef struct _OUTPUT_DATA_HEADER +{ + DWORD dwData; + DWORD dwDataLength; +} OUTPUT_DATA_HEADER; +typedef OUTPUT_DATA_HEADER *POUTPUT_DATA_HEADER; + +#include + +//----------------------------------------------------------------------------- +// Classes +//----------------------------------------------------------------------------- + +/////////////////////////////////////////////////////////////////////////////// +// CSaveData +// Saves the wave data to disk. +// +__drv_maxIRQL(PASSIVE_LEVEL) +PAGED_CODE_SEG +IO_WORKITEM_ROUTINE SaveFrameWorkerCallback; + +class CSaveData +{ +protected: + UNICODE_STRING m_FileName; // DataFile name. + HANDLE m_FileHandle; // DataFile handle. + PBYTE m_pDataBuffer; // Data buffer. + ULONG m_ulBufferSize; // Total buffer size. + + ULONG m_ulFrameIndex; // Current Frame. + ULONG m_ulFrameCount; // Frame count. + ULONG m_ulFrameSize; + ULONG m_ulBufferOffset; // index in buffer. + PBOOL m_fFrameUsed; // Frame usage table. + KSPIN_LOCK m_FrameInUseSpinLock; // Spinlock for synch. + KMUTEX m_FileSync; // Synchronizes file access + + OBJECT_ATTRIBUTES m_objectAttributes; // Used for opening file. + + OUTPUT_FILE_HEADER m_FileHeader; + PWAVEFORMATEX m_waveFormat; + OUTPUT_DATA_HEADER m_DataHeader; + PLARGE_INTEGER m_pFilePtr; + + static PDEVICE_OBJECT m_pDeviceObject; + static ULONG m_ulStreamId; + static ULONG m_ulOffloadStreamId; + static PSAVEWORKER_PARAM m_pWorkItems; + + BOOL m_fWriteDisabled; + + BOOL m_bInitialized; + +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CSaveData(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CSaveData(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void + Cleanup( + void + ); + + static + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + InitializeWorkItems( + _In_ PDEVICE_OBJECT DeviceObject + ); + + static + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void + DestroyWorkItems( + void + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void + Disable( + _In_ BOOL fDisable + ); + + static + __drv_maxIRQL(DISPATCH_LEVEL) + PSAVEWORKER_PARAM + GetNewWorkItem( + void + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Initialize( + _In_ BOOL _bOffloaded + ); + + static + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetDeviceObject( + _In_ PDEVICE_OBJECT DeviceObject + ); + + static + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + PDEVICE_OBJECT + GetDeviceObject( + void + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void + ReadData( + _Inout_updates_bytes_all_(ulByteCount) PBYTE pBuffer, + _In_ ULONG ulByteCount + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetDataFormat( + _In_ PKSDATAFORMAT pDataFormat + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetMaxWriteSize( + _In_ ULONG ulMaxWriteSize + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void + WaitAllWorkItems( + void + ); + + __drv_maxIRQL(DISPATCH_LEVEL) + void + WriteData( + _In_reads_bytes_(ulByteCount) PBYTE pBuffer, + _In_ ULONG ulByteCount + ); + +private: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + FileClose( + void + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + FileOpen( + _In_ BOOL fOverWrite + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + FileWrite( + _In_reads_bytes_(ulDataSize) PBYTE pData, + _In_ ULONG ulDataSize + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + FileWriteHeader( + void + ); + + __drv_maxIRQL(DISPATCH_LEVEL) + void + SaveFrame( + _In_ ULONG ulFrameNo, + _In_ ULONG ulDataSize + ); + + friend + IO_WORKITEM_ROUTINE SaveFrameWorkerCallback; +}; +typedef CSaveData *PCSaveData; + diff --git a/audio/Acx/Samples/Common/SimPeakMeter.cpp b/audio/Acx/Samples/Common/SimPeakMeter.cpp new file mode 100644 index 000000000..0dfbd4e5c --- /dev/null +++ b/audio/Acx/Samples/Common/SimPeakMeter.cpp @@ -0,0 +1,106 @@ +/*++ + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SimPeakMeter.cpp + +Abstract: + + Virtual Peakmeter - aggregates all streams + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "SimPeakMeter.h" + +#ifndef __INTELLISENSE__ +#include "SimPeakMeter.tmh" +#endif + +_Use_decl_annotations_ +PAGED_CODE_SEG +CSimPeakMeter::CSimPeakMeter() +{ + PAGED_CODE(); + m_NumStreams = 0; + m_PeakMeterIndex = 0; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CSimPeakMeter::~CSimPeakMeter() +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +LONG CSimPeakMeter::GetValue(ULONG Channel) +{ + PAGED_CODE(); + + // Ignore channel + UNREFERENCED_PARAMETER(Channel); + +#define PEAKMETER_VALUE_FULL (PEAKMETER_MAXIMUM / PEAKMETER_STEPPING_DELTA * PEAKMETER_STEPPING_DELTA) +#define PEAKMETER_VALUE_HALF (PEAKMETER_MAXIMUM / 2 / PEAKMETER_STEPPING_DELTA * PEAKMETER_STEPPING_DELTA) +#define PEAKMETER_VALUE_QUARTER (PEAKMETER_MAXIMUM / 4 / PEAKMETER_STEPPING_DELTA * PEAKMETER_STEPPING_DELTA) +#define PEAKMETER_VALUE_ONE_EIGTH (PEAKMETER_MAXIMUM / 8 / PEAKMETER_STEPPING_DELTA * PEAKMETER_STEPPING_DELTA) + + LONG PeakMeterValues[] = { + PEAKMETER_VALUE_ONE_EIGTH, + PEAKMETER_VALUE_QUARTER, + PEAKMETER_VALUE_HALF, + PEAKMETER_VALUE_FULL, + PEAKMETER_VALUE_HALF, + PEAKMETER_VALUE_QUARTER + }; + + if (m_NumStreams) + { + LONG pmi = InterlockedIncrement(&m_PeakMeterIndex); + if (pmi == ARRAYSIZE(PeakMeterValues)) + { + pmi = 0; + InterlockedExchange(&m_PeakMeterIndex, 0); + } + + return PeakMeterValues[pmi]; + } + + // + // No active streams. Peak meter = 0 + // + return 0; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CSimPeakMeter::StartStream() +{ + PAGED_CODE(); + InterlockedIncrement(&m_NumStreams); + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CSimPeakMeter::StopStream() +{ + PAGED_CODE(); + + ASSERT(m_NumStreams); + InterlockedDecrement(&m_NumStreams); + + return STATUS_SUCCESS; +} diff --git a/audio/Acx/Samples/Common/SimPeakMeter.h b/audio/Acx/Samples/Common/SimPeakMeter.h new file mode 100644 index 000000000..7203f299c --- /dev/null +++ b/audio/Acx/Samples/Common/SimPeakMeter.h @@ -0,0 +1,51 @@ +/*++ + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SimPeakMeter.h + +Abstract: + + Virtual Peakmeter - aggregates all streams + +Environment: + + Kernel mode + +--*/ + +#pragma once + +class CSimPeakMeter +{ +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CSimPeakMeter(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CSimPeakMeter(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + LONG GetValue(_In_ ULONG Channel); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS StartStream(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS StopStream(); + +private: + LONG m_NumStreams; + LONG m_PeakMeterIndex; +}; + diff --git a/audio/Acx/Samples/Common/StreamEngine.cpp b/audio/Acx/Samples/Common/StreamEngine.cpp new file mode 100644 index 000000000..be90bac6b --- /dev/null +++ b/audio/Acx/Samples/Common/StreamEngine.cpp @@ -0,0 +1,1345 @@ +/*++ + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + StreamEngine.cpp + +Abstract: + + Virtual Streaming Engine - this module controls streaming logic for + the device. + +Environment: + + Kernel mode + +--*/ + +#include "private.h" +#include "public.h" +#include +#include +#include +#include +#include "streamengine.h" + +#ifndef __INTELLISENSE__ +#include "streamengine.tmh" +#endif + +_Use_decl_annotations_ +PAGED_CODE_SEG +CStreamEngine::CStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ BOOL Offload, + _In_opt_ CSimPeakMeter *CircuitPeakmeter +) + : m_PacketsCount(0), + m_PacketSize(0), + m_FirstPacketOffset(0), + m_NotificationTimer(NULL), + m_CurrentState(AcxStreamStateStop), + m_CurrentPacket(0), + m_Position(0), + m_Stream(Stream), + m_StreamFormat(StreamFormat), + m_StartTime(0), + m_StartPosition(0), + m_GlitchAdjust(0), + m_ToneFrequency(DEFAULT_FREQUENCY), + m_Offload(Offload), + m_pCircuitPeakmeter(CircuitPeakmeter) +{ + PAGED_CODE(); + + KeQueryPerformanceCounter(&m_PerformanceCounterFrequency); + RtlZeroMemory(m_Packets, sizeof(m_Packets)); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CStreamEngine::~CStreamEngine() +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::AllocateRtPackets( + _In_ ULONG PacketCount, + _In_ ULONG PacketSize, + _Out_ PACX_RTPACKET* Packets +) +{ + NTSTATUS status = STATUS_SUCCESS; + PACX_RTPACKET packets = NULL; + PVOID packetBuffer = NULL; + ULONG i; + ULONG packetAllocSizeInPages = 0; + ULONG packetAllocSizeInBytes = 0; + ULONG firstPacketOffset = 0; + size_t packetsSize = 0; + + PAGED_CODE(); + + if (PacketCount > MAX_PACKET_COUNT) + { + ASSERT(FALSE); + status = STATUS_INVALID_PARAMETER; + goto exit; + } + + status = RtlSizeTMult(PacketCount, sizeof(ACX_RTPACKET), &packetsSize); + if (!NT_SUCCESS(status)) + { + ASSERT(FALSE); + goto exit; + } + + packets = (PACX_RTPACKET)ExAllocatePool2(POOL_FLAG_NON_PAGED, packetsSize, DeviceDriverTag); + if (!packets) + { + status = STATUS_NO_MEMORY; + ASSERT(FALSE); + goto exit; + } + + // + // We need to allocate page-aligned buffers, to ensure no kernel memory leaks + // to user space. Round up the packet size to page aligned, then calculate + // the first packet's buffer offset so packet 0 ends on a page boundary and + // packet 1 begins on a page boundary. + // + status = RtlULongAdd(PacketSize, PAGE_SIZE - 1, &packetAllocSizeInPages); + if (!NT_SUCCESS(status)) + { + ASSERT(FALSE); + goto exit; + } + packetAllocSizeInPages = packetAllocSizeInPages / PAGE_SIZE; + packetAllocSizeInBytes = PAGE_SIZE * packetAllocSizeInPages; + firstPacketOffset = packetAllocSizeInBytes - PacketSize; + + for (i = 0; i < PacketCount; ++i) + { + PMDL pMdl = NULL; + + ACX_RTPACKET_INIT(&packets[i]); + + packetBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, packetAllocSizeInBytes, DeviceDriverTag); + if (packetBuffer == NULL) + { + status = STATUS_NO_MEMORY; + goto exit; + } + + pMdl = IoAllocateMdl(packetBuffer, packetAllocSizeInBytes, FALSE, TRUE, NULL); + if (pMdl == NULL) + { + status = STATUS_NO_MEMORY; + goto exit; + } + + MmBuildMdlForNonPagedPool(pMdl); + + WDF_MEMORY_DESCRIPTOR_INIT_MDL(&((packets)[i].RtPacketBuffer), pMdl, packetAllocSizeInBytes); + + packets[i].RtPacketSize = PacketSize; + if (i == 0) + { + packets[i].RtPacketOffset = firstPacketOffset; + } + else + { + packets[i].RtPacketOffset = 0; + } + m_Packets[i] = packetBuffer; + + packetBuffer = NULL; + } + + *Packets = packets; + packets = NULL; + m_PacketsCount = PacketCount; + m_PacketSize = PacketSize; + m_FirstPacketOffset = firstPacketOffset; + +exit: + if (packetBuffer) + { + ExFreePoolWithTag(packetBuffer, DeviceDriverTag); + } + if (packets) + { + FreeRtPackets(packets, PacketCount); + } + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +VOID +CStreamEngine::FreeRtPackets( + _Frees_ptr_ PACX_RTPACKET Packets, + _In_ ULONG PacketCount +) +{ + ULONG i; + PVOID buffer; + + PAGED_CODE(); + + for (i = 0; i < PacketCount; ++i) + { + if (Packets[i].RtPacketBuffer.u.MdlType.Mdl) + { + buffer = MmGetMdlVirtualAddress(Packets[i].RtPacketBuffer.u.MdlType.Mdl); + IoFreeMdl(Packets[i].RtPacketBuffer.u.MdlType.Mdl); + ExFreePool(buffer); + } + } + + ExFreePool(Packets); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::PrepareHardware() +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + WDF_TIMER_CONFIG timerConfig; + WDF_OBJECT_ATTRIBUTES timerAttributes; + PSTREAM_TIMER_CONTEXT timerCtx; + + PAGED_CODE(); + + // + // If already in this state, do nothing. + // + if (m_CurrentState == AcxStreamStatePause) + { + // Nothing to do. + status = STATUS_SUCCESS; + goto exit; + } + + if (m_CurrentState != AcxStreamStateStop) + { + // Error out. + status = STATUS_INVALID_STATE_TRANSITION; + goto exit; + } + + // + // Stop to Pause. + // + WDF_TIMER_CONFIG_INIT(&timerConfig, CStreamEngine::s_EvtStreamPassCallback); + timerConfig.AutomaticSerialization = TRUE; + timerConfig.UseHighResolutionTimer = WdfTrue; + timerConfig.Period = 0; + + WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes); + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&timerAttributes, STREAM_TIMER_CONTEXT); + timerAttributes.ParentObject = m_Stream; + + status = WdfTimerCreate(&timerConfig, &timerAttributes, &m_NotificationTimer); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + timerCtx = GetStreamTimerContext(m_NotificationTimer); + timerCtx->StreamEngine = this; + + m_CurrentState = AcxStreamStatePause; + status = STATUS_SUCCESS; + +exit: + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::ReleaseHardware() +{ + PAGED_CODE(); + + // + // If already in this state, do nothing. + // + if (m_CurrentState == AcxStreamStateStop) + { + // Nothing to do. + goto exit; + } + + // + // Just assert we are in the correct state. + // On the way down we always want to succeed. + // + ASSERT(m_CurrentState == AcxStreamStatePause); + + // + // Pause to Stop. + // + if (m_NotificationTimer) + { + WdfTimerStop(m_NotificationTimer, TRUE); + WdfObjectDelete(m_NotificationTimer); + m_NotificationTimer = NULL; + } + + KeFlushQueuedDpcs(); + + m_Position = 0; + m_GlitchAdjust = 0; + m_CurrentPacket = 0; + + m_CurrentState = AcxStreamStateStop; + +exit: + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::Pause() +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + + PAGED_CODE(); + + if (m_CurrentState == AcxStreamStatePause) + { + // Nothing to do. + status = STATUS_SUCCESS; + goto exit; + } + + if (m_CurrentState != AcxStreamStateRun) + { + // Error out. + status = STATUS_INVALID_STATE_TRANSITION; + goto exit; + } + + m_PeakMeter.StopStream(); + if (m_pCircuitPeakmeter) + { + m_pCircuitPeakmeter->StopStream(); + } + + // + // Run to Pause. + // + WdfTimerStop(m_NotificationTimer, TRUE); + + // Save the position we paused at. + UpdatePosition(); + + m_CurrentState = AcxStreamStatePause; + status = STATUS_SUCCESS; + +exit: + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::Run() +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + + PAGED_CODE(); + + if (m_CurrentState == AcxStreamStateRun) + { + // Nothing to do. + status = STATUS_SUCCESS; + goto exit; + } + + if (m_CurrentState != AcxStreamStatePause) + { + status = STATUS_INVALID_STATE_TRANSITION; + goto exit; + } + + m_PeakMeter.StartStream(); + if (m_pCircuitPeakmeter) + { + m_pCircuitPeakmeter->StartStream(); + } + + // + // Pause to Run. + // + // Save the time and position - if we ran and paused previously, the StartTime and StartPosition will allow + // us to continue scheduling packet completions correctly, while still reporting absolute position from the + // start of the stream. + // + m_StartTime = KSCONVERT_PERFORMANCE_TIME(m_PerformanceCounterFrequency.QuadPart, KeQueryPerformanceCounter(NULL)); + m_StartPosition = m_Position; + + // Reset time we've lost to glitches + m_GlitchAdjust = 0; + + ScheduleNextPass(); + + m_CurrentState = AcxStreamStateRun; + status = STATUS_SUCCESS; + +exit: + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::GetPresentationPosition( + _Out_ PULONGLONG PositionInBlocks, + _Out_ PULONGLONG QPCPosition +) +{ + ULONG blockAlign; + LARGE_INTEGER qpc; + + PAGED_CODE(); + + blockAlign = AcxDataFormatGetBlockAlign(m_StreamFormat); + + // Update the position based on the current time + UpdatePosition(); + qpc = KeQueryPerformanceCounter(NULL); + + *PositionInBlocks = m_Position / blockAlign; + *QPCPosition = (ULONGLONG)qpc.QuadPart; + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::GetLinearBufferPosition( + _Out_ PULONGLONG Position +) +{ + UNREFERENCED_PARAMETER(Position); + PAGED_CODE(); + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::SetCurrentWritePosition( + _In_ ULONG Position +) +{ + UNREFERENCED_PARAMETER(Position); + PAGED_CODE(); + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::SetLastBufferPosition( + _In_ ULONG Position +) +{ + UNREFERENCED_PARAMETER(Position); + PAGED_CODE(); + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::AssignDrmContentId( + ULONG DrmContentId, + PACXDRMRIGHTS DrmRights +) +{ + PAGED_CODE(); + + UNREFERENCED_PARAMETER(DrmContentId); + UNREFERENCED_PARAMETER(DrmRights); + + // + // At this point the driver should enforce the new DrmRights. + // + // HDMI render: if DigitalOutputDisable or CopyProtect is true, enable HDCP. + // + // From MSDN: + // + // This sample doesn't forward protected content, but if your driver uses + // lower layer drivers or a different stack to properly work, please see the + // following info from MSDN: + // + // "Before allowing protected content to flow through a data path, the system + // verifies that the data path is secure. To do so, the system authenticates + // each module in the data path beginning at the upstream end of the data path + // and moving downstream. As each module is authenticated, that module gives + // the system information about the next module in the data path so that it + // can also be authenticated. To be successfully authenticated, a module's + // binary file must be signed as DRM-compliant. + // + // Two adjacent modules in the data path can communicate with each other in + // one of several ways. If the upstream module calls the downstream module + // through IoCallDriver, the downstream module is part of a WDM driver. In + // this case, the upstream module calls the AcxDrmForwardContentToDeviceObject + // function to provide the system with the device object representing the + // downstream module. (If the two modules communicate through the downstream + // module's content handlers, the upstream module calls AcxDrmAddContentHandlers + // instead.) + // + // For more information, see MSDN's DRM Functions and Interfaces. + // + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::GetHWLatency( + _Out_ ULONG* FifoSize, + _Out_ ULONG* Delay +) +{ + PAGED_CODE(); + + *FifoSize = 128; + *Delay = 0; + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CSimPeakMeter * +CStreamEngine::GetPeakMeter() +{ + PAGED_CODE(); + + return &m_PeakMeter; +} + +_Use_decl_annotations_ +VOID +CStreamEngine::s_EvtStreamPassCallback( + _In_ WDFTIMER Timer +) +{ + CStreamEngine* This; + PSTREAM_TIMER_CONTEXT timerCtx; + + // Get our stream engine pointer from the timer context + timerCtx = GetStreamTimerContext(Timer); + This = timerCtx->StreamEngine; + + // Call the StreamPassCallback for the engine + This->StreamPassCallback(); +} + +// This is run every time the stream timer fires +_Use_decl_annotations_ +VOID +CStreamEngine::StreamPassCallback() +{ + ULONGLONG completedPacket; + ULONGLONG qpcCompleted; + + // Process the packet (e.g. save render to file/generate capture data) + ProcessPacket(); + + // We've completed a packet! Increment our currently active packet + completedPacket = (ULONG)InterlockedIncrement((LONG*)&m_CurrentPacket) - 1; + // Save the time at which we moved to the next packet + qpcCompleted = (ULONGLONG)KeQueryPerformanceCounter(NULL).QuadPart; + + InterlockedExchange64(&m_LastPacketStart.QuadPart, m_CurrentPacketStart.QuadPart); + InterlockedExchange64(&m_CurrentPacketStart.QuadPart, qpcCompleted); + + // Tell ACX we've completed the packet. + (void)AcxRtStreamNotifyPacketComplete(m_Stream, completedPacket, qpcCompleted); + + // Schedule when our new current packet will finish + ScheduleNextPass(); +} + +_Use_decl_annotations_ +VOID +CStreamEngine::ScheduleNextPass() +{ + LONGLONG delay = 0; + ULONG bytesPerSecond; + ULONGLONG nextPacket = 0; + ULONGLONG nextPacketStartPosition = 0; + ULONGLONG nextPacketPositionFromLastPause = 0; + ULONGLONG nextPacketTimeFromLastPauseHns = 0; + ULONGLONG nextPacketTime = 0; + ULONGLONG currentTime; + BOOLEAN inTimerQueue = FALSE; + + // Get the number of bytes per second from our stored stream format + bytesPerSecond = GetBytesPerSecond(); + + // Calculate the absolute position of the beginning of the next packet from the beginning of the stream + nextPacket = m_CurrentPacket + 1; + nextPacketStartPosition = nextPacket * m_PacketSize; + + // Adjust next packet position to account for the last time we resumed from Pause + nextPacketPositionFromLastPause = nextPacketStartPosition - m_StartPosition; + + // Convert from bytes to HNS (to prevent truncation, multiply first then divide) + nextPacketTimeFromLastPauseHns = nextPacketPositionFromLastPause * HNS_PER_SEC / bytesPerSecond; + + // Next packet time is Time @ resume from Pause, offset for lost time due to glitch, with next packet time added + nextPacketTime = m_StartTime + m_GlitchAdjust + nextPacketTimeFromLastPauseHns; + + currentTime = KSCONVERT_PERFORMANCE_TIME(m_PerformanceCounterFrequency.QuadPart, KeQueryPerformanceCounter(NULL)); + + // Determine how long we want to wait, in HNS. Negative since it's a relative wait + delay = -(LONGLONG)(nextPacketTime - currentTime); + + // If the delay isn't negative, this means we lost some time (e.g. broken into kernel debugger). Update + // our glitch adjust to account for that lost time, and attempt to schedule again + if (delay >= 0) + { + // Glitch!!! + // Update the glitch adjustment and set the new delay. + m_GlitchAdjust += delay; + + StreamPassCallback(); + + return; + } + + // Start the timer for our next pass! Note the timer isn't periodic. + inTimerQueue = WdfTimerStart(m_NotificationTimer, delay); + + // We shouldn't be scheduling our next pass if the timer was previously still pending + ASSERT(inTimerQueue == FALSE); +} + +_Use_decl_annotations_ +VOID +CStreamEngine::UpdatePosition() +{ + ULONGLONG currentTime; + ULONG bytesPerSecond; + + if (m_CurrentState != AcxStreamStateRun) + { + return; + } + bytesPerSecond = GetBytesPerSecond(); + currentTime = KSCONVERT_PERFORMANCE_TIME(m_PerformanceCounterFrequency.QuadPart, KeQueryPerformanceCounter(NULL)); + + // Update position + m_Position = m_StartPosition - m_GlitchAdjust + (currentTime - m_StartTime) * bytesPerSecond / HNS_PER_SEC; +} + +_Use_decl_annotations_ +ULONG +CStreamEngine::GetBytesPerSecond() +{ + ULONG bytesPerSecond; + + bytesPerSecond = AcxDataFormatGetAverageBytesPerSec(m_StreamFormat); + + return bytesPerSecond; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CStreamEngine::GetCurrentPacket( + _Out_ PULONG CurrentPacket +) +{ + ULONG currentPacket; + PAGED_CODE(); + + currentPacket = (ULONG)InterlockedCompareExchange((LONG*)&m_CurrentPacket, -1, -1); + + *CurrentPacket = currentPacket; + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CRenderStreamEngine::CRenderStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ BOOL Offload, + _In_ CSimPeakMeter * CircuitPeakmeter + +) + : CStreamEngine(Stream, StreamFormat, Offload, CircuitPeakmeter) +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CRenderStreamEngine::~CRenderStreamEngine() +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CRenderStreamEngine::PrepareHardware() +{ + NTSTATUS status = STATUS_SUCCESS; + + PAGED_CODE(); + + status = CStreamEngine::PrepareHardware(); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + status = m_SaveData.SetDataFormat((PKSDATAFORMAT)AcxDataFormatGetKsDataFormat(m_StreamFormat)); + if (!NT_SUCCESS(status)) + { + status = STATUS_SUCCESS; + goto exit; + } + + status = m_SaveData.Initialize(m_Offload); + if (!NT_SUCCESS(status)) + { + status = STATUS_SUCCESS; + goto exit; + } + + status = m_SaveData.SetMaxWriteSize(m_PacketSize * m_PacketsCount * 16); + if (!NT_SUCCESS(status)) + { + status = STATUS_SUCCESS; + goto exit; + } + +exit: + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CRenderStreamEngine::ReleaseHardware() +{ + PAGED_CODE(); + + m_SaveData.WaitAllWorkItems(); + m_SaveData.Cleanup(); + + return CStreamEngine::ReleaseHardware(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CRenderStreamEngine::AssignDrmContentId( + ULONG DrmContentId, + PACXDRMRIGHTS DrmRights + ) +{ + PAGED_CODE(); + + UNREFERENCED_PARAMETER(DrmContentId); + + // + // At this point the driver should enforce the new DrmRights. + // The sample driver handles DrmRights per stream basis, and + // stops writing the stream to disk, if CopyProtect = TRUE. + // + // HDMI render: if DigitalOutputDisable or CopyProtect is true, enable HDCP. + // Loopback: if CopyProtect is true, disable loopback stream. + // + + // + // Sample writes each stream seperately to disk. If the rights for this + // stream indicates that the stream is CopyProtected, stop writing to disk. + // + m_SaveData.Disable(DrmRights->CopyProtect); + + // + // From MSDN: + // + // This sample doesn't forward protected content, but if your driver uses + // lower layer drivers or a different stack to properly work, please see the + // following info from MSDN: + // + // "Before allowing protected content to flow through a data path, the system + // verifies that the data path is secure. To do so, the system authenticates + // each module in the data path beginning at the upstream end of the data path + // and moving downstream. As each module is authenticated, that module gives + // the system information about the next module in the data path so that it + // can also be authenticated. To be successfully authenticated, a module's + // binary file must be signed as DRM-compliant. + // + // Two adjacent modules in the data path can communicate with each other in + // one of several ways. If the upstream module calls the downstream module + // through IoCallDriver, the downstream module is part of a WDM driver. In + // this case, the upstream module calls the AcxDrmForwardContentToDeviceObject + // function to provide the system with the device object representing the + // downstream module. (If the two modules communicate through the downstream + // module's content handlers, the upstream module calls AcxDrmAddContentHandlers + // instead.) + // + // For more information, see MSDN's DRM Functions and Interfaces. + // + + return STATUS_SUCCESS; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CRenderStreamEngine::SetRenderPacket( + _In_ ULONG Packet, + _In_ ULONG Flags, + _In_ ULONG EosPacketLength +) +{ + NTSTATUS status = STATUS_SUCCESS; + ULONG currentPacket; + + UNREFERENCED_PARAMETER(Flags); + UNREFERENCED_PARAMETER(EosPacketLength); + + PAGED_CODE(); + + currentPacket = (ULONG)InterlockedCompareExchange((LONG*)&m_CurrentPacket, -1, -1); + + if (Packet <= currentPacket) + { + //ASSERT(FALSE); + status = STATUS_DATA_LATE_ERROR; + } + else if (Packet > currentPacket + 1) + { + //ASSERT(FALSE); + status = STATUS_DATA_OVERRUN; + } + + return status; +} + +_Use_decl_annotations_ +VOID +CRenderStreamEngine::ProcessPacket() +{ + ULONG currentPacket; + ULONG packetIndex; + PBYTE packetBuffer; + + currentPacket = (ULONG)InterlockedCompareExchange((LONG*)&m_CurrentPacket, -1, -1); + + packetIndex = currentPacket % m_PacketsCount; + packetBuffer = (PBYTE)m_Packets[packetIndex]; + // Packet 0 starts at an offset if the size isn't a multiple of page_size + if (packetIndex == 0) + { + packetBuffer += m_FirstPacketOffset; + } + + m_SaveData.WriteData(packetBuffer, m_PacketSize); +} + + +_Use_decl_annotations_ +PAGED_CODE_SEG +CCaptureStreamEngine::CCaptureStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat +) + : CStreamEngine(Stream, StreamFormat, FALSE, NULL), + m_EnableWaveCapture(0) +{ + PAGED_CODE(); + + m_CurrentPacketStart.QuadPart = 0; + m_LastPacketStart.QuadPart = 0; + + RtlInitUnicodeString(&m_HostCaptureFileName, NULL); + RtlInitUnicodeString(&m_LoopbackCaptureFileName, NULL); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CCaptureStreamEngine::~CCaptureStreamEngine() +{ + PAGED_CODE(); + + RtlFreeUnicodeString(&m_HostCaptureFileName); + RtlFreeUnicodeString(&m_LoopbackCaptureFileName); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CCaptureStreamEngine::PrepareHardware() +{ + NTSTATUS status = STATUS_SUCCESS; + PWAVEFORMATEXTENSIBLE pwfext = NULL; + + PAGED_CODE(); + + status = CStreamEngine::PrepareHardware(); + if (!NT_SUCCESS(status)) + { + goto exit; + } + + (void)ReadRegistrySettings(); + + pwfext = (PWAVEFORMATEXTENSIBLE)AcxDataFormatGetWaveFormatExtensible(m_StreamFormat); + if (pwfext == NULL) + { + // Cannot initialize reader or generator with a format that's not understood + status = STATUS_NO_MATCH; + ASSERT(FALSE); + goto exit; + } + + if (m_EnableWaveCapture) + { + status = m_WaveReader.Init(pwfext, &m_HostCaptureFileName); + if (!NT_SUCCESS(status)) + { + m_EnableWaveCapture = FALSE; + } + } + + if (!m_EnableWaveCapture) + { + status = m_ToneGenerator.Init(m_ToneFrequency, pwfext); + } + +exit: + return status; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CCaptureStreamEngine::ReleaseHardware() +{ + PAGED_CODE(); + + if (m_EnableWaveCapture) + { + m_WaveReader.WaitAllWorkItems(); + } + + return CStreamEngine::ReleaseHardware(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CCaptureStreamEngine::GetCapturePacket( + _Out_ ULONG* LastCapturePacket, + _Out_ ULONGLONG* QPCPacketStart, + _Out_ BOOLEAN* MoreData +) +{ + NTSTATUS status = STATUS_SUCCESS; + ULONG currentPacket; + LONGLONG qpcPacketStart; + + PAGED_CODE(); + + currentPacket = (ULONG)InterlockedCompareExchange((LONG*)&m_CurrentPacket, -1, -1); + qpcPacketStart = InterlockedCompareExchange64(&m_LastPacketStart.QuadPart, -1, -1); + + *LastCapturePacket = currentPacket - 1; + *QPCPacketStart = (ULONGLONG)qpcPacketStart; + *MoreData = FALSE; + + return status; +} + +_Use_decl_annotations_ +VOID +CCaptureStreamEngine::ProcessPacket() +{ + ULONG currentPacket; + ULONG packetIndex; + PBYTE packetBuffer; + + currentPacket = (ULONG)InterlockedCompareExchange((LONG*)&m_CurrentPacket, -1, -1); + + packetIndex = currentPacket % m_PacketsCount; + packetBuffer = (PBYTE)m_Packets[packetIndex]; + + // Packet 0 starts at an offset if the size isn't a multiple of page_size + if (packetIndex == 0) + { + packetBuffer += m_FirstPacketOffset; + } + + if (m_EnableWaveCapture) + { + m_WaveReader.ReadWaveData(packetBuffer, m_PacketSize); + } + else + { + m_ToneGenerator.GenerateSine(packetBuffer, m_PacketSize); + } +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CCaptureStreamEngine::ReadRegistrySettings() +{ + NTSTATUS status; + PDRIVER_OBJECT DriverObject; + HANDLE DriverKey; + + RTL_QUERY_REGISTRY_TABLE paramTable[] = { + // QueryRoutine Flags Name EntryContext DefaultType DefaultData DefaultLength + { NULL, RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK, L"EnableWaveCapture", &m_EnableWaveCapture, (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_DWORD, &m_EnableWaveCapture, sizeof(DWORD) }, + { NULL, RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK, L"HostCaptureFileName", &m_HostCaptureFileName, (REG_SZ << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_SZ, &m_HostCaptureFileName, sizeof(UNICODE_STRING) }, + { NULL, RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK, L"LoopbackCaptureFileName", &m_LoopbackCaptureFileName, (REG_SZ << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_SZ, &m_LoopbackCaptureFileName, sizeof(UNICODE_STRING) }, + { NULL, 0, NULL, NULL, 0, NULL, 0 } + }; + + PAGED_CODE(); + + DriverObject = WdfDriverWdmGetDriverObject(WdfGetDriver()); + DriverKey = NULL; + status = IoOpenDriverRegistryKey(DriverObject, + DriverRegKeyParameters, + KEY_READ, + 0, + &DriverKey); + + if (!NT_SUCCESS(status)) + { + ASSERT(FALSE); + goto exit; + } + + status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE, + (PCWSTR) DriverKey, + ¶mTable[0], + NULL, + NULL); + + if (DriverKey) + { + ZwClose(DriverKey); + } + +exit: + if (!NT_SUCCESS(status)) + { + m_EnableWaveCapture = FALSE; + } + + return status; +} +_Use_decl_annotations_ +PAGED_CODE_SEG +CBufferedCaptureStreamEngine::CBufferedCaptureStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ CKeywordDetector* KeywordDetector + +) + : CCaptureStreamEngine(Stream, StreamFormat), + m_KeywordDetector(KeywordDetector) +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +CBufferedCaptureStreamEngine::~CBufferedCaptureStreamEngine() +{ + PAGED_CODE(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CBufferedCaptureStreamEngine::Pause() +{ + PAGED_CODE(); + + m_KeywordDetector->Stop(); + return CCaptureStreamEngine::Pause(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CBufferedCaptureStreamEngine::Run() +{ + PAGED_CODE(); + + m_KeywordDetector->Run(); + return CCaptureStreamEngine::Run(); +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS +CBufferedCaptureStreamEngine::GetCapturePacket( + _Out_ ULONG* LastCapturePacket, + _Out_ ULONGLONG* QPCPacketStart, + _Out_ BOOLEAN* MoreData +) +{ + PAGED_CODE(); + + // retrieve the packet from the fifo queue + return m_KeywordDetector->GetReadPacket(m_PacketsCount, m_PacketSize, m_Packets, LastCapturePacket, QPCPacketStart, MoreData); +} + +_Use_decl_annotations_ +VOID +CBufferedCaptureStreamEngine::ProcessPacket() +{ + LARGE_INTEGER qpc; + LARGE_INTEGER qpcFrequency; + + qpc = KeQueryPerformanceCounter(&qpcFrequency); + + // Add the next packet to the fifo queue + m_KeywordDetector->DpcRoutine(qpc.QuadPart, qpcFrequency.QuadPart); +} + +//Streamengine callbacks + +VOID +EvtStreamDestroy( + _In_ WDFOBJECT Object +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + ctx = GetStreamEngineContext((ACXSTREAM)Object); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + ctx->StreamEngine = NULL; + delete streamEngine; +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetHwLatency( + _In_ ACXSTREAM Stream, + _Out_ ULONG* FifoSize, + _Out_ ULONG* Delay +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->GetHWLatency(FifoSize, Delay); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamAllocateRtPackets( + _In_ ACXSTREAM Stream, + _In_ ULONG PacketCount, + _In_ ULONG PacketSize, + _Out_ PACX_RTPACKET* Packets +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->AllocateRtPackets(PacketCount, PacketSize, Packets); +} + +PAGED_CODE_SEG +VOID +EvtStreamFreeRtPackets( + _In_ ACXSTREAM Stream, + _In_ PACX_RTPACKET Packets, + _In_ ULONG PacketCount +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->FreeRtPackets(Packets, PacketCount); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamPrepareHardware( + _In_ ACXSTREAM Stream +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->PrepareHardware(); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamReleaseHardware( + _In_ ACXSTREAM Stream +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->ReleaseHardware(); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamRun( + _In_ ACXSTREAM Stream +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->Run(); +} + + +PAGED_CODE_SEG +NTSTATUS +EvtStreamPause( + _In_ ACXSTREAM Stream +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->Pause(); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamAssignDrmContentId( + _In_ ACXSTREAM Stream, + _In_ ULONG DrmContentId, + _In_ PACXDRMRIGHTS DrmRights +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine * streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = (CStreamEngine*)ctx->StreamEngine; + + return streamEngine->AssignDrmContentId(DrmContentId, DrmRights); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetCurrentPacket( + _In_ ACXSTREAM Stream, + _Out_ PULONG CurrentPacket +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = static_cast(ctx->StreamEngine); + + return streamEngine->GetCurrentPacket(CurrentPacket); +} + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetPresentationPosition( + _In_ ACXSTREAM Stream, + _Out_ PULONGLONG PositionInBlocks, + _Out_ PULONGLONG QPCPosition +) +{ + PSTREAMENGINE_CONTEXT ctx; + CStreamEngine* streamEngine = NULL; + + PAGED_CODE(); + + ctx = GetStreamEngineContext(Stream); + + streamEngine = static_cast(ctx->StreamEngine); + + return streamEngine->GetPresentationPosition(PositionInBlocks, QPCPosition); +} + diff --git a/audio/Acx/Samples/Common/StreamEngine.h b/audio/Acx/Samples/Common/StreamEngine.h new file mode 100644 index 000000000..deeff95a6 --- /dev/null +++ b/audio/Acx/Samples/Common/StreamEngine.h @@ -0,0 +1,449 @@ +#pragma once + +#include "savedata.h" +#include "tonegenerator.h" +#include "WaveReader.h" +#include "SimPeakMeter.h" +#include "keyworddetector.h" + +#define HNSTIME_PER_MILLISECOND 10000 + +#define MAX_PACKET_COUNT 2 + +#define DEFAULT_FREQUENCY 220 +#define LOOPBACK_FREQUENCY 500 + +// Stream callbacks shared between Capture and Render + +VOID +EvtStreamDestroy( + _In_ WDFOBJECT Object +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetHwLatency( + _In_ ACXSTREAM Stream, + _Out_ ULONG* FifoSize, + _Out_ ULONG* Delay +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamAllocateRtPackets( + _In_ ACXSTREAM Stream, + _In_ ULONG PacketCount, + _In_ ULONG PacketSize, + _Out_ PACX_RTPACKET* Packets +); + +PAGED_CODE_SEG +VOID +EvtStreamFreeRtPackets( + _In_ ACXSTREAM Stream, + _In_ PACX_RTPACKET Packets, + _In_ ULONG PacketCount +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamPrepareHardware( + _In_ ACXSTREAM Stream +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamReleaseHardware( + _In_ ACXSTREAM Stream +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamRun( + _In_ ACXSTREAM Stream +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamPause( + _In_ ACXSTREAM Stream +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamAssignDrmContentId( + _In_ ACXSTREAM Stream, + _In_ ULONG DrmContentId, + _In_ PACXDRMRIGHTS DrmRights +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetCurrentPacket( + _In_ ACXSTREAM Stream, + _Out_ PULONG CurrentPacket +); + +PAGED_CODE_SEG +NTSTATUS +EvtStreamGetPresentationPosition( + _In_ ACXSTREAM Stream, + _Out_ PULONGLONG PositionInBlocks, + _Out_ PULONGLONG QPCPosition +); + + +class CStreamEngine +{ +public: + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + AllocateRtPackets( + _In_ ULONG PacketCount, + _In_ ULONG PacketSize, + _Out_ PACX_RTPACKET * Packets + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID + FreeRtPackets( + _Frees_ptr_ PACX_RTPACKET Packets, + _In_ ULONG PacketCount + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + PrepareHardware(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + ReleaseHardware(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Run(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Pause(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetPresentationPosition( + _Out_ PULONGLONG PositionInBlocks, + _Out_ PULONGLONG QPCPosition + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetLinearBufferPosition( + _Out_ PULONGLONG Position + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetCurrentWritePosition( + _In_ ULONG Position + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetLastBufferPosition( + _In_ ULONG Position + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetCurrentPacket( + _Out_ PULONG CurrentPacket + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetHWLatency( + _Out_ ULONG * FifoSize, + _Out_ ULONG * Delay + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + AssignDrmContentId( + _In_ ULONG DrmContentId, + _In_ PACXDRMRIGHTS DrmRights + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CSimPeakMeter * + GetPeakMeter(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ BOOL Offload, + _In_opt_ CSimPeakMeter *CircuitPeakmeter + ); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CStreamEngine(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID + SetFrequency( + _In_ DWORD ToneFrequency + ) + { + PAGED_CODE(); + + m_ToneFrequency = ToneFrequency; + } + +protected: + PVOID m_Packets[MAX_PACKET_COUNT]; + ULONG m_PacketsCount; + ULONG m_PacketSize; + ULONG m_FirstPacketOffset; + WDFTIMER m_NotificationTimer; + ACX_STREAM_STATE m_CurrentState; + ULONG m_CurrentPacket; + ULONGLONG m_Position; + ACXSTREAM m_Stream; + ACXDATAFORMAT m_StreamFormat; + ULONGLONG m_StartTime; + ULONGLONG m_StartPosition; + ULONGLONG m_GlitchAdjust; + LARGE_INTEGER m_PerformanceCounterFrequency; + LARGE_INTEGER m_CurrentPacketStart; + LARGE_INTEGER m_LastPacketStart; + DWORD m_ToneFrequency; + BOOL m_Offload; + CSimPeakMeter m_PeakMeter; + CSimPeakMeter* m_pCircuitPeakmeter; + + static + __drv_maxIRQL(DISPATCH_LEVEL) + _Function_class_(EVT_WDF_TIMER) + VOID s_EvtStreamPassCallback( + _In_ WDFTIMER Timer + ); + + // This is run every time the stream timer fires + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + StreamPassCallback(); + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + ScheduleNextPass(); + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + UpdatePosition(); + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + ULONG + GetBytesPerSecond(); + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + ProcessPacket() = 0; +}; + +class CRenderStreamEngine : public CStreamEngine +{ +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CRenderStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ BOOL Offload, + _In_ CSimPeakMeter *CircuitPeakmeter + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CRenderStreamEngine(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + PrepareHardware(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + ReleaseHardware(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + AssignDrmContentId( + _In_ ULONG DrmContentId, + _In_ PACXDRMRIGHTS DrmRights + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + SetRenderPacket( + _In_ ULONG Packet, + _In_ ULONG Flags, + _In_ ULONG EosPacketLength + ); + +protected: + CSaveData m_SaveData; + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + ProcessPacket(); + +}; + +class CCaptureStreamEngine : public CStreamEngine +{ +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CCaptureStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CCaptureStreamEngine(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + PrepareHardware(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + ReleaseHardware(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetCapturePacket( + _Out_ ULONG * LastCapturePacket, + _Out_ ULONGLONG * QPCPacketStart, + _Out_ BOOLEAN * MoreData + ); + +protected: + ToneGenerator m_ToneGenerator; + CWaveReader m_WaveReader; + DWORD m_EnableWaveCapture; + UNICODE_STRING m_HostCaptureFileName; + UNICODE_STRING m_LoopbackCaptureFileName; + + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + ProcessPacket(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + ReadRegistrySettings(); +}; + +class CBufferedCaptureStreamEngine : public CCaptureStreamEngine +{ +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CBufferedCaptureStreamEngine( + _In_ ACXSTREAM Stream, + _In_ ACXDATAFORMAT StreamFormat, + _In_ CKeywordDetector * KeywordDetector + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CBufferedCaptureStreamEngine(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Run(); + + virtual + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Pause(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + GetCapturePacket( + _Out_ ULONG * LastCapturePacket, + _Out_ ULONGLONG * QPCPacketStart, + _Out_ BOOLEAN * MoreData + ); + +protected: + virtual + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + ProcessPacket(); + + CKeywordDetector * m_KeywordDetector; +}; + +// Define circuit/stream pin context. +// +typedef struct _STREAM_TIMER_CONTEXT { + CStreamEngine * StreamEngine; +} STREAM_TIMER_CONTEXT, *PSTREAM_TIMER_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(STREAM_TIMER_CONTEXT, GetStreamTimerContext) diff --git a/audio/Acx/Samples/Common/ToneGenerator.cpp b/audio/Acx/Samples/Common/ToneGenerator.cpp new file mode 100644 index 000000000..fc30e3b28 --- /dev/null +++ b/audio/Acx/Samples/Common/ToneGenerator.cpp @@ -0,0 +1,297 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + ToneGenerator.cpp + +Abstract: + + Implementation of sine wave generator for ACX driver samples + + +--*/ +#include "private.h" +#include "public.h" +#include +#include +#include +#include +#include "ToneGenerator.h" + +#define TONEGENERATOR_POOLTAG 'rGnT' + +const double TONE_AMPLITUDE = 0.5; // Scalar value, should be between 0.0 - 1.0 +const double TWO_PI = M_PI * 2; + +DWORD g_DisableToneGenerator = 0; // default is to generate tones. + +#define IF_FAILED_JUMP(result, tag) do {if (!NT_SUCCESS(result)) {goto tag;}} while(false) +#define IF_TRUE_JUMP(result, tag) do {if (result) {goto tag;}} while(false) +#define IF_TRUE_ACTION_JUMP(result, action, tag) do {if (result) {action; goto tag;}} while(false) + +// +// Double to short conversion. +// +__drv_maxIRQL(DISPATCH_LEVEL) +short ConvertToShort(double Value) +{ + return (short)(Value * _I16_MAX); +}; + +// +// Double to char conversion. +// +__drv_maxIRQL(DISPATCH_LEVEL) +unsigned char ConvertToUChar(double Value) +{ + const double F_127_5 = 127.5; + return (unsigned char)(Value * F_127_5 + F_127_5); +}; + +// +// Ctor: basic init. +// +_Use_decl_annotations_ +PAGED_CODE_SEG +ToneGenerator::ToneGenerator() +: m_Frequency(0), + m_ChannelCount(0), + m_BitsPerSample(0), + m_SamplesPerSecond(0), + m_Mute(false), + m_PartialFrame(NULL), + m_PartialFrameBytes(0), + m_FrameSize(0) +{ + PAGED_CODE(); + + // Theta (double) and SampleIncrement (double) are init in the Init() method + // after saving the floating point state. +} + +// +// Dtor: free resources. +// +_Use_decl_annotations_ +PAGED_CODE_SEG +ToneGenerator::~ToneGenerator() +{ + PAGED_CODE(); + + if (m_PartialFrame) + { + ExFreePoolWithTag(m_PartialFrame, TONEGENERATOR_POOLTAG); + m_PartialFrame = NULL; + m_PartialFrameBytes = 0; + } +} + +// +// Init a new frame. +// Note: caller will save and restore the floatingpoint state. +// +#pragma warning(push) +// Caller wraps this routine between KeSaveFloatingPointState/KeRestoreFloatingPointState calls. +#pragma warning(disable: 28110) + +_Use_decl_annotations_ +VOID ToneGenerator::InitNewFrame +( + _Out_writes_bytes_(FrameSize) BYTE* Frame, + _In_ DWORD FrameSize +) +{ + double sinValue = TONE_AMPLITUDE * sin( m_Theta ); + + if (FrameSize != (DWORD)m_ChannelCount * m_BitsPerSample/8) + { + ASSERT(FALSE); + RtlZeroMemory(Frame, FrameSize); + return; + } + + for(ULONG i = 0; i < m_ChannelCount; ++i) + { + if (m_BitsPerSample == 8) + { + unsigned char *dataBuffer = reinterpret_cast(Frame); + dataBuffer[i] = ConvertToUChar(sinValue); + } + else // 16 bits per sample + { + short *dataBuffer = reinterpret_cast(Frame); + dataBuffer[i] = ConvertToShort(sinValue); + } + } + + m_Theta += m_SampleIncrement; + if (m_Theta >= TWO_PI) + { + m_Theta -= TWO_PI; + } +} +#pragma warning(pop) + +// +// GenerateSamples() +// +// Generate a sine wave that fits into the specified buffer. +// +// Buffer - Buffer to hold the samples +// BufferLength - Length of the buffer. +// +// Note: this function supports 16bit and 8bit samples only. +// +_Use_decl_annotations_ +void ToneGenerator::GenerateSine +( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ size_t BufferLength +) +{ + NTSTATUS status; + KFLOATING_SAVE saveData; + BYTE * buffer; + size_t length; + size_t copyBytes; + + // if muted, or tone generator disabled via registry, + // we deliver silence. + if (m_Mute || g_DisableToneGenerator) + { + goto ZeroBuffer; + } + + status = KeSaveFloatingPointState(&saveData); + if (!NT_SUCCESS(status)) + { + goto ZeroBuffer; + } + + buffer = Buffer; + length = BufferLength; + + // + // Check if we have any residual frame bytes from the last time. + // + if (m_PartialFrameBytes) + { + ASSERT(m_FrameSize > m_PartialFrameBytes); + DWORD offset = m_FrameSize - m_PartialFrameBytes; + copyBytes = MIN(m_PartialFrameBytes, length); + RtlCopyMemory(buffer, m_PartialFrame + offset, copyBytes); + RtlZeroMemory(m_PartialFrame + offset, copyBytes); + length -= copyBytes; + buffer += copyBytes; + m_PartialFrameBytes = 0; + } + + IF_TRUE_JUMP(length == 0, Done); + + // + // Copy all the aligned frames. + // + + size_t frames = length/m_FrameSize; + + for (size_t i = 0; i < frames; ++i) + { + InitNewFrame(buffer, m_FrameSize); + buffer += m_FrameSize; + length -= m_FrameSize; + } + + IF_TRUE_JUMP(length == 0, Done); + + // + // Copy any partial frame at the end. + // + ASSERT(m_FrameSize > length); + InitNewFrame(m_PartialFrame, m_FrameSize); + RtlCopyMemory(buffer, m_PartialFrame, length); + RtlZeroMemory(m_PartialFrame, length); + m_PartialFrameBytes = m_FrameSize - (DWORD)length; + +Done: + KeRestoreFloatingPointState(&saveData); + return; + +ZeroBuffer: + RtlZeroMemory(Buffer, BufferLength); + return; +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS ToneGenerator::Init +( + _In_ DWORD ToneFrequency, + _In_ PWAVEFORMATEXTENSIBLE WfExt +) +{ + NTSTATUS status = STATUS_SUCCESS; + KFLOATING_SAVE saveData; + + PAGED_CODE(); + + // + // This sample supports PCM 16bit formats only. + // + if ((WfExt->Format.wFormatTag != WAVE_FORMAT_PCM && + !(WfExt->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && + IsEqualGUIDAligned(WfExt->SubFormat, KSDATAFORMAT_SUBTYPE_PCM))) || + (WfExt->Format.wBitsPerSample != 16 && + WfExt->Format.wBitsPerSample != 8)) + { + status = STATUS_NOT_SUPPORTED; + } + IF_FAILED_JUMP(status, Done); + + // + // Save floating state (just in case). + // + status = KeSaveFloatingPointState(&saveData); + IF_FAILED_JUMP(status, Done); + + // + // Basic init. + // + RtlZeroMemory(&m_Theta, sizeof(m_Theta)); + m_Frequency = ToneFrequency; + m_ChannelCount = WfExt->Format.nChannels; // # channels. + m_BitsPerSample = WfExt->Format.wBitsPerSample; // bits per sample. + m_SamplesPerSecond = WfExt->Format.nSamplesPerSec; // samples per sec. + m_Mute = false; + m_SampleIncrement = (m_Frequency * TWO_PI) / (double)m_SamplesPerSecond; + m_FrameSize = (DWORD)m_ChannelCount * m_BitsPerSample/8; + ASSERT(m_FrameSize == WfExt->Format.nBlockAlign); + + // + // Restore floating state. + // + KeRestoreFloatingPointState(&saveData); + + // + // Allocate a buffer to hold a partial frame. + // + m_PartialFrame = (BYTE*)ExAllocatePool2( + POOL_FLAG_NON_PAGED, + m_FrameSize, + TONEGENERATOR_POOLTAG); + + IF_TRUE_ACTION_JUMP(m_PartialFrame == NULL, status = STATUS_INSUFFICIENT_RESOURCES, Done); + + status = STATUS_SUCCESS; + +Done: + return status; +} + + diff --git a/audio/Acx/Samples/Common/ToneGenerator.h b/audio/Acx/Samples/Common/ToneGenerator.h new file mode 100644 index 000000000..9de138f83 --- /dev/null +++ b/audio/Acx/Samples/Common/ToneGenerator.h @@ -0,0 +1,88 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + ToneGenerator.h + +Abstract: + + Declaration of sine wave generator for ACX driver samples. + + +--*/ +#pragma once + +#define _USE_MATH_DEFINES +#include +#include + +class ToneGenerator +{ +public: + DWORD m_Frequency; + WORD m_ChannelCount; + WORD m_BitsPerSample; + DWORD m_SamplesPerSecond; + double m_Theta; + double m_SampleIncrement; + bool m_Mute; + BYTE* m_PartialFrame; + DWORD m_PartialFrameBytes; + DWORD m_FrameSize; + +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ToneGenerator(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~ToneGenerator(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS + Init + ( + _In_ DWORD ToneFrequency, + _In_ PWAVEFORMATEXTENSIBLE WfExt + ); + + __drv_maxIRQL(DISPATCH_LEVEL) + VOID + GenerateSine + ( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ size_t BufferLength + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID + SetMute + ( + _In_ bool Value + ) + { + PAGED_CODE(); + + m_Mute = Value; + } + +private: + __drv_maxIRQL(DISPATCH_LEVEL) + VOID InitNewFrame + ( + _Out_writes_bytes_(FrameSize) BYTE* Frame, + _In_ DWORD FrameSize + ); +}; + + diff --git a/audio/Acx/Samples/Common/Trace_macros.h b/audio/Acx/Samples/Common/Trace_macros.h new file mode 100644 index 000000000..5291b3916 --- /dev/null +++ b/audio/Acx/Samples/Common/Trace_macros.h @@ -0,0 +1,470 @@ +#pragma once + +#include // for va_start, etc. + +#pragma region Tracing level definitions + +#if !defined(FAILED_NTSTATUS) +#define FAILED_NTSTATUS(status) (((NTSTATUS)(status)) < 0) +#endif + +#if !defined(SUCCEEDED_NTSTATUS) +#define SUCCEEDED_NTSTATUS(status) (((NTSTATUS)(status)) >= 0) +#endif + +//! Define shorter versions of the ETW trace levels +#define LEVEL_CRITICAL TRACE_LEVEL_CRITICAL +#define LEVEL_ERROR TRACE_LEVEL_ERROR +#define LEVEL_WARNING TRACE_LEVEL_WARNING +#define LEVEL_INFO TRACE_LEVEL_INFORMATION +#define LEVEL_VERBOSE TRACE_LEVEL_VERBOSE + +//! This is a special LEVEL that changes the trace macro level from ERROR to VERBOSE +//! depending on whether the return value passed to the macro was non-zero or zero, +//! respectively. +#define LEVEL_COND 0xFF +#pragma endregion + +//! Logger and Enabled that supports both level and flag. +//! \link https://msdn.microsoft.com/en-us/library/windows/hardware/ff542492(v=vs.85).aspx +#define WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) WPP_LEVEL_LOGGER(FLAGS) +#define WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) (WPP_LEVEL_ENABLED(FLAGS) && (WPP_CONTROL(WPP_BIT_ ## FLAGS).Level >= LEVEL)) + +//! This macro is to be used by the WPP custom macros below that want to do conditional +//! logging based on return value. If LEVEL_VERBOSE is specified when calling a macro that +//! uses this, the level will be set to LEVEL_INFO if return code is 0 or +//! LEVEL_ERROR if the return code is not 0. This can be called in any PRE macro. +//! +//! The "LEVEL == LEVEL_COND" check generates a compiler warning that the "conditional +//! expression is constant" so we explicitly disable that. +#define WPP_CONDITIONAL_LEVEL_FLAGS_OVERRIDE(LEVEL, FLAGS, HR) \ + BOOL bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS); \ + __pragma(warning(push)) \ + __pragma(warning(disable: 4127)) \ + if (LEVEL == LEVEL_COND) \ + { \ + if (SUCCEEDED(HR)) \ + { \ + bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL_VERBOSE, FLAGS); \ + } \ + else \ + { \ + bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL_ERROR, FLAGS); \ + } \ + } \ + __pragma(warning(pop)) + +#define WPP_CONDITIONAL_LEVEL_FLAGS_OVERRIDE_NTSTATUS(LEVEL, FLAGS, STATUS) \ + BOOLEAN bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS); \ + __pragma(warning(push)) \ + __pragma(warning(disable: 4127)) \ + if (LEVEL == LEVEL_COND) \ + { \ + if (SUCCEEDED_NTSTATUS(STATUS)) \ + { \ + bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL_VERBOSE, FLAGS); \ + } \ + else \ + { \ + bEnabled = WPP_LEVEL_FLAGS_ENABLED(LEVEL_ERROR, FLAGS); \ + } \ + } \ + __pragma(warning(pop)) + + +#define WPP_LEVEL_FLAGS_IFRLOG_ENABLED(LEVEL, FLAGS, IFRLOG) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_IFRLOG_LOGGER(LEVEL, FLAGS, IFRLOG) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) +#define WPP_LEVEL_IFRLOG_FLAGS_ENABLED(LEVEL, IFRLOG, FLAGS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_IFRLOG_FLAGS_LOGGER(LEVEL, IFRLOG, FLAGS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_HR_PRE(LEVEL, FLAGS, HR) { WPP_CONDITIONAL_LEVEL_FLAGS_OVERRIDE(LEVEL, FLAGS, HR) +#define WPP_LEVEL_FLAGS_HR_POST(LEVEL, FLAGS, HR) ;} +#define WPP_LEVEL_FLAGS_HR_ENABLED(LEVEL, FLAGS, HR) bEnabled +#define WPP_LEVEL_FLAGS_HR_LOGGER(LEVEL, FLAGS, HR) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETVAL_ENABLED(LEVEL, FLAGS, RETVAL) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETVAL_LOGGER(LEVEL, FLAGS, RETVAL) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_FI_ENABLED(LEVEL, FLAGS, FI) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_FI_LOGGER(LEVEL, FLAGS, FI) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_STATUS_PRE(LEVEL, FLAGS, STATUS) { WPP_CONDITIONAL_LEVEL_FLAGS_OVERRIDE_NTSTATUS(LEVEL, FLAGS, STATUS) +#define WPP_LEVEL_FLAGS_STATUS_POST(LEVEL, FLAGS, STATUS) ;} +#define WPP_LEVEL_FLAGS_STATUS_ENABLED(LEVEL, FLAGS, STATUS) bEnabled +#define WPP_LEVEL_FLAGS_STATUS_LOGGER(LEVEL, FLAGS, STATUS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETSTATUS_PRE(LEVEL, FLAGS, RETSTATUS) do { NTSTATUS __statusRet = (RETSTATUS); if (FAILED_NTSTATUS(__statusRet)) { +#define WPP_LEVEL_FLAGS_RETSTATUS_POST(LEVEL, FLAGS, RETSTATUS) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_RETSTATUS_ENABLED(LEVEL, FLAGS, RETSTATUS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETSTATUS_LOGGER(LEVEL, FLAGS, RETSTATUS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_PRE(LEVEL, FLAGS, IFRLOG, RETSTATUS) do { NTSTATUS __statusRet = (RETSTATUS); if (FAILED_NTSTATUS(__statusRet)) { +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_POST(LEVEL, FLAGS, IFRLOG, RETSTATUS) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_ENABLED(LEVEL, FLAGS, IFRLOG, RETSTATUS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_LOGGER(LEVEL, FLAGS, IFRLOG, RETSTATUS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_PRE(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) do {\ +NTSTATUS __statusRet = (RETSTATUS);\ +if(__statusRet == ALLOWEDSTATUS)\ +{\ + __statusRet = STATUS_SUCCESS;\ +}\ +if (FAILED_NTSTATUS(__statusRet)) { +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_POST(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_ENABLED(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_LOGGER(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETPTR_PRE(LEVEL, FLAGS, RETPTR) do { if ((RETPTR) == nullptr) { +#define WPP_LEVEL_FLAGS_RETPTR_POST(LEVEL, FLAGS, RETPTR) ; return STATUS_INSUFFICIENT_RESOURCES; } } while (0, 0) +#define WPP_LEVEL_FLAGS_RETPTR_ENABLED(LEVEL, FLAGS, RETPTR) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETPTR_LOGGER(LEVEL, FLAGS, RETPTR) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETSTATUS_RETPTR_PRE(LEVEL, FLAGS, RETSTATUS, RETPTR) do { NTSTATUS __statusRet = (RETSTATUS); if ((RETPTR) == nullptr) { +#define WPP_LEVEL_FLAGS_RETSTATUS_RETPTR_POST(LEVEL, FLAGS, RETSTATUS, RETPTR) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_RETSTATUS_RETPTR_ENABLED(LEVEL, FLAGS, RETSTATUS, RETPTR) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETSTATUS_RETPTR_LOGGER(LEVEL, FLAGS, RETSTATUS, RETPTR) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETSTATUS_POSCOND_PRE(LEVEL, FLAGS, RETSTATUS, POSCOND) do { NTSTATUS __statusRet = (RETSTATUS); if ((POSCOND)) { +#define WPP_LEVEL_FLAGS_RETSTATUS_POSCOND_POST(LEVEL, FLAGS, RETSTATUS, POSCOND) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_RETSTATUS_POSCOND_ENABLED(LEVEL, FLAGS, RETSTATUS, POSCOND) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETSTATUS_POSCOND_LOGGER(LEVEL, FLAGS, RETSTATUS, POSCOND) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_PRE(LEVEL, FLAGS, IFRLOG, POSCOND, RETSTATUS) do { NTSTATUS __statusRet = (RETSTATUS); if ((POSCOND)) { +#define WPP_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_POST(LEVEL, FLAGS, IFRLOG, POSCOND, RETSTATUS) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_ENABLED(LEVEL, FLAGS, IFRLOG, POSCOND, RETSTATUS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_LOGGER(LEVEL, FLAGS, IFRLOG, POSCOND, RETSTATUS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#define WPP_LEVEL_FLAGS_RETSTATUS_NEGCOND_PRE(LEVEL, FLAGS, RETSTATUS, NEGCOND) do { NTSTATUS __statusRet = (RETSTATUS); if (!(NEGCOND)) { +#define WPP_LEVEL_FLAGS_RETSTATUS_NEGCOND_POST(LEVEL, FLAGS, RETSTATUS, NEGCOND) ; return __statusRet; } } while (0, 0) +#define WPP_LEVEL_FLAGS_RETSTATUS_NEGCOND_ENABLED(LEVEL, FLAGS, RETSTATUS, NEGCOND) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) +#define WPP_LEVEL_FLAGS_RETSTATUS_NEGCOND_LOGGER(LEVEL, FLAGS, RETSTATUS, NEGCOND) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) + +#pragma region IFR Enablement Macros + +// Opt-in to a WPP recorder feature that enables independent evaluation of conditions to decide if a +// message needs to be sent to the recorder, an enabled session, or both. +#define ENABLE_WPP_TRACE_FILTERING_WITH_WPP_RECORDER 1 + +// Logger/Enabled macros used to decide if a message that is being sent to a custom recorder should +// also go to an enabled session. These do not depend on the custom recorder itself, so just +// delegate to the default. +#define WPP_IFRLOG_LEVEL_FLAGS_LOGGER(IFRLOG, LEVEL, FLAGS) WPP_LEVEL_FLAGS_LOGGER(LEVEL, FLAGS) +#define WPP_IFRLOG_LEVEL_FLAGS_ENABLED(IFRLOG, LEVEL, FLAGS) WPP_LEVEL_FLAGS_ENABLED(LEVEL, FLAGS) + +#define WPP_RECORDER_CONDITIONAL_LEVEL_FLAGS_OVERRIDE(LEVEL, FLAGS, HR) \ + ((LEVEL == LEVEL_COND) ? \ + (FAILED(HR) ? \ + WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL_ERROR, FLAGS) : WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL_VERBOSE, FLAGS)) : \ + WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS)) + +#define WPP_RECORDER_CONDITIONAL_LEVEL_FLAGS_OVERRIDE_NTSTATUS(LEVEL, FLAGS, STATUS) \ + ((LEVEL == LEVEL_COND) ? \ + (FAILED_NTSTATUS(STATUS) ? \ + WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL_ERROR, FLAGS) : WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL_VERBOSE, FLAGS)) : \ + WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS)) + +#define WPP_RECORDER_LEVEL_FLAGS_HR_ARGS(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_HR_FILTER(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETVAL_ARGS(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETVAL_FILTER(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_FI_ARGS(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_FI_FILTER(LEVEL, FLAGS, RETVAL) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_STATUS_ARGS(LEVEL, FLAGS, STATUS) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_STATUS_FILTER(LEVEL, FLAGS, STATUS) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_ARGS(LEVEL, FLAGS, RETSTATUS) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_FILTER(LEVEL, FLAGS, RETSTATUS) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_RETSTATUS_ARGS(LEVEL, FLAGS, IFRLOG, RETSTATUS) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_RETSTATUS_FILTER(LEVEL, FLAGS, IFRLOG, RETSTATUS) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_ARGS(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_RETSTATUS_ALLOWEDSTATUS_FILTER(LEVEL, FLAGS, IFRLOG, RETSTATUS, ALLOWEDSTATUS) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETPTR_ARGS(LEVEL, FLAGS, RETPTR) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETPTR_FILTER(LEVEL, FLAGS, RETPTR) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_RETPTR_ARGS(LEVEL, FLAGS, RETSTATUS, RETPTR) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_RETPTR_FILTER(LEVEL, FLAGS, RETSTATUS, RETPTR) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_POSCOND_ARGS(LEVEL, FLAGS, RETSTATUS, POSCOND) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_POSCOND_FILTER(LEVEL, FLAGS, RETSTATUS, POSCOND) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_ARGS(LEVEL, FLAGS, IFRLOG, RETSTATUS, POSCOND) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_IFRLOG_POSCOND_RETSTATUS_FILTER(LEVEL, FLAGS, IFRLOG, RETSTATUS, POSCOND) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) + +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_NEGCOND_ARGS(LEVEL, FLAGS, RETSTATUS, NEGCOND) WPP_RECORDER_LEVEL_FLAGS_ARGS(LEVEL, FLAGS) +#define WPP_RECORDER_LEVEL_FLAGS_RETSTATUS_NEGCOND_FILTER(LEVEL, FLAGS, RETSTATUS, NEGCOND) WPP_RECORDER_LEVEL_FLAGS_FILTER(LEVEL, FLAGS) +#pragma endregion + +#pragma region Custom tracing macros + +// begin_wpp config +// USEPREFIX(DrvLogCritical, "%!STDPREFIX!CRIT: "); +// USEPREFIX(DrvLogError, "%!STDPREFIX!ERROR: "); +// USEPREFIX(DrvLogWarning, "%!STDPREFIX!WARN: "); +// USEPREFIX(DrvLogInfo, "%!STDPREFIX!INFO: "); +// USEPREFIX(DrvLogVerbose, "%!STDPREFIX!VERB: "); +// USEPREFIX(DrvLogEnter, "%!STDPREFIX!ENTER"); +// USEPREFIX(DrvLogExit, "%!STDPREFIX!EXIT"); +// end_wpp + +// begin_wpp config +// FUNC DrvLogCritical{LEVEL=TRACE_LEVEL_CRITICAL}(IFRLOG,FLAGS,MSG,...); +// FUNC DrvLogError{LEVEL=TRACE_LEVEL_ERROR}(IFRLOG,FLAGS,MSG,...); +// FUNC DrvLogWarning{LEVEL=TRACE_LEVEL_WARNING}(IFRLOG,FLAGS,MSG,...); +// FUNC DrvLogInfo{LEVEL=TRACE_LEVEL_INFORMATION}(IFRLOG,FLAGS,MSG,...); +// FUNC DrvLogEnter{LEVEL=TRACE_LEVEL_VERBOSE,FLAGS=FLAG_FUNCTION}(IFRLOG,...); +// FUNC DrvLogVerbose{LEVEL=TRACE_LEVEL_VERBOSE}(IFRLOG,FLAGS,MSG,...); +// FUNC DrvLogExit{LEVEL=TRACE_LEVEL_VERBOSE,FLAGS=FLAG_FUNCTION}(IFRLOG,...); +// end_wpp + + +#ifdef __INTELLISENSE__ +#define FLAG_DEVICE_ALL 0x01 +#define FLAG_FUNCTION 0x02 +#define FLAG_INFO 0x04 +#define FLAG_PNP 0x08 +#define FLAG_POWER 0x10 +#define FLAG_STREAM 0x20 +#define FLAG_INIT 0x40 +#define FLAG_DDI 0x80 +#define FLAG_GENERIC 0x100 +void DrvLogCritical(void* log, int flags, const WCHAR* fmt, ...); +void DrvLogError(void* log, int flags, const WCHAR* fmt, ...); +void DrvLogWarning(void* log, int flags, const WCHAR* fmt, ...); +void DrvLogInfo(void* log, int flags, const WCHAR* fmt, ...); +void DrvLogEnter(void* log, ...); +void DrvLogVerbose(void* log, int flags, const WCHAR* fmt, ...); +void DrvLogExit(void* log, ...); + +void RETURN_IF_FAILED(NTSTATUS status); +void RETURN_NTSTATUS_IF_FAILED(NTSTATUS status); +void RETURN_NTSTATUS_IF_FAILED_MSG(NTSTATUS status, const WCHAR* fmt, ...); +void RETURN_NTSTATUS_IF_FAILED_UNLESS_ALLOWED(NTSTATUS returnStatus, NTSTATUS allowedStatus); +void RETURN_NTSTATUS_IF_NULL_ALLOC(PVOID ptr); +void RETURN_NTSTATUS_IF_NULL(PVOID ptr); +void RETURN_NTSTATUS_IF_TRUE(BOOL condition, NTSTATUS status); +void RETURN_NTSTATUS_IF_TRUE_MSG(BOOL condition, NTSTATUS status, const WCHAR* fmt, ...); +void RETURN_NTSTATUS_IF_FALSE(BOOL condition, NTSTATUS status); +void RETURN_NTSTATUS(NTSTATUS status); +void RETURN_NTSTATUS_MSG(NTSTATUS status, const WCHAR* fmt, ...); +#endif// __INTELLISENSE__ + +//********************************************************* +// MACRO: TRACE_METHOD_LINE +// +// begin_wpp config +// FUNC TRACE_METHOD_LINE(LEVEL, FLAGS, MSG, ...); +// USESUFFIX (TRACE_METHOD_LINE, ", this=0x%p", this); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_ENTRY +// +// begin_wpp config +// FUNC TRACE_METHOD_ENTRY(LEVEL, FLAGS); +// USESUFFIX (TRACE_METHOD_ENTRY, "Enter, this=0x%p", this); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_EXIT +// +// begin_wpp config +// FUNC TRACE_METHOD_EXIT(LEVEL, FLAGS); +// USESUFFIX (TRACE_METHOD_EXIT, "Exit, this=0x%p", this); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_EXIT_HR +// +// begin_wpp config +// FUNC TRACE_METHOD_EXIT_HR(LEVEL, FLAGS, HR); +// USESUFFIX (TRACE_METHOD_EXIT_HR, "Exit, this=0x%p, hr=%!HRESULT!", this, HR); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_EXIT_DWORD +// +// begin_wpp config +// FUNC TRACE_METHOD_EXIT_DWORD(LEVEL, FLAGS, RETVAL); +// USESUFFIX (TRACE_METHOD_EXIT_DWORD, "Exit, this=0x%p, ret=0x%08Ix ", this, RETVAL); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_EXIT_PTR +// +// begin_wpp config +// FUNC TRACE_METHOD_EXIT_PTR(LEVEL, FLAGS, RETVAL); +// USESUFFIX (TRACE_METHOD_EXIT_PTR,"Exit, this=0x%p, retptr=0x%p", this, RETVAL); +// end_wpp + +//********************************************************* +// MACRO: TRACE_METHOD_EXIT_STATUS +// +// begin_wpp config +// FUNC TRACE_METHOD_EXIT_STATUS(LEVEL, FLAGS, STATUS); +// USESUFFIX (TRACE_METHOD_EXIT_STATUS, "Exit, this=0x%p, status=%!STATUS!", this, STATUS); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_ENTRY +// +// begin_wpp config +// FUNC TRACE_FUNCTION_ENTRY(LEVEL, FLAGS); +// USESUFFIX (TRACE_FUNCTION_ENTRY, "Enter"); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_EXIT +// +// begin_wpp config +// FUNC TRACE_FUNCTION_EXIT(LEVEL, FLAGS); +// USESUFFIX (TRACE_FUNCTION_EXIT, "Exit"); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_EXIT_HR +// +// begin_wpp config +// FUNC TRACE_FUNCTION_EXIT_HR(LEVEL, FLAGS, HR); +// USESUFFIX (TRACE_FUNCTION_EXIT_HR, "Exit, hr=%!HRESULT!", HR); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_EXIT_DWORD +// +// begin_wpp config +// FUNC TRACE_FUNCTION_EXIT_DWORD(LEVEL, FLAGS, RETVAL); +// USESUFFIX (TRACE_FUNCTION_EXIT_DWORD, "Exit, ret=0x%08Ix", RETVAL); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_EXIT_PTR +// +// begin_wpp config +// FUNC TRACE_FUNCTION_EXIT_PTR(LEVEL, FLAGS, RETVAL); +// USESUFFIX (TRACE_FUNCTION_EXIT_PTR, "Exit, retptr=0x%p", RETVAL); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FUNCTION_EXIT_STATUS +// +// begin_wpp config +// FUNC TRACE_FUNCTION_EXIT_STATUS(LEVEL, FLAGS, STATUS); +// USESUFFIX (TRACE_FUNCTION_EXIT_STATUS, "Exit, status=%!STATUS!", STATUS); +// end_wpp + +//********************************************************* +// MACRO: TRACE_LINE +// +// begin_wpp config +// FUNC TRACE_LINE(LEVEL, FLAGS, MSG, ...); +// end_wpp + +//********************************************************* +// MACRO: TRACE_HRESULT +// +// begin_wpp config +// FUNC TRACE_HRESULT(LEVEL, FLAGS, HR, MSG, ...); +// USESUFFIX (TRACE_HRESULT, ", ret=%!HRESULT!", HR); +// end_wpp + +//********************************************************* +// MACRO: TRACE_FAILURE_INFO (WIL FailureInfo logging) +// see: https://github.com/microsoft/wil/blob/master/include/wil/result_macros.h +// +// begin_wpp config +// FUNC TRACE_FAILURE_INFO(LEVEL, FLAGS, FI); +// USESUFFIX(TRACE_FAILURE_INFO, " [%04X] '%ws', hr=%!HRESULT! ['%s' (%u)]", FI.threadId, FI.pszMessage, FI.hr, FI.pszFile, FI.uLineNumber); +// end_wpp + +// MACRO: RETURN_IF_FAILED +// +// begin_wpp config +// FUNC RETURN_IF_FAILED{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS); +// USEPREFIX(RETURN_IF_FAILED, "%!STDPREFIX!ERROR:"); +// USESUFFIX(RETURN_IF_FAILED, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + + +// MACRO: RETURN_NTSTATUS_IF_FAILED +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_FAILED{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS); +// USEPREFIX(RETURN_NTSTATUS_IF_FAILED, "%!STDPREFIX!ERROR:"); +// USESUFFIX(RETURN_NTSTATUS_IF_FAILED, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_FAILED_MSG +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_FAILED_MSG{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS, MSG, ...); +// USEPREFIX(RETURN_NTSTATUS_IF_FAILED_MSG, "%!STDPREFIX!ERROR:"); +// USESUFFIX(RETURN_NTSTATUS_IF_FAILED_MSG, " - status=%!STATUS!",__statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_FAILED_UNLESS_ALLOWED +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_FAILED_UNLESS_ALLOWED{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS, ALLOWEDSTATUS); +// USEPREFIX(RETURN_NTSTATUS_IF_FAILED_UNLESS_ALLOWED, "%!STDPREFIX!ERROR:"); +// USESUFFIX(RETURN_NTSTATUS_IF_FAILED_UNLESS_ALLOWED, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_NULL_ALLOC +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_NULL_ALLOC{LEVEL=LEVEL_ERROR,FLAGS=DUMMY}(RETPTR); +// USESUFFIX(RETURN_NTSTATUS_IF_NULL, "status=STATUS_INSUFFICIENT_RESOURCES"); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_NULL +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_NULL{LEVEL=LEVEL_ERROR,FLAGS=DUMMY}(RETSTATUS, RETPTR); +// USESUFFIX(RETURN_NTSTATUS_IF_NULL, "status=%!STATUS!", __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_TRUE +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_TRUE{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(POSCOND, RETSTATUS); +// USESUFFIX(RETURN_NTSTATUS_IF_TRUE, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_TRUE_MSG +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_TRUE_MSG{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(POSCOND, RETSTATUS, MSG, ...); +// USESUFFIX(RETURN_NTSTATUS_IF_TRUE_MSG, " - status=%!STATUS!", __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_IF_FALSE +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_IF_FALSE{LEVEL=LEVEL_ERROR,FLAGS=DUMMY}(RETSTATUS, NEGCOND); +// USESUFFIX(RETURN_NTSTATUS_IF_FALSE, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS +// +// begin_wpp config +// FUNC RETURN_NTSTATUS{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS); +// USESUFFIX(RETURN_NTSTATUS, " File:%s, Line:%d - status=%!STATUS!", __FILE__, __LINE__, __statusRet); +// end_wpp + +// MACRO: RETURN_NTSTATUS_MSG +// +// begin_wpp config +// FUNC RETURN_NTSTATUS_MSG{LEVEL=LEVEL_ERROR,FLAGS=FLAG_DEVICE_ALL,IFRLOG=g_AudioDspLog}(RETSTATUS, MSG, ...); +// USESUFFIX(RETURN_NTSTATUS_MSG, " - status=%!STATUS!", __statusRet); +// end_wpp + +#define W32 +#define WPP_CHECK_FOR_NULL_STRING //to prevent exceptions due to NULL strings + +#pragma endregion diff --git a/audio/Acx/Samples/Common/WaveReader.cpp b/audio/Acx/Samples/Common/WaveReader.cpp new file mode 100644 index 000000000..4fa6eae90 --- /dev/null +++ b/audio/Acx/Samples/Common/WaveReader.cpp @@ -0,0 +1,769 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + WaveReader.cpp + +Abstract: + Implementation of wave file reader for ACX sample drivers. + + To read data from disk, this class maintains a circular data buffer. This buffer is segmented into multiple chunks of + big buffer (Though we only need two, so it is set to two now). Initially we fill first two chunks and once a chunk gets emptied + by OS, we schedule a workitem to fill the next available chunk. + + +--*/ + +#pragma warning (disable : 4127) +#pragma warning (disable : 26165) + +#include "private.h" +#include +#include +#include +#include +#include "WaveReader.h" + +#define FILE_NAME_BUFFER_TAG 'WRT1' +#define WAVE_DATA_BUFFER_TAG 'WRT2' +#define WORK_ITEM_BUFFER_TAG 'WRT3' + +#define MAX_READ_WORKER_ITEM_COUNT 15 + +#define IF_FAILED_JUMP(result, tag) do {if (!NT_SUCCESS(result)) {goto tag;}} while(false) +#define IF_TRUE_JUMP(result, tag) do {if (result) {goto tag;}} while(false) +#define IF_TRUE_ACTION_JUMP(result, action, tag) do {if (result) {action; goto tag;}} while(false) + +PREADWORKER_PARAM CWaveReader::m_pWorkItems = NULL; +PDEVICE_OBJECT CWaveReader::m_pDeviceObject = NULL; + + +/*++ + +Routine Description: + Ctor: basic init. + +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +CWaveReader::CWaveReader() +: m_ChannelCount(0), + m_BitsPerSample(0), + m_SamplesPerSecond(0), + m_Mute(false), + m_FileHandle(NULL) +{ + PAGED_CODE(); + m_WaveDataQueue.pWavData = NULL; + KeInitializeMutex(&m_FileSync, 0); +} + +/*++ + +Routine Description: + Dtor: free resources. + +--*/ +_Use_decl_annotations_ +PAGED_CODE_SEG +CWaveReader::~CWaveReader() +{ + PAGED_CODE(); + if (STATUS_SUCCESS == KeWaitForSingleObject + ( + &m_FileSync, + Executive, + KernelMode, + FALSE, + NULL + )) + { + if (m_WaveDataQueue.pWavData != NULL) + { + ExFreePoolWithTag(m_WaveDataQueue.pWavData, WAVE_DATA_BUFFER_TAG); + m_WaveDataQueue.pWavData = NULL; + } + + FileClose(); + KeReleaseMutex(&m_FileSync, FALSE); + } + +} + +/*++ + +Routine Description: + - Initializing the workitems. These workitems will be scheduled asynchronously by the OS. + - When these work items will be scheduled the wave file will be read and the data + - will be put inside the big chunks. + +Arguments: + Device object + +Return Value: + NT status code. + +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::InitializeWorkItems(_In_ PDEVICE_OBJECT DeviceObject) +{ + PAGED_CODE(); + + ASSERT(DeviceObject); + + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (m_pWorkItems != NULL) + { + return ntStatus; + } + + m_pWorkItems = (PREADWORKER_PARAM) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + sizeof(READWORKER_PARAM) * MAX_READ_WORKER_ITEM_COUNT, + 'RDPT' + ); + if (m_pWorkItems) + { + for (int i = 0; i < MAX_READ_WORKER_ITEM_COUNT; i++) + { + + m_pWorkItems[i].WorkItem = IoAllocateWorkItem(DeviceObject); + if (m_pWorkItems[i].WorkItem == NULL) + { + return STATUS_INSUFFICIENT_RESOURCES; + } + KeInitializeEvent + ( + &m_pWorkItems[i].EventDone, + NotificationEvent, + TRUE + ); + } + } + else + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + + return ntStatus; +} + +/*++ + +Routine Description: +- Wait for all the scheduled workitems to finish. + +--*/ + + +//============================================================================= +_Use_decl_annotations_ +PAGED_CODE_SEG +void CWaveReader::WaitAllWorkItems() +{ + PAGED_CODE(); + + for (int i = 0; i < MAX_READ_WORKER_ITEM_COUNT; i++) + { + KeWaitForSingleObject + ( + &(m_pWorkItems[i].EventDone), + Executive, + KernelMode, + FALSE, + NULL + ); + } +} + +/*++ + +Routine Description: + - Deallocating the workitems. + +--*/ + + +_Use_decl_annotations_ +PAGED_CODE_SEG +VOID CWaveReader::DestroyWorkItems() +{ + PAGED_CODE(); + + if (m_pWorkItems) + { + for (int i = 0; i < MAX_READ_WORKER_ITEM_COUNT; i++) + { + if (m_pWorkItems[i].WorkItem != NULL) + { + IoFreeWorkItem(m_pWorkItems[i].WorkItem); + m_pWorkItems[i].WorkItem = NULL; + } + } + ExFreePoolWithTag(m_pWorkItems, WORK_ITEM_BUFFER_TAG); + m_pWorkItems = NULL; + } +} + +/*++ + +Routine Description: + - Get a free work item to schedule a file read operation. + +--*/ +_Use_decl_annotations_ +PREADWORKER_PARAM CWaveReader::GetNewWorkItem() +{ + LARGE_INTEGER timeOut = { 0 }; + NTSTATUS ntStatus; + + for (int i = 0; i < MAX_READ_WORKER_ITEM_COUNT; i++) + { + ntStatus = + KeWaitForSingleObject + ( + &m_pWorkItems[i].EventDone, + Executive, + KernelMode, + FALSE, + &timeOut + ); + if (STATUS_SUCCESS == ntStatus) + { + if (m_pWorkItems[i].WorkItem) + return &(m_pWorkItems[i]); + else + return NULL; + } + } + + return NULL; +} + +/*++ +Routine Description: +- This routine will enqueue a workitem for reading wave file and putting +- the data into the chunk buffer. + +Arguments: + Chunk descriptor for the chunk to be filled. +--*/ + +_Use_decl_annotations_ +VOID CWaveReader::ReadWavChunk(PCHUNKDESCRIPTOR pChunkDescriptor) +{ + PREADWORKER_PARAM pParam = NULL; + + pParam = GetNewWorkItem(); + if (pParam) + { + pParam->PtrWaveReader = this; + pParam->PtrChunkDescriptor = pChunkDescriptor; + KeResetEvent(&pParam->EventDone); + IoQueueWorkItem(pParam->WorkItem, ReadFrameWorkerCallback, + DelayedWorkQueue, (PVOID)pParam); + } +} + +_Use_decl_annotations_ +PAGED_CODE_SEG +IO_WORKITEM_ROUTINE ReadFrameWorkerCallback; +/* +Routine Description: +- This routine will be called by the OS. It will fill the chunk buffer, defined by the chunk descriptor +- If end of file is reached it will mark the end of file as true. + +Arguments: + pDeviceObject - Device object + Context - pointer to reader worker params +*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +VOID ReadFrameWorkerCallback +( + _In_ PDEVICE_OBJECT pDeviceObject, + _In_opt_ PVOID Context +) +{ + PAGED_CODE(); + UNREFERENCED_PARAMETER(pDeviceObject); + pWaveReader pWavRd; + PREADWORKER_PARAM pParam = (PREADWORKER_PARAM)Context; + + if (NULL == pParam) + { + // This is completely unexpected, assert here. + // + ASSERT(pParam); + goto exit; + } + + pWavRd = pParam->PtrWaveReader; + + if (pWavRd == NULL) + { + goto exit; + } + if (STATUS_SUCCESS == KeWaitForSingleObject + ( + &pWavRd->m_FileSync, + Executive, + KernelMode, + FALSE, + NULL + )) + { + + NTSTATUS ntStatus = STATUS_SUCCESS; + + ASSERT(Context); + + IO_STATUS_BLOCK ioStatusBlock; + + if (pParam->WorkItem) + { + if (pWavRd->m_WaveDataQueue.bEofReached || pWavRd->m_WaveDataQueue.pWavData == NULL) + { + KeReleaseMutex(&pWavRd->m_FileSync, FALSE); + goto exit; + } + + if (pParam->PtrChunkDescriptor->pStartAddress != NULL) + { + ntStatus = ZwReadFile(pWavRd->m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + pParam->PtrChunkDescriptor->pStartAddress, + pParam->PtrChunkDescriptor->ulChunkLength, + NULL, + NULL); + + pParam->PtrChunkDescriptor->bIsChunkEmpty = false; + + if (ioStatusBlock.Information != pParam->PtrChunkDescriptor->ulChunkLength) + { + pWavRd->m_WaveDataQueue.bEofReached = true; + } + } + } + + KeReleaseMutex(&pWavRd->m_FileSync, FALSE); + } + +exit: + KeSetEvent(&pParam->EventDone, 0, FALSE); +} + +/*++ + +Routine Description: +- If all the chunks are empty this resturn true. + +--*/ + +_Use_decl_annotations_ +bool CWaveReader::IsAllChunkEmpty() +{ + for (int i = 0; i < NUM_OF_CHUNK_FOR_FILE_READ; i++) + { + if (!m_WaveDataQueue.sChunkDescriptor[i].bIsChunkEmpty) + { + return false; + } + } + return true; +} + +/*++ +Routine Description: + - This routine does the actual copy of data from the chunk buffer to the buffer provided by OS. + - If it empties the current chunk buffer, then it sets it state to empty and then enqueue a workitem + - to read data from the wave file and put it to the next available chunk buffer. + +Arguments: + Buffer - Pointer to the OS buffer + BufferLength - Length of the data to be filled (in bytes) + +--*/ +_Use_decl_annotations_ +VOID CWaveReader::CopyDataFromRingBuffer +( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ ULONG BufferLength +) +{ + if (IsAllChunkEmpty()) + { + RtlZeroMemory(Buffer, BufferLength); + } + else + { + ULONG prevChunk = (m_WaveDataQueue.ulReadPtr*NUM_OF_CHUNK_FOR_FILE_READ )/ m_WaveDataQueue.ulLength; + + ///////////////// + BYTE *currentBuf = Buffer; + ULONG length = BufferLength; + while (length > 0) + { + ULONG runWrite = min(length, m_WaveDataQueue.ulLength - m_WaveDataQueue.ulReadPtr); + + // Copy the wave buffer data to OS buffer + RtlCopyMemory(currentBuf, m_WaveDataQueue.pWavData + m_WaveDataQueue.ulReadPtr, runWrite); + // Zero out the wave buffer, so that if wave end of file is reached we should copy only zeros + RtlZeroMemory(m_WaveDataQueue.pWavData + m_WaveDataQueue.ulReadPtr, runWrite); + // Update the read pointer + m_WaveDataQueue.ulReadPtr = (m_WaveDataQueue.ulReadPtr + runWrite) % m_WaveDataQueue.ulLength; + currentBuf += runWrite; + length = length - runWrite; + } + + ULONG curChunk = (m_WaveDataQueue.ulReadPtr*NUM_OF_CHUNK_FOR_FILE_READ) / m_WaveDataQueue.ulLength; + + if (curChunk != prevChunk) + { + m_WaveDataQueue.currentExecutedChunk++; + // Schedule a workitem to read data from the wave file + ULONG chunkNo = m_WaveDataQueue.currentExecutedChunk % NUM_OF_CHUNK_FOR_FILE_READ; + m_WaveDataQueue.sChunkDescriptor[chunkNo].bIsChunkEmpty = true; + if (!m_WaveDataQueue.bEofReached) + { + ReadWavChunk(&m_WaveDataQueue.sChunkDescriptor[chunkNo]); + } + } + } +} + +/*++ +Routine Description: + - Just a high level read buffer call. + + Arguments: + Buffer - Pointer to the OS buffer + BufferLength - Length of the data to be filled (in bytes) +--*/ + +_Use_decl_annotations_ +VOID CWaveReader::ReadWaveData +( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ ULONG BufferLength +) +{ + if (m_Mute) + { + RtlZeroMemory(Buffer, BufferLength); + } + else + { + CopyDataFromRingBuffer(Buffer, BufferLength); + } +} + +/*++ +Routine Description: +- initialization for the wavereader member variables, +- Allocating memory for the 1 second buffer +- Preread the one second buffer data, so that when OS comes to read the data we have it available in the memory. + +Arguments: + WfExt - Format which should be used for capture + fileNameString - name of the file to be read + +Return: + NTStatus +--*/ +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::Init +( + _In_ PWAVEFORMATEXTENSIBLE WfExt, + _In_ PUNICODE_STRING puiFileName +) +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + KFLOATING_SAVE saveData; + + // Save floating state (just in case). + ntStatus = KeSaveFloatingPointState(&saveData); + if (!NT_SUCCESS(ntStatus)) + { + return ntStatus; + } + + // + // This sample supports PCM 16bit formats only. + // + if ((WfExt->Format.wFormatTag != WAVE_FORMAT_PCM && + !(WfExt->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && + IsEqualGUIDAligned(WfExt->SubFormat, KSDATAFORMAT_SUBTYPE_PCM))) || + (WfExt->Format.wBitsPerSample != 16 && + WfExt->Format.wBitsPerSample != 8)) + { + ntStatus = STATUS_NOT_SUPPORTED; + } + IF_FAILED_JUMP(ntStatus, Done); + + // Basic init. + m_ChannelCount = WfExt->Format.nChannels; // # channels. + m_BitsPerSample = WfExt->Format.wBitsPerSample; // bits per sample. + m_SamplesPerSecond = WfExt->Format.nSamplesPerSec; // samples per sec. + m_Mute = false; + + // Wave data queue initialization + m_WaveDataQueue.ulLength = WfExt->Format.nAvgBytesPerSec; + m_WaveDataQueue.bEofReached = false; + m_WaveDataQueue.ulReadPtr = 0; + + // Mark all the chunk empty + for (int i = 0; i < NUM_OF_CHUNK_FOR_FILE_READ; i++) + { + m_WaveDataQueue.sChunkDescriptor[i].bIsChunkEmpty = true; + } + + ntStatus = OpenWaveFile(puiFileName); + IF_FAILED_JUMP(ntStatus, Done); + + ntStatus = AllocateBigBuffer(); + IF_FAILED_JUMP(ntStatus, Done); + + ntStatus = ReadHeaderAndFillBuffer(); + +Done: + (void)KeRestoreFloatingPointState(&saveData); + return ntStatus; +} + +/*++ +Routine Description: + This function read the wave header file and compare the header info with the + stream info. Currently we are using only number of channel, sampling frequency + and bits per sample as the primary parameters for the wave file to compare against + stream params. If the params don't match we return success but streams zeros. + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::ReadHeaderAndFillBuffer() +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + ntStatus = FileReadHeader(); + + if(NT_SUCCESS(ntStatus)) + { + if (m_WaveHeader.numChannels != m_ChannelCount || + m_WaveHeader.bitsPerSample != m_BitsPerSample || + m_WaveHeader.sampleRate != m_SamplesPerSecond) + { + // If the wave file format don't match we wont treat this as error + // and we will stream zeros. So we return from here and will not read the + // wave file and wont fill the buffers. + return STATUS_SUCCESS; + } + } + + if (NT_SUCCESS(ntStatus)) + { + // If the wave file format is same as the stream format we will stream the data + // else we will just stream zeros. + ReadWavChunk(&m_WaveDataQueue.sChunkDescriptor[0]); // Fill the first chunk + ReadWavChunk(&m_WaveDataQueue.sChunkDescriptor[1]); // Fill the second chunk + // Set the current executed chunk to 1. Once OS finishs the data for the first chunk + // use the currentExecutedChunk to find the next chunk and schedule a workitem to fill the + // data into the next chunk + m_WaveDataQueue.currentExecutedChunk = 1; + } + + return ntStatus; +} + +/*++ +Routine Description: + This function allocates 1 second buffer. + Segments the buffer into multiple (currently two) chunks. Assigns the start pointer and length + for each chunk. + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::AllocateBigBuffer() +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + + m_WaveDataQueue.pWavData = (PBYTE) + ExAllocatePool2 + ( + POOL_FLAG_NON_PAGED, + m_WaveDataQueue.ulLength, + WAVE_DATA_BUFFER_TAG + ); + if (!m_WaveDataQueue.pWavData) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + else + { + ULONG chunklLength = m_WaveDataQueue.ulLength / NUM_OF_CHUNK_FOR_FILE_READ; + for (int i = 0; i < NUM_OF_CHUNK_FOR_FILE_READ; i++) + { + m_WaveDataQueue.sChunkDescriptor[i].pStartAddress = m_WaveDataQueue.pWavData + chunklLength*i; + m_WaveDataQueue.sChunkDescriptor[i].ulChunkLength = chunklLength; + } + } + return ntStatus; +} + +/*++ +Routine Description: + This function opens wave file. + +Arguments: + fileNameString - Name of the wave file + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::OpenWaveFile(PUNICODE_STRING puiFileName) +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (NT_SUCCESS(ntStatus) && puiFileName->Buffer != NULL) + { + // Create data file. + InitializeObjectAttributes + ( + &m_objectAttributes, + puiFileName, + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, + NULL + ); + + // Open Wave File + ntStatus = FileOpen(); + } + + return ntStatus; +} + +/*++ +Routine Description: + This function closes wave file handle. + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::FileClose() +{ + PAGED_CODE(); + + NTSTATUS ntStatus = STATUS_SUCCESS; + + if (m_FileHandle) + { + ntStatus = ZwClose(m_FileHandle); + m_FileHandle = NULL; + } + + return ntStatus; +} + +/*++ +Routine Description: + Reads the wave file file header information + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::FileReadHeader() +{ + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + IO_STATUS_BLOCK ioStatusBlock; + + + ntStatus = ZwReadFile(m_FileHandle, + NULL, + NULL, + NULL, + &ioStatusBlock, + &m_WaveHeader, + sizeof(WAVEHEADER), + NULL, + NULL); + + return ntStatus; +} + +/*++ +Routine Description: + This function opens wave file. + +Return: + NTStatus +--*/ + +_Use_decl_annotations_ +PAGED_CODE_SEG +NTSTATUS CWaveReader::FileOpen() +{ + + PAGED_CODE(); + NTSTATUS ntStatus = STATUS_SUCCESS; + IO_STATUS_BLOCK ioStatusBlock; + + if (!m_FileHandle) + { + ntStatus = + ZwCreateFile + ( + &m_FileHandle, + GENERIC_READ, + &m_objectAttributes, + &ioStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL, + FILE_SHARE_READ, + FILE_OPEN, + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0 + ); + } + + return ntStatus; +} + diff --git a/audio/Acx/Samples/Common/WaveReader.h b/audio/Acx/Samples/Common/WaveReader.h new file mode 100644 index 000000000..08516be79 --- /dev/null +++ b/audio/Acx/Samples/Common/WaveReader.h @@ -0,0 +1,196 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + WaveReader.h + +Abstract: + + Declaration of wave reader for ACX sample drivers. + + +--*/ +#pragma once + +#define _USE_MATH_DEFINES +#include +#include + +#define NUM_OF_CHUNK_FOR_FILE_READ 2 + +class CWaveReader; + +// Wave header structure decleration +typedef CWaveReader *pWaveReader; +typedef struct _WAVEHEADER +{ + BYTE chunkId[4]; + ULONG chunkSize; + BYTE format[4]; + BYTE subChunkId[4]; + ULONG subChunkSize; + WORD audioFormat; + WORD numChannels; + ULONG sampleRate; + ULONG bytesPerSecond; + WORD blockAlign; + WORD bitsPerSample; + BYTE dataChunkId[4]; + ULONG dataSize; +}WAVEHEADER; + +typedef struct _CHUNKDESCRIPTOR +{ + PBYTE pStartAddress; // Starting address of the chunk + ULONG ulChunkLength; // Length of the chunk + bool bIsChunkEmpty; // If the chunk is empty +}CHUNKDESCRIPTOR; +typedef CHUNKDESCRIPTOR *PCHUNKDESCRIPTOR; + +/* + The idea here is to allocate one second long worth of buffer and divide it into NUM_OF_CHUNK_FOR_FILE_READ chunks. + In one file read operation we read and fill one chunk data . The chunk will be emptied every 10 ms by OS. + Once the OS empties one chunk data we schedule a workitem to read and fill next available chunk. +*/ + +typedef struct _WAVEDATAQUEUE +{ + PBYTE pWavData; // Pointer to the temporary buffer for reading one second worth of data from wave file + ULONG ulLength; // length of pWavData in bytes + ULONG ulReadPtr; // current reading position in pWavData in bytes + bool bEofReached; // This will be set once the eof is reached. + WORD currentExecutedChunk; + CHUNKDESCRIPTOR sChunkDescriptor[NUM_OF_CHUNK_FOR_FILE_READ]; +}WAVEDATAQUEUE; +typedef WAVEDATAQUEUE *PWAVEDATAQUEUE; + +// Parameter to workitem. +#include +typedef struct _READWORKER_PARAM { + PIO_WORKITEM WorkItem; // Pointer to the workitem + KEVENT EventDone; // Used for synchronizing a workitem for scheduling. + pWaveReader PtrWaveReader; // pointer to the wavereader class. + PCHUNKDESCRIPTOR PtrChunkDescriptor; // chunk descriptor for the chunk, which needs to be filled after file read +} READWORKER_PARAM; +typedef READWORKER_PARAM *PREADWORKER_PARAM; +#include + +__drv_maxIRQL(PASSIVE_LEVEL) +PAGED_CODE_SEG +IO_WORKITEM_ROUTINE ReadFrameWorkerCallback; + +// Wave Reader class + +class CWaveReader +{ + +public: + HANDLE m_FileHandle; // Wave File handle. + WORD m_ChannelCount; // Number of Channels for the stream during stream init + WORD m_BitsPerSample; // Number of Bits per sample for the stream during stream init + DWORD m_SamplesPerSecond; // Number of Sample per second for the stream during stream init + bool m_Mute; // Capture Zero buffer if mute + OBJECT_ATTRIBUTES m_objectAttributes; // Used for opening file. + WAVEDATAQUEUE m_WaveDataQueue; // Big buffer data object and its current state + KMUTEX m_FileSync; // Synchronizes file access + WAVEHEADER m_WaveHeader; + +public: + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + CWaveReader(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + ~CWaveReader(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS Init + ( + _In_ PWAVEFORMATEXTENSIBLE WfExt, + _In_ PUNICODE_STRING puiFileName + ); + + __drv_maxIRQL(DISPATCH_LEVEL) + VOID ReadWaveData + ( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ ULONG BufferLength + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + VOID SetMute(_In_ bool Value) + { + PAGED_CODE(); + + m_Mute = Value; + } + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + void WaitAllWorkItems(); + + // Static allocation totally related to the workitems for reading data from wavefile and putting it to chunk buffer + static PDEVICE_OBJECT m_pDeviceObject; + static PREADWORKER_PARAM m_pWorkItems; + PAGED_CODE_SEG + static NTSTATUS InitializeWorkItems(_In_ PDEVICE_OBJECT DeviceObject); + + __drv_maxIRQL(DISPATCH_LEVEL) + static PREADWORKER_PARAM GetNewWorkItem(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + static VOID DestroyWorkItems(); + +private: + __drv_maxIRQL(DISPATCH_LEVEL) + VOID ReadWavChunk(PCHUNKDESCRIPTOR PtrChunkDescriptor); + + __drv_maxIRQL(DISPATCH_LEVEL) + bool IsAllChunkEmpty(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS OpenWaveFile(PUNICODE_STRING puiFileName); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS FileClose(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS FileReadHeader(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS FileOpen(); + + __drv_maxIRQL(DISPATCH_LEVEL) + VOID CopyDataFromRingBuffer + ( + _Out_writes_bytes_(BufferLength) BYTE *Buffer, + _In_ ULONG BufferLength + ); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS AllocateBigBuffer(); + + __drv_maxIRQL(PASSIVE_LEVEL) + PAGED_CODE_SEG + NTSTATUS ReadHeaderAndFillBuffer(); + + friend IO_WORKITEM_ROUTINE ReadFrameWorkerCallback; +}; + + diff --git a/audio/Acx/Samples/Inc/AudioFormats.h b/audio/Acx/Samples/Inc/AudioFormats.h new file mode 100644 index 000000000..8a48b1cfa --- /dev/null +++ b/audio/Acx/Samples/Inc/AudioFormats.h @@ -0,0 +1,959 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + AudioFormats.h + +Abstract: + + Contains Audio formats supported for the ACX Sample Drivers + +Environment: + + Kernel mode + +--*/ + +#pragma once + +#define NOBITMAP +#include + +// +// Basic-testing formats. +// +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm44100c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 44100, + 176400, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm44100c2_24in32 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 44100, + 352800, + 8, + 32, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 24, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm48000c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 48000, + 192000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm48000c2_24in32 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 48000, + 384000, + 8, + 32, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 24, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm192000c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 192000, + 768000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm44100c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 44100, + 88200, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm48000c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 48000, + 96000, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm16000c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 16000, + 32000, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm32000c2 = +{ // 14 + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 32000, + 128000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm88200c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 88200, + 352800, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm96000c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 96000, + 384000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm24000c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 24000, + 96000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm16000c2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 16000, + 64000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + 0, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm8000c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 8000, + 16000, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm11025c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 11025, + 22050, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm22050c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 22050, + 44100, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm24000c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 24000, + 48000, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm32000c1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 1, + 32000, + 64000, + 2, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_MONO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +// +// Definitions of HDMI specific audio formats. +// + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyDigital = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 48000, + 192000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyDigitalPlus = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 192000, + 768000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyDigitalPlusAtmos = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS_ATMOS), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 192000, + 768000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS_ATMOS) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyMlp = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyMlpSurround = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1_SURROUND, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DtsSurround = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 48000, + 192000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DtsHD = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DtsHDLowBitRate = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_STEREO, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DtsXE1 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTSX_E1), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTSX_E1) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DtsXE2 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTSX_E2), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DTSX_E2) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyMAT20 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MAT20), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MAT20) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE DolbyMAT21 = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MAT21), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 8, + 192000, + 3072000, + 16, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + KSAUDIO_SPEAKER_7POINT1, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MAT21) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm44100c2nomask = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 44100, + 176400, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX) + }, + 16, + 0, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +// No Mask version is used for 2ch Capture, where the mask is not meaningful +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm48000c2nomask = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 2, + 48000, + 192000, + 4, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + 0, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; + +static +KSDATAFORMAT_WAVEFORMATEXTENSIBLE Pcm16000c4nomask = +{ + { + sizeof(KSDATAFORMAT_WAVEFORMATEXTENSIBLE), + 0, + 0, + 0, + STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO), + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM), + STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) + }, + { + { + WAVE_FORMAT_EXTENSIBLE, + 4, + 16000, + 128000, + 8, + 16, + sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) + }, + 16, + 0, + STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM) + } +}; diff --git a/audio/Acx/Samples/Inc/cpp_utils.h b/audio/Acx/Samples/Inc/cpp_utils.h new file mode 100644 index 000000000..f4ed62207 --- /dev/null +++ b/audio/Acx/Samples/Inc/cpp_utils.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + cpp_utils.h + +Abstract: + + Contains CPP utilities + +Environment: + + Kernel mode + +--*/ + +#pragma once + +// Function scope_exit instantiates scope_exit object +// Constructor accepts lamda as parameter. +// Assign tasks in lamdba to be executed on scope exit. +template +auto scope_exit(F f) +{ + class scope_exit + { + public: + scope_exit(F f) : + _f{ f } + { + } + + ~scope_exit() + { + if (_call) + { + _f(); + } + } + + // Ensures the scope_exit lambda will not be called + void release() + { + _call = false; + } + + // Executes the scope_exit lambda immediately if not yet run; ensures it will not run again + void reset() + { + if (_call) + { + _f(); + _call = false; + } + } + + private: + F _f; + bool _call = true; + }; + + return scope_exit{ f }; +}; + diff --git a/audio/Acx/Samples/Shared/Public.h b/audio/Acx/Samples/Shared/Public.h new file mode 100644 index 000000000..f1e9da3bd --- /dev/null +++ b/audio/Acx/Samples/Shared/Public.h @@ -0,0 +1,342 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Public.h + +Abstract: + + Contains structure definitions and function prototypes for the driver + that are public. + +Environment: + + Kernel mode + +--*/ + +/* make prototypes usable from C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include "Trace.h" + +#include +#include + +#define PAGED_CODE_SEG __declspec(code_seg("PAGE")) +#define INIT_CODE_SEG __declspec(code_seg("INIT")) + +// Number of msec for idle timeout. +#define IDLE_POWER_TIMEOUT 5000 + +extern RECORDER_LOG g_AudioDspLog; +extern RECORDER_LOG g_AudioDspMcLog; + +// +// Define CODEC device context. +// +typedef struct _CODEC_DEVICE_CONTEXT { + ACXCIRCUIT Render; + ACXCIRCUIT Capture; + WDF_TRI_STATE ExcludeD3Cold; +} CODEC_DEVICE_CONTEXT, * PCODEC_DEVICE_CONTEXT; + +// +// Codec driver prototypes. +// +EVT_WDF_DRIVER_DEVICE_ADD Codec_EvtBusDeviceAdd; +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_UNLOAD AudioCodecDriverUnload; + +// +// Codec device callbacks. +// +EVT_WDF_DEVICE_PREPARE_HARDWARE Codec_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE Codec_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY Codec_EvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT Codec_EvtDeviceD0Exit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP Codec_EvtDeviceContextCleanup; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CODEC_DEVICE_CONTEXT, GetCodecDeviceContext) + +// +// Define DSP device context. +// +typedef struct _DSP_DEVICE_CONTEXT { + ACXCIRCUIT Speaker; + ACXCIRCUIT MicArray; + ACXCIRCUIT SpeakerHp; + ACXCIRCUIT MicrophoneHp; + ACXCIRCUIT HDMI; + WDF_TRI_STATE ExcludeD3Cold; +} DSP_DEVICE_CONTEXT, * PDSP_DEVICE_CONTEXT; + +// +// Dsp driver prototypes. +// +EVT_WDF_DRIVER_DEVICE_ADD Dsp_EvtBusDeviceAdd; +EVT_WDF_DRIVER_UNLOAD AudioDspDriverUnload; + +// +// Dsp device callbacks. +// +EVT_WDF_DEVICE_PREPARE_HARDWARE Dsp_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE Dsp_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY Dsp_EvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT Dsp_EvtDeviceD0Exit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP Dsp_EvtDeviceContextCleanup; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSP_DEVICE_CONTEXT, GetDspDeviceContext) + +// +// Define CODECMC (multicircuit codec) device context. +// +typedef struct _CODECMC_DEVICE_CONTEXT +{ + ACXCIRCUIT Render; + ACXCIRCUIT Capture; + ACXCOMPOSITETEMPLATE Composite[2]; + ULONG refComposite[2]; + WDF_TRI_STATE ExcludeD3Cold; +} CODECMC_DEVICE_CONTEXT, *PCODECMC_DEVICE_CONTEXT; + +// +// Multicircuit codec driver prototypes. +// +EVT_WDF_DRIVER_DEVICE_ADD CodecMc_EvtBusDeviceAdd; +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_UNLOAD AudioCodecMcDriverUnload; + +// +// Multicircuit codec device callbacks. +// +EVT_WDF_DEVICE_PREPARE_HARDWARE CodecMc_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE CodecMc_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY CodecMc_EvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT CodecMc_EvtDeviceD0Exit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP CodecMc_EvtDeviceContextCleanup; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CODECMC_DEVICE_CONTEXT, GetCodecMcDeviceContext) + +// +// Composite type definition used in multicircuit codec. +// +typedef enum +{ + CompositeType_RENDER, + CompositeType_CAPTURE +} CompositeType; + +// +// Define DSPMC (multicircuit dsp) device context. +// +typedef struct _DSPMC_DEVICE_CONTEXT +{ + ACXCIRCUIT Render; + ACXCIRCUIT Capture; + WDF_TRI_STATE ExcludeD3Cold; +} DSPMC_DEVICE_CONTEXT, *PDSPMC_DEVICE_CONTEXT; + +// +// Multicircuit dsp driver prototypes. +// +EVT_WDF_DRIVER_DEVICE_ADD DspMc_EvtBusDeviceAdd; +EVT_WDF_DRIVER_UNLOAD AudioDspMcDriverUnload; + +// +// Multicircuit dsp device callbacks. +// +EVT_WDF_DEVICE_PREPARE_HARDWARE DspMc_EvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE DspMc_EvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY DspMc_EvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT DspMc_EvtDeviceD0Exit; +EVT_WDF_DEVICE_CONTEXT_CLEANUP DspMc_EvtDeviceContextCleanup; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DSPMC_DEVICE_CONTEXT, GetDspMcDeviceContext) + +// Factory circuit callbacks for multicircuit dsp. +EVT_ACX_FACTORY_CIRCUIT_CREATE_CIRCUITDEVICE RenderMCDsp_EvtAcxFactoryCircuitCreateCircuitDevice; +EVT_ACX_FACTORY_CIRCUIT_CREATE_CIRCUIT RenderMCDsp_EvtAcxFactoryCircuitCreateCircuit; + +EVT_ACX_FACTORY_CIRCUIT_CREATE_CIRCUITDEVICE CaptureMCDsp_EvtAcxFactoryCircuitCreateCircuitDevice; +EVT_ACX_FACTORY_CIRCUIT_CREATE_CIRCUIT CaptureMCDsp_EvtAcxFactoryCircuitCreateCircuit; + + +/* make internal prototypes usable from C++ */ +#ifdef __cplusplus +} +#endif + +// Used to store the registry settings path for the driver: +extern UNICODE_STRING g_RegistryPath; + +// Driver tag name: +extern ULONG DeviceDriverTag; + +// The idle timeout in msec for power policy structure: +extern ULONG IdleTimeoutMsec; + +#define DECLARE_CONST_ACXOBJECTBAG_MULTICIRCUIT_SAMPLE_PROPERTY_NAME(name) \ + DECLARE_CONST_UNICODE_STRING(name, L"mc_" #name) + +__drv_requiresIRQL(PASSIVE_LEVEL) +PAGED_CODE_SEG +NTSTATUS +CopyRegistrySettingsPath( + _In_ PUNICODE_STRING RegistryPath +); + +PAGED_CODE_SEG +NTSTATUS +Codec_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +Dsp_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +CodecMc_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +DspMc_SetPowerPolicy( + _In_ WDFDEVICE Device +); + +PAGED_CODE_SEG +NTSTATUS +CodecR_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +CodecC_AddStaticCapture( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +Speaker_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ UNICODE_STRING CircuitName, + _In_ BOOLEAN IsHeadphones +); + +PAGED_CODE_SEG +NTSTATUS +MicArray_AddStaticCapture( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ GUID MicCustomName, + _In_ UNICODE_STRING CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +MicrophoneHp_AddStaticCapture( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ GUID MicCustomName, + _In_ UNICODE_STRING CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +SpeakerHp_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ UNICODE_STRING CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +HDMI_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ GUID ComponentGuid, + _In_ UNICODE_STRING CircuitName +); + +PAGED_CODE_SEG +NTSTATUS +RenderMC_AddStaticRender( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const UNICODE_STRING * CircuitName, + _In_ const UNICODE_STRING * Uri +); + +PAGED_CODE_SEG +NTSTATUS +CaptureMC_AddStaticCapture( + _In_ WDFDEVICE Device, + _In_ const GUID * ComponentGuid, + _In_ const GUID * MicCustomName, + _In_ const UNICODE_STRING * CircuitName, + _In_ const UNICODE_STRING * Uri +); + +PAGED_CODE_SEG +NTSTATUS +CodecC_CircuitCleanup( + _In_ ACXCIRCUIT Device +); + +PAGED_CODE_SEG +NTSTATUS +MicArray_CircuitCleanup( + _In_ ACXCIRCUIT Device +); + +PAGED_CODE_SEG +NTSTATUS +CaptureMCDsp_CircuitCleanup( + _In_ ACXCIRCUIT Device +); + +PAGED_CODE_SEG +NTSTATUS +DspMc_AddFactoryCircuit( + _In_ WDFDRIVER Driver, + _In_ WDFDEVICE Device +); + +NTSTATUS +CodecMc_AddRenderComposites(_In_ WDFDEVICE Device); + +PAGED_CODE_SEG +NTSTATUS +CodecMc_AddCaptureComposites(_In_ WDFDEVICE Device); + +PAGED_CODE_SEG +NTSTATUS +CodecMc_AddComposites(_In_ WDFDEVICE Device, _In_ CompositeType compositeType); + +NTSTATUS +CodecMc_RemoveComposites(_In_ WDFDEVICE Device); diff --git a/audio/Acx/Samples/Shared/Trace.h b/audio/Acx/Samples/Shared/Trace.h new file mode 100644 index 000000000..01478bfca --- /dev/null +++ b/audio/Acx/Samples/Shared/Trace.h @@ -0,0 +1,33 @@ +/*++ + +Copyright (c) Microsoft Corporation + +Module Name: + +Trace.h + +--*/ + +#pragma once + +#include +#include // For TRACE_LEVEL definitions + +#define WPP_TOTAL_BUFFER_SIZE (PAGE_SIZE) +#define WPP_ERROR_PARTITION_SIZE (WPP_TOTAL_BUFFER_SIZE/4) + +// {1945C417-844C-48C6-9BCE-3AA2113A2B69} +#define WPP_CONTROL_GUIDS \ +WPP_DEFINE_CONTROL_GUID(DrvLogger,(1945C417,844C,48C6,9BCE,3AA2113A2B69), \ + WPP_DEFINE_BIT(FLAG_DEVICE_ALL) /* bit 0 = 0x00000001 */ \ + WPP_DEFINE_BIT(FLAG_FUNCTION) /* bit 1 = 0x00000002 */ \ + WPP_DEFINE_BIT(FLAG_INFO) /* bit 2 = 0x00000004 */ \ + WPP_DEFINE_BIT(FLAG_PNP) /* bit 3 = 0x00000008 */ \ + WPP_DEFINE_BIT(FLAG_POWER) /* bit 4 = 0x00000010 */ \ + WPP_DEFINE_BIT(FLAG_STREAM) /* bit 5 = 0x00000020 */ \ + WPP_DEFINE_BIT(FLAG_INIT) /* bit 6 = 0x00000040 */ \ + WPP_DEFINE_BIT(FLAG_DDI) /* bit 7 = 0x00000080 */ \ + WPP_DEFINE_BIT(FLAG_GENERIC) /* bit 8 = 0x00000100 */ \ + ) + +#include "trace_macros.h" diff --git a/audio/simpleaudiosample/Source/Main/SimpleAudioSample.inx b/audio/simpleaudiosample/Source/Main/SimpleAudioSample.inx index a63bb0ba8..07a5593cb 100644 Binary files a/audio/simpleaudiosample/Source/Main/SimpleAudioSample.inx and b/audio/simpleaudiosample/Source/Main/SimpleAudioSample.inx differ diff --git a/audio/simpleaudiosample/Source/Main/adapter.cpp b/audio/simpleaudiosample/Source/Main/adapter.cpp index bbe23f26f..a66ee5a29 100644 --- a/audio/simpleaudiosample/Source/Main/adapter.cpp +++ b/audio/simpleaudiosample/Source/Main/adapter.cpp @@ -59,6 +59,8 @@ UNICODE_STRING g_RegistryPath; // This is used to store the registry settin #pragma code_seg("PAGE") void ReleaseRegistryStringBuffer() { + PAGED_CODE(); + if (g_RegistryPath.Buffer != NULL) { ExFreePool(g_RegistryPath.Buffer); diff --git a/audio/simpleaudiosample/Source/Main/common.cpp b/audio/simpleaudiosample/Source/Main/common.cpp index 8843d3a4d..457bdb17a 100644 --- a/audio/simpleaudiosample/Source/Main/common.cpp +++ b/audio/simpleaudiosample/Source/Main/common.cpp @@ -2547,6 +2547,7 @@ Return Value: return ntStatus; } +#pragma code_seg("PAGE") NTSTATUS CopyRegistryKey(HANDLE _hSourceKey, HANDLE _hDestinationKey, BOOL _bOverwrite = FALSE) /*++ @@ -2686,7 +2687,7 @@ Return Value: return ntStatus; } - +#pragma code_seg("PAGE") NTSTATUS CAdapterCommon::MigrateDeviceInterfaceTemplateParameters ( _In_ PUNICODE_STRING SymbolicLinkName, @@ -2729,6 +2730,8 @@ Return Value: UNICODE_STRING TemplateSymbolicLinkName; UNICODE_STRING referenceString; + PAGED_CODE(); + RtlInitUnicodeString(&TemplateSymbolicLinkName, NULL); RtlInitUnicodeString(&referenceString, TemplateReferenceString); diff --git a/audio/sysvad/APO/DelayAPO/DelayAPOMFX.cpp b/audio/sysvad/APO/DelayAPO/DelayAPOMFX.cpp index e7492131e..af67571b8 100644 --- a/audio/sysvad/APO/DelayAPO/DelayAPOMFX.cpp +++ b/audio/sysvad/APO/DelayAPO/DelayAPOMFX.cpp @@ -292,7 +292,7 @@ STDMETHODIMP CDelayAPOMFX::LockForProcess(UINT32 u32NumInputConnections, // // A more typical approach would be to allocate the memory using AERT_Allocate, which locks the memory // But for the purposes of this APO, CoTaskMemAlloc suffices, and the risk of glitches is not important - m_pf32DelayBuffer.Allocate(GetSamplesPerFrame() * m_nDelayFrames); + m_pf32DelayBuffer.Allocate((size_t) GetSamplesPerFrame() * m_nDelayFrames); WriteSilence(m_pf32DelayBuffer, m_nDelayFrames, GetSamplesPerFrame()); if (nullptr == m_pf32DelayBuffer) { @@ -1166,4 +1166,4 @@ HRESULT CDelayAPOMFX::CheckCustomFormats(IAudioMediaType *pRequestedFormat) } return hResult; -} \ No newline at end of file +} diff --git a/audio/sysvad/APO/DelayAPO/DelayAPOSFX.cpp b/audio/sysvad/APO/DelayAPO/DelayAPOSFX.cpp index c37abb7cd..67ae2788f 100644 --- a/audio/sysvad/APO/DelayAPO/DelayAPOSFX.cpp +++ b/audio/sysvad/APO/DelayAPO/DelayAPOSFX.cpp @@ -241,7 +241,7 @@ STDMETHODIMP CDelayAPOSFX::LockForProcess(UINT32 u32NumInputConnections, // // A more typical approach would be to allocate the memory using AERT_Allocate, which locks the memory // But for the purposes of this APO, CoTaskMemAlloc suffices, and the risk of glitches is not important - m_pf32DelayBuffer.Allocate(GetSamplesPerFrame() * m_nDelayFrames); + m_pf32DelayBuffer.Allocate((size_t) GetSamplesPerFrame() * m_nDelayFrames); WriteSilence(m_pf32DelayBuffer, m_nDelayFrames, GetSamplesPerFrame()); if (nullptr == m_pf32DelayBuffer) diff --git a/audio/sysvad/EndpointsCommon/MiniportAudioEngineNode.cpp b/audio/sysvad/EndpointsCommon/MiniportAudioEngineNode.cpp index 34477606e..8c3979f21 100644 --- a/audio/sysvad/EndpointsCommon/MiniportAudioEngineNode.cpp +++ b/audio/sysvad/EndpointsCommon/MiniportAudioEngineNode.cpp @@ -57,9 +57,9 @@ Called at PASSIVE_LEVEL } KSAUDIOENGINE_DESCRIPTOR, *PKSAUDIOENGINE_DESCRIPTOR; The fields are defined as: - nHostPinId – The ID of the pin factory connected to the audio engine node that is intended for host processed audio data. This is the pin factory on which a software audio engine will run. - nOffloadPinId – The ID of the pin factory connected to the audio engine node that is intended for offloaded streams. - nLoopbackPinId – The ID of the pin factory connected to the audio engine that is intended for supplying a post-mix loopback or reference stream. + nHostPinId - The ID of the pin factory connected to the audio engine node that is intended for host processed audio data. This is the pin factory on which a software audio engine will run. + nOffloadPinId - The ID of the pin factory connected to the audio engine node that is intended for offloaded streams. + nLoopbackPinId - The ID of the pin factory connected to the audio engine that is intended for supplying a post-mix loopback or reference stream. All pin ids need to be unique for each audio engine node. diff --git a/audio/sysvad/TabletAudioSample/ComponentizedApoSample.inx b/audio/sysvad/TabletAudioSample/ComponentizedApoSample.inx index 34b8401af..7c08f86a4 100644 Binary files a/audio/sysvad/TabletAudioSample/ComponentizedApoSample.inx and b/audio/sysvad/TabletAudioSample/ComponentizedApoSample.inx differ diff --git a/audio/sysvad/TabletAudioSample/ComponentizedAudioSample.inx b/audio/sysvad/TabletAudioSample/ComponentizedAudioSample.inx index 2f2f9638f..1c6382738 100644 Binary files a/audio/sysvad/TabletAudioSample/ComponentizedAudioSample.inx and b/audio/sysvad/TabletAudioSample/ComponentizedAudioSample.inx differ diff --git a/audio/sysvad/TabletAudioSample/ComponentizedAudioSampleExtension.inx b/audio/sysvad/TabletAudioSample/ComponentizedAudioSampleExtension.inx index 4afba2242..2ce2f6a09 100644 Binary files a/audio/sysvad/TabletAudioSample/ComponentizedAudioSampleExtension.inx and b/audio/sysvad/TabletAudioSample/ComponentizedAudioSampleExtension.inx differ diff --git a/audio/sysvad/TabletAudioSample/TabletAudioSample.vcxproj b/audio/sysvad/TabletAudioSample/TabletAudioSample.vcxproj index fe70dacf9..6e4e4c440 100644 --- a/audio/sysvad/TabletAudioSample/TabletAudioSample.vcxproj +++ b/audio/sysvad/TabletAudioSample/TabletAudioSample.vcxproj @@ -40,7 +40,7 @@ Windows10 False - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -64,7 +64,7 @@ Windows10 True - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -72,7 +72,7 @@ Windows10 False - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -80,7 +80,7 @@ Windows10 True - Windows Driver + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/avstream/avscamera/mft0/AvsCameraMft0.vcxproj b/avstream/avscamera/mft0/AvsCameraMft0.vcxproj index 518a324f4..f1c67d95a 100644 --- a/avstream/avscamera/mft0/AvsCameraMft0.vcxproj +++ b/avstream/avscamera/mft0/AvsCameraMft0.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -39,7 +39,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -47,7 +47,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -55,7 +55,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/avstream/avscamera/sys/AvsCamera.vcxproj b/avstream/avscamera/sys/AvsCamera.vcxproj index 5456ee7ac..74cada21f 100644 --- a/avstream/avscamera/sys/AvsCamera.vcxproj +++ b/avstream/avscamera/sys/AvsCamera.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -256,4 +256,4 @@ - + \ No newline at end of file diff --git a/avstream/avscamera/sys/AvsCamera.vcxproj.Filters b/avstream/avscamera/sys/AvsCamera.vcxproj.Filters index 8d9ec4698..1c346b6c2 100644 --- a/avstream/avscamera/sys/AvsCamera.vcxproj.Filters +++ b/avstream/avscamera/sys/AvsCamera.vcxproj.Filters @@ -1,4 +1,4 @@ - + @@ -97,10 +97,23 @@ Source Files + + Source Files + Resource Files + + + Header Files + + + + + Driver Files + + \ No newline at end of file diff --git a/avstream/avscamera/sys/Capture.cpp b/avstream/avscamera/sys/Capture.cpp index 25e6a5f88..730370e60 100644 --- a/avstream/avscamera/sys/Capture.cpp +++ b/avstream/avscamera/sys/Capture.cpp @@ -2294,6 +2294,7 @@ SetFramingSizes( PKSALLOCATOR_FRAMING_EX Framing ) { + PAGED_CODE(); Framing->FramingItem[0].PhysicalRange.MinFrameSize = m_VideoInfoHeader->bmiHeader.biSizeImage; Framing->FramingItem[0].PhysicalRange.MaxFrameSize = m_VideoInfoHeader->bmiHeader.biSizeImage; Framing->FramingItem[0].FramingRange.Range.MinFrameSize = m_VideoInfoHeader->bmiHeader.biSizeImage; diff --git a/avstream/avscamera/sys/Device.cpp b/avstream/avscamera/sys/Device.cpp index 2741da08e..38d4f555f 100644 --- a/avstream/avscamera/sys/Device.cpp +++ b/avstream/avscamera/sys/Device.cpp @@ -110,6 +110,7 @@ IrpSynchronousCompletion( IN PVOID pKevent ) { + PAGED_CODE(); if (Irp->PendingReturned) { NT_ASSERT(pKevent); diff --git a/avstream/avscamera/sys/avscamera.inx b/avstream/avscamera/sys/avscamera.inx index f6f1e8469..c4cee29bb 100644 Binary files a/avstream/avscamera/sys/avscamera.inx and b/avstream/avscamera/sys/avscamera.inx differ diff --git a/avstream/avscamera/sys/hwsim.cpp b/avstream/avscamera/sys/hwsim.cpp index fdf7b3673..80a4adcfc 100644 --- a/avstream/avscamera/sys/hwsim.cpp +++ b/avstream/avscamera/sys/hwsim.cpp @@ -796,6 +796,7 @@ bool CHardwareSimulation:: CheckForAvailableBuffer() { + PAGED_CODE(); return true; } @@ -803,6 +804,7 @@ NTSTATUS CHardwareSimulation:: CommitImageData(PSCATTER_GATHER_ENTRY sGEntry, ULONG stride) { + PAGED_CODE(); // Have the synthesizer output a frame to the buffer. ULONG CommitBufferSize = sGEntry->ByteCount; PUCHAR CommitBufferAddress = sGEntry->Virtual; @@ -818,6 +820,7 @@ NTSTATUS CHardwareSimulation:: ValidateBuffer(PSCATTER_GATHER_ENTRY sGEntry) { + PAGED_CODE(); return STATUS_SUCCESS; } diff --git a/avstream/avshws/avshws.inx b/avstream/avshws/avshws.inx index 238ce1878..9409635d3 100644 Binary files a/avstream/avshws/avshws.inx and b/avstream/avshws/avshws.inx differ diff --git a/avstream/avshws/avshws.vcxproj b/avstream/avshws/avshws.vcxproj index 407048b73..11fb4c396 100644 --- a/avstream/avshws/avshws.vcxproj +++ b/avstream/avshws/avshws.vcxproj @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -61,7 +61,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -69,7 +69,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -77,7 +77,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -85,7 +85,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -93,7 +93,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -101,7 +101,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/avstream/avshws/avshws.vcxproj.Filters b/avstream/avshws/avshws.vcxproj.Filters index 4e32a73fd..bc11045f2 100644 --- a/avstream/avshws/avshws.vcxproj.Filters +++ b/avstream/avshws/avshws.vcxproj.Filters @@ -1,4 +1,4 @@ - + @@ -43,4 +43,14 @@ Resource Files + + + Header Files + + + + + Driver Files + + \ No newline at end of file diff --git a/avstream/avssamp/avssamp.inx b/avstream/avssamp/avssamp.inx index 61d66fa37..c06925ea3 100644 Binary files a/avstream/avssamp/avssamp.inx and b/avstream/avssamp/avssamp.inx differ diff --git a/avstream/avssamp/avssamp.vcxproj b/avstream/avssamp/avssamp.vcxproj index 58d7992df..dfe36af75 100644 --- a/avstream/avssamp/avssamp.vcxproj +++ b/avstream/avssamp/avssamp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/avstream/avssamp/avssamp.vcxproj.Filters b/avstream/avssamp/avssamp.vcxproj.Filters index 8d3458319..5a9d5e00b 100644 --- a/avstream/avssamp/avssamp.vcxproj.Filters +++ b/avstream/avssamp/avssamp.vcxproj.Filters @@ -1,4 +1,4 @@ - + @@ -53,24 +53,6 @@ Header Files - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - diff --git a/avstream/sampledevicemft/basepin.cpp b/avstream/sampledevicemft/basepin.cpp index 563ff610a..471bbca7d 100644 --- a/avstream/sampledevicemft/basepin.cpp +++ b/avstream/sampledevicemft/basepin.cpp @@ -37,12 +37,6 @@ CBasePin::CBasePin( _In_ ULONG id, _In_ CMultipinMft *parent) : CBasePin::~CBasePin() { - - for ( ULONG ulIndex = 0, ulSize = (ULONG)m_listOfMediaTypes.size(); ulIndex < ulSize; ulIndex++ ) - { - ComPtr spMediaType; - spMediaType.Attach(m_listOfMediaTypes[ulIndex]); // Releases the previously stored pointer - } m_listOfMediaTypes.clear(); m_spAttributes = nullptr; } @@ -68,7 +62,6 @@ HRESULT CBasePin::AddMediaType( _Inout_ DWORD *pos, _In_ IMFMediaType *pMediaTyp m_listOfMediaTypes.push_back(pMediaType); }); DMFTCHECKHR_GOTO(hr, done); - pMediaType->AddRef(); if (pos) { *pos = (DWORD)(m_listOfMediaTypes.size() - 1); @@ -89,7 +82,8 @@ HRESULT CBasePin::GetMediaTypeAt( _In_ DWORD pos, _Outptr_result_maybenull_ IMFM { DMFTCHECKHR_GOTO(MF_E_NO_MORE_TYPES,done); } - spMediaType = m_listOfMediaTypes[pos]; + DMFTCHECKHR_GOTO(MFCreateMediaType(spMediaType.GetAddressOf()), done); + DMFTCHECKHR_GOTO(m_listOfMediaTypes[pos]->CopyAllItems(spMediaType.Get()), done); *ppMediaType = spMediaType.Detach(); done: return hr; @@ -129,8 +123,10 @@ STDMETHODIMP_(BOOL) CBasePin::IsMediaTypeSupported { bFound = TRUE; if (ppIMFMediaTypeFull) { - *ppIMFMediaTypeFull = m_listOfMediaTypes[uIIndex]; - (*ppIMFMediaTypeFull)->AddRef(); + ComPtr spMediaType; + DMFTCHECKHR_GOTO(MFCreateMediaType(spMediaType.GetAddressOf()), done); + DMFTCHECKHR_GOTO(m_listOfMediaTypes[uIIndex]->CopyAllItems(spMediaType.Get()), done); + *ppIMFMediaTypeFull = spMediaType.Detach(); } break; } @@ -219,7 +215,7 @@ CInPin::~CInPin() } STDMETHODIMP CInPin::Init( - _In_ IMFTransform* pTransform + _In_ IMFDeviceTransform* pTransform ) { @@ -239,7 +235,7 @@ STDMETHODIMP CInPin::Init( m_waitInputMediaTypeWaiter = CreateEvent( NULL, FALSE, FALSE, - TEXT("MediaTypeWaiter") + nullptr ); DMFTCHECKNULL_GOTO( m_waitInputMediaTypeWaiter, done, E_OUTOFMEMORY ); @@ -275,7 +271,7 @@ HRESULT CInPin::GenerateMFMediaTypeListFromDevice( ComPtr spMediaType; DWORD pos = 0; - hr = m_spSourceTransform->MFTGetOutputAvailableType(uiStreamId, iMediaType, spMediaType.GetAddressOf()); + hr = m_spSourceTransform->GetOutputAvailableType(uiStreamId, iMediaType, spMediaType.GetAddressOf()); if (hr != S_OK) break; @@ -813,11 +809,6 @@ STDMETHODIMP CTranslateOutPin::AddMediaType( DMFTCHECKHR_GOTO(pMediaType->GetGUID(MF_MT_SUBTYPE, &guidSubType), done); // @@@@ README the below lines show how to exclude mediatypes which we don't want - /* if ((guidSubType != MFVideoFormat_H264)) - { - hr = S_FALSE; - goto done; - }*/ if (needTranslation(pMediaType)) { @@ -829,9 +820,21 @@ STDMETHODIMP CTranslateOutPin::AddMediaType( DMFTCHECKHR_GOTO(MFCalculateImageSize(translatedGUID, uiWidth, uiHeight, &uiImageSize), done); DMFTCHECKHR_GOTO(pNewMediaType->SetGUID(MF_MT_SUBTYPE, translatedGUID), done); DMFTCHECKHR_GOTO(pNewMediaType->SetUINT32(MF_MT_SAMPLE_SIZE, uiImageSize), done); + + (void)pNewMediaType->DeleteItem(MF_MT_COMPRESSED); + (void)pNewMediaType->DeleteItem(MF_MT_SAMPLE_SIZE); + (void)pNewMediaType->DeleteItem(MF_MT_AVG_BITRATE); + (void)pNewMediaType->DeleteItem(MF_MT_MPEG2_PROFILE); + (void)pNewMediaType->DeleteItem(MF_MT_MPEG2_LEVEL); + + (void)pNewMediaType->DeleteItem(MF_MT_VIDEO_ROTATION); + (void)pNewMediaType->DeleteItem(MF_MT_MINIMUM_DISPLAY_APERTURE); + + DMFTCHECKHR_GOTO(pNewMediaType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), done); + DMFTCHECKHR_GOTO(pNewMediaType->SetUINT32(MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_0_255), done); hr = ExceptionBoundary([&]() { - m_TranslatedMediaTypes.insert(std::pair( pNewMediaType.Get(), pMediaType)); + m_TranslatedMediaTypes.insert(std::pair, ComPtr>( pNewMediaType.Get(), pMediaType)); }); DMFTCHECKHR_GOTO(hr, done); } @@ -858,18 +861,22 @@ STDMETHODIMP_(BOOL) CTranslateOutPin::IsMediaTypeSupported( { DWORD dwFlags = 0, dwMatchedFlags = (MF_MEDIATYPE_EQUAL_MAJOR_TYPES | MF_MEDIATYPE_EQUAL_FORMAT_TYPES | MF_MEDIATYPE_EQUAL_FORMAT_DATA); - std::map::iterator found = std::find_if(m_TranslatedMediaTypes.begin(), m_TranslatedMediaTypes.end(), - [&](std::pair p) + auto found = std::find_if(m_TranslatedMediaTypes.begin(), m_TranslatedMediaTypes.end(), + [&](std::pair, ComPtr> p) { - return (SUCCEEDED(pMediaType->IsEqual(p.first, &dwFlags)) + return (SUCCEEDED(pMediaType->IsEqual(p.first.Get(), &dwFlags)) && ((dwFlags & dwMatchedFlags) == (dwMatchedFlags))); }); if (found != m_TranslatedMediaTypes.end()) { - ComPtr spMediaType = (*found).second; + ComPtr spMediaType; if (ppIMFMediaTypeFull) { + if (FAILED(MFCreateMediaType(spMediaType.GetAddressOf()))|| FAILED((*found).second->CopyAllItems(spMediaType.Get()))) + { + return false; + } *ppIMFMediaTypeFull = spMediaType.Detach(); } return true; diff --git a/avstream/sampledevicemft/basepin.h b/avstream/sampledevicemft/basepin.h index cce17d0bd..d3e45c938 100644 --- a/avstream/sampledevicemft/basepin.h +++ b/avstream/sampledevicemft/basepin.h @@ -458,10 +458,10 @@ class CBasePin: class CInPin: public CBasePin{ public: CInPin( _In_opt_ IMFAttributes*, _In_ ULONG ulPinId = 0, _In_ CMultipinMft *pParent=NULL); - ~CInPin(); + virtual ~CInPin(); STDMETHOD ( Init )( - _In_ IMFTransform * + _In_ IMFDeviceTransform * ); STDMETHOD_( VOID, ConnectPin)( _In_ CBasePin * @@ -514,7 +514,7 @@ class CInPin: public CBasePin{ STDMETHOD_( VOID, ShutdownPin)(); protected: - ComPtr m_spSourceTransform; /*Source Transform i.e. DevProxy*/ + ComPtr m_spSourceTransform; /*Source Transform i.e. DevProxy*/ GUID m_stStreamType; /*GUID representing the GUID*/ ComPtr m_outpin; //Only one output pin connected per input pin. There can be multiple pins connected and this could be a list DeviceStreamState m_preferredStreamState; @@ -541,7 +541,7 @@ class COutPin: public CBasePin{ , _In_ MFSampleAllocatorUsage allocatorUsage = MFSampleAllocatorUsage_DoesNotAllocate #endif ); - ~COutPin(); + virtual ~COutPin(); STDMETHODIMP FlushQueues(); STDMETHODIMP AddPin( _In_ DWORD pinId @@ -619,7 +619,7 @@ class CAsyncInPin: public CInPin { Init(); } STDMETHOD_(VOID, ShutdownPin)(); - ~CAsyncInPin() + virtual ~CAsyncInPin() { FlushQueues(); } @@ -663,10 +663,10 @@ class CTranslateOutPin : public COutPin { _In_ IMFMediaType *pInMediatype, _In_ IMFMediaType* pOutMediaType, _In_ DeviceStreamState state); - + virtual ~CTranslateOutPin() {} protected: - map m_TranslatedMediaTypes; + map, ComPtr> m_TranslatedMediaTypes; }; diff --git a/avstream/sampledevicemft/common.h b/avstream/sampledevicemft/common.h index bc6bbf28b..57126378f 100644 --- a/avstream/sampledevicemft/common.h +++ b/avstream/sampledevicemft/common.h @@ -230,9 +230,9 @@ typedef enum _DMFT_conversion_type{ DeviceMftTransformTypeIllegal // We cannot satisfy the input and output combination }DMFT_conversion_type,*PDMFT_conversion_type; -typedef std::vector< IMFMediaType *> IMFMediaTypeArray; -typedef std::vector< CBasePin *> CBasePinArray; -typedef std::vector< IMFSample *> IMFSampleList; +typedef std::vector > IMFMediaTypeArray; +typedef std::vector > CBasePinArray; +typedef std::vector > IMFSampleList; typedef std::pair< std::multimap::iterator, std::multimap::iterator > MMFTMMAPITERATOR; diff --git a/avstream/sampledevicemft/multipinmft.cpp b/avstream/sampledevicemft/multipinmft.cpp index 30c0463fe..b171338aa 100644 --- a/avstream/sampledevicemft/multipinmft.cpp +++ b/avstream/sampledevicemft/multipinmft.cpp @@ -54,21 +54,10 @@ CMultipinMft::CMultipinMft() CMultipinMft::~CMultipinMft( ) { - - - for ( ULONG ulIndex = 0, ulSize = (ULONG) m_InPins.size(); ulIndex < ulSize; ulIndex++ ) - { - SAFERELEASE(m_InPins[ ulIndex ]); - } m_InPins.clear(); - for (ULONG ulIndex = 0, ulSize = (ULONG) m_OutPins.size(); ulIndex < ulSize; ulIndex++) - { - SAFERELEASE(m_OutPins[ ulIndex ]); - } m_OutPins.clear(); SAFE_ARRAYDELETE(m_SymbolicLink); m_spSourceTransform = nullptr; - } STDMETHODIMP_(ULONG) CMultipinMft::AddRef( @@ -205,7 +194,7 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( DMFTCHECKHR_GOTO( m_spSourceTransform.As( &m_spIkscontrol ), done ); - DMFTCHECKHR_GOTO( m_spSourceTransform->MFTGetStreamCount( &inputStreams, &outputStreams ), done ); + DMFTCHECKHR_GOTO( m_spSourceTransform->GetStreamCount( &inputStreams, &outputStreams ), done ); spFilterUnk = nullptr; @@ -222,7 +211,7 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( pcOutputStreams = new (std::nothrow) DWORD[ outputStreams ]; DMFTCHECKNULL_GOTO( pcOutputStreams, done, E_OUTOFMEMORY ); - DMFTCHECKHR_GOTO( m_spSourceTransform->MFTGetStreamIDs( inputStreams, pcInputStreams, + DMFTCHECKHR_GOTO( m_spSourceTransform->GetStreamIDs( inputStreams, pcInputStreams, outputStreams, pcOutputStreams ),done ); @@ -252,7 +241,6 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( }); DMFTCHECKHR_GOTO(hr, done); DMFTCHECKHR_GOTO( spInPin->Init(m_spSourceTransform.Get() ), done); - spInPin.Detach(); } // @@ -263,7 +251,7 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( ComPtr spoPin; BOOL bCustom = FALSE; - ComPtr spiPin = ( CInPin * )m_InPins[ ulIndex ]; + ComPtr spiPin = ( CInPin * )m_InPins[ ulIndex ].Get(); if (spiPin.Get()) { @@ -292,7 +280,6 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( { m_OutPins.push_back(spoPin.Get()); }), done); - spoPin.Detach(); ulOutPinIndex++; hr = S_OK; } @@ -329,15 +316,7 @@ STDMETHODIMP CMultipinMft::InitializeTransform ( if ( FAILED( hr ) ) { //Release the pins and the resources acquired - for (ULONG ulIndex = 0, ulSize = (ULONG)m_InPins.size(); ulIndex < ulSize; ulIndex++) - { - SAFERELEASE(m_InPins[ulIndex]); - } m_InPins.clear(); - for (ULONG ulIndex = 0, ulSize = (ULONG)m_OutPins.size(); ulIndex < ulSize; ulIndex++) - { - SAFERELEASE(m_OutPins[ulIndex]); - } m_OutPins.clear(); // // Simply clear the custom pins since the input pins must have deleted the pin @@ -461,7 +440,7 @@ STDMETHODIMP CMultipinMft::GetInputAvailableType( ) { HRESULT hr = S_OK; - + CAutoLock lock(m_critSec); ComPtr spiPin = GetInPin( dwInputStreamID ); DMFTCHECKNULL_GOTO(ppMediaType, done, E_INVALIDARG); DMFTCHECKNULL_GOTO( spiPin, done, MF_E_INVALIDSTREAMNUMBER ); @@ -721,7 +700,7 @@ STDMETHODIMP CMultipinMft::ProcessInput( { HRESULT hr = S_OK; UNREFERENCED_PARAMETER( dwFlags ); - + CAutoLock lock(m_critSec); ComPtr spInPin = GetInPin( dwInputStreamID ); DMFTCHECKNULL_GOTO(spInPin, done, MF_E_INVALIDSTREAMNUMBER); @@ -762,6 +741,7 @@ output pins and populate the corresponding MFT_OUTPUT_DATA_BUFFER with the sampl HRESULT hr = S_OK; BOOL gotOne = false; ComPtr spOpin; + CAutoLock _lock(m_critSec); UNREFERENCED_PARAMETER( dwFlags ); if (cOutputBufferCount > m_OutputPinCount ) @@ -774,7 +754,6 @@ output pins and populate the corresponding MFT_OUTPUT_DATA_BUFFER with the sampl { DWORD dwStreamID = pOutputSamples[i].dwStreamID; { - CAutoLock _lock(m_critSec); spOpin = nullptr; spOpin = GetOutPin(dwStreamID); GUID pinGuid = GUID_NULL; @@ -828,7 +807,7 @@ STDMETHODIMP CMultipinMft::GetInputStreamAttributes( { HRESULT hr = S_OK; ComPtr spIPin; - + CAutoLock Lock(m_critSec); DMFTCHECKNULL_GOTO( ppAttributes, done, E_INVALIDARG ); *ppAttributes = nullptr; @@ -857,7 +836,7 @@ STDMETHODIMP CMultipinMft::GetOutputStreamAttributes( { HRESULT hr = S_OK; ComPtr spoPin; - + CAutoLock Lock(m_critSec); DMFTCHECKNULL_GOTO(ppAttributes, done, E_INVALIDARG); *ppAttributes = nullptr; @@ -893,6 +872,7 @@ STDMETHODIMP CMultipinMft::SetInputStreamState( --*/ { HRESULT hr = S_OK; + CAutoLock Lock(m_critSec); ComPtr spiPin = GetInPin(dwStreamID); DMFTCHECKNULL_GOTO(spiPin, done, MF_E_INVALIDSTREAMNUMBER); @@ -909,6 +889,7 @@ STDMETHODIMP CMultipinMft::GetInputStreamState( ) { HRESULT hr = S_OK; + CAutoLock Lock(m_critSec); ComPtr piPin = GetInPin(dwStreamID); DMFTCHECKNULL_GOTO(piPin, done, MF_E_INVALIDSTREAMNUMBER); @@ -994,6 +975,7 @@ STDMETHODIMP CMultipinMft::GetInputStreamPreferredState( --*/ { HRESULT hr = S_OK; + CAutoLock lock(m_critSec); ComPtr spiPin = GetInPin(dwStreamID); DMFTCHECKNULL_GOTO(ppMediaType, done, E_INVALIDARG); DMFTCHECKNULL_GOTO(spiPin, done, MF_E_INVALIDSTREAMNUMBER); @@ -1061,7 +1043,7 @@ STDMETHODIMP_(VOID) CMultipinMft::FlushAllStreams( CAutoLock Lock(m_critSec); for ( DWORD dwIndex = 0, dwSize = (DWORD)m_OutPins.size(); dwIndex < dwSize; dwIndex++ ) { - ComPtr spoPin = (COutPin *)m_OutPins[dwIndex]; + ComPtr spoPin = (COutPin *)m_OutPins[dwIndex].Get(); oldState = spoPin->SetState(DeviceStreamState_Disabled); spoPin->FlushQueues(); // @@ -1391,7 +1373,7 @@ CInPin* CMultipinMft::GetInPin( CInPin *inPin = NULL; for (DWORD dwIndex = 0, dwSize = (DWORD)m_InPins.size(); dwIndex < dwSize; dwIndex++) { - inPin = (CInPin *)m_InPins[dwIndex]; + inPin = (CInPin *)m_InPins[dwIndex].Get(); if (dwStreamId == inPin->streamId()) { break; @@ -1408,7 +1390,7 @@ COutPin* CMultipinMft::GetOutPin( COutPin *outPin = NULL; for ( DWORD dwIndex = 0, dwSize = (DWORD) m_OutPins.size(); dwIndex < dwSize; dwIndex++ ) { - outPin = ( COutPin * )m_OutPins[ dwIndex ]; + outPin = ( COutPin * )m_OutPins[ dwIndex ].Get(); if ( dwStreamId == outPin->streamId() ) { @@ -1509,7 +1491,10 @@ HRESULT CMultipinMft::ChangeMediaTypeEx( // // The media type will be set on the input pin by the time we return from the wait // - DMFTCHECKHR_GOTO(spinPin->WaitForSetInputPinMediaChange(), done); + m_critSec.Unlock(); + hr = spinPin->WaitForSetInputPinMediaChange(); + m_critSec.Lock(); + DMFTCHECKHR_GOTO(hr, done); // Change the media type on the output.. DMFTCHECKHR_GOTO(spoPin->ChangeMediaTypeFromInpin(pFullType.Get(), pMediaType , reqState), done); // @@ -1728,10 +1713,8 @@ STDMETHODIMP CMultipinMft::Shutdown( for (ULONG ulIndex = 0, ulSize = (ULONG)m_InPins.size(); ulIndex < ulSize; ulIndex++ ) { - CInPin *pInPin = static_cast(m_InPins[ulIndex]); - // Deref on the connected outpins to break reference loop - (VOID)pInPin->ShutdownPin(); + (VOID)((CInPin*)m_InPins[ulIndex].Get())->ShutdownPin(); } #if defined (MF_DEVICEMFT_ALLOW_MFT0_LOAD) && defined (MFT_UNIQUE_METHOD_NAMES) for (ULONG ulIndex = 0, ulSize = (ULONG)m_OutPins.size(); ulIndex < ulSize; ulIndex++) @@ -1833,7 +1816,7 @@ HRESULT CMultipinMft::SetStreamingStateCustomPins( for (ULONG ulIndex = 0; ulIndex < m_InPins.size(); ulIndex++) { BOOL isCustom = false; - CInPin* pInPin = static_cast(m_InPins[ulIndex]); + CInPin* pInPin = static_cast(m_InPins[ulIndex].Get()); if ( SUCCEEDED( CheckCustomPin(pInPin, &isCustom) ) && ( isCustom ) ) diff --git a/avstream/sampledevicemft/multipinmft.h b/avstream/sampledevicemft/multipinmft.h index 70367f1d9..be86d66bb 100644 --- a/avstream/sampledevicemft/multipinmft.h +++ b/avstream/sampledevicemft/multipinmft.h @@ -377,7 +377,7 @@ class CMultipinMft : //Inline functions // - __inline IMFTransform* Parent() + __inline IMFDeviceTransform* Parent() { return m_spSourceTransform.Get(); } @@ -406,7 +406,7 @@ class CMultipinMft : long m_nRefCount; // Reference count CCritSec m_critSec; // Control lock.. taken only durign state change operations ComPtr m_spDeviceManagerUnk; // D3D Manager set, when MFT_MESSAGE_SET_D3D_MANAGER is called through ProcessMessage - ComPtr m_spSourceTransform; // The sources transform. This is the pipeline DevProxy + ComPtr m_spSourceTransform; // The sources transform. This is the pipeline DevProxy MFSHUTDOWN_STATUS m_eShutdownStatus; DWORD m_dwWorkQueueId; LONG m_lWorkQueuePriority; diff --git a/avstream/sampledevicemft/multipinmft.vcxproj b/avstream/sampledevicemft/multipinmft.vcxproj index f13ed67d6..152ff207e 100644 --- a/avstream/sampledevicemft/multipinmft.vcxproj +++ b/avstream/sampledevicemft/multipinmft.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -189,7 +189,7 @@ %(PreprocessorDefinitions);UNICODE;MF_WPP;SECURITY_WIN32;MFT_UNIQUE_METHOD_NAMES;MF_DEVICEMFT_ALLOW_MFT0_LOAD - %(AdditionalDependencies);D2d1.lib;mf.lib;mfplat.lib;mfuuid.lib;uuid.lib + onecore.lib;D2d1.lib;mfcore.lib;mfplat.lib;mfuuid.lib;uuid.lib Source.def @@ -204,7 +204,7 @@ %(PreprocessorDefinitions);UNICODE;MF_WPP;SECURITY_WIN32;MFT_UNIQUE_METHOD_NAMES;MF_DEVICEMFT_ALLOW_MFT0_LOAD - %(AdditionalDependencies);D2d1.lib;mf.lib;mfplat.lib;mfuuid.lib;uuid.lib + onecore.lib;D2d1.lib;mfcore.lib;mfplat.lib;mfuuid.lib;uuid.lib Source.def @@ -219,7 +219,7 @@ %(PreprocessorDefinitions);UNICODE;MF_WPP;SECURITY_WIN32;MFT_UNIQUE_METHOD_NAMES;MF_DEVICEMFT_ALLOW_MFT0_LOAD - %(AdditionalDependencies);D2d1.lib;mf.lib;mfplat.lib;mfuuid.lib;uuid.lib + onecore.lib;D2d1.lib;mfcore.lib;mfplat.lib;mfuuid.lib;uuid.lib Source.def @@ -234,7 +234,7 @@ %(PreprocessorDefinitions);UNICODE;MF_WPP;SECURITY_WIN32;MFT_UNIQUE_METHOD_NAMES;MF_DEVICEMFT_ALLOW_MFT0_LOAD - %(AdditionalDependencies);D2d1.lib;mf.lib;mfplat.lib;mfuuid.lib;uuid.lib + onecore.lib;D2d1.lib;mfcore.lib;mfplat.lib;mfuuid.lib;uuid.lib Source.def diff --git a/avstream/sampledevicemft/multipinmfthelpers.cpp b/avstream/sampledevicemft/multipinmfthelpers.cpp index 34cebe8bf..0d720c3d6 100644 --- a/avstream/sampledevicemft/multipinmfthelpers.cpp +++ b/avstream/sampledevicemft/multipinmfthelpers.cpp @@ -38,7 +38,6 @@ CPinQueue::~CPinQueue( ) --*/ STDMETHODIMP_(VOID) CPinQueue::InsertInternal( _In_ IMFSample *pSample ) { - pSample->AddRef(); HRESULT hr = ExceptionBoundary([&]() { m_sampleList.push_back(pSample); @@ -52,8 +51,6 @@ STDMETHODIMP_(VOID) CPinQueue::InsertInternal( _In_ IMFSample *pSample ) if (FAILED(hr)) { DMFTRACE(DMFT_GENERAL, TRACE_LEVEL_INFORMATION, "%!FUNC! exiting %x = %!HRESULT!", hr, hr); - // There is a bug in the pipeline that doesn't release the sample fed from processinput. We have to explicitly release the sample here - SAFE_RELEASE(pSample); } } @@ -78,7 +75,7 @@ STDMETHODIMP CPinQueue::Remove( _Outptr_result_maybenull_ IMFSample **ppSample) if ( !m_sampleList.empty() ) { - *ppSample = m_sampleList.front(); + *ppSample = m_sampleList.front().Detach(); } DMFTCHECKNULL_GOTO( *ppSample, done, MF_E_TRANSFORM_NEED_MORE_INPUT ); @@ -177,33 +174,31 @@ STDMETHODIMP CPinQueue::RecreateTeeByAllocatorMode( Ctee::ReleaseTee(m_spTeer);// Should release the reference - wistd::unique_ptr nulltee = wil::make_unique_nothrow(this); - RETURN_IF_NULL_ALLOC(nulltee); + ComPtr spNulltee = new (std::nothrow) CNullTee(this); + DMFTCHECKNULL_GOTO(spNulltee.Get(), done, E_OUTOFMEMORY); if (allocatorUsage == MFSampleAllocatorUsage_DoesNotAllocate) { - m_spTeer.Attach(nulltee.release()); /*A simple passthrough*/ + m_spTeer = spNulltee.Get(); } else { - wistd::unique_ptr sampleCopytee; - RETURN_IF_NULL_ALLOC(sampleCopytee); - (void)sampleCopytee->SetD3DManager(punkManager); - + ComPtr spSampleCopytee; if (allocatorUsage == MFSampleAllocatorUsage_UsesProvidedAllocator) { RETURN_HR_IF_NULL(E_INVALIDARG, pAllocator); - sampleCopytee = wil::make_unique_nothrow(nulltee.release(), pinCategory(), pAllocator); + spSampleCopytee = new (std::nothrow) CSampleCopytee(spNulltee.Get(), pinCategory(), pAllocator); } else { - sampleCopytee = wil::make_unique_nothrow(nulltee.release(), pinCategory(), nullptr); + spSampleCopytee = new (std::nothrow) CSampleCopytee(spNulltee.Get(), pinCategory(), nullptr); } - - RETURN_IF_FAILED(sampleCopytee->SetMediaTypes(inMediatype, outMediatype)); - m_spTeer.Attach(sampleCopytee.release()); + DMFTCHECKNULL_GOTO(spSampleCopytee.Get(), done, E_OUTOFMEMORY); + (void)spSampleCopytee->SetD3DManager(punkManager); + RETURN_IF_FAILED(spSampleCopytee->SetMediaTypes(inMediatype, outMediatype)); + m_spTeer = spSampleCopytee.Get(); } - +done: return hr; } #endif // ((defined NTDDI_WIN10_VB) && (NTDDI_VERSION >= NTDDI_WIN10_VB)) @@ -283,28 +278,13 @@ this path traversed. This function feeds the sample to the XVP or the decoding T STDMETHODIMP CWrapTee::PassThrough( _In_ IMFSample* pInSample ) { HRESULT hr = S_OK; - IMFSample* pOutSample = nullptr; - bool newSample = false; + ComPtr spOutSample = nullptr; DMFTCHECKNULL_GOTO(pInSample, done, S_OK); // pass through for no sample - DMFTCHECKHR_GOTO(Do(pInSample, &pOutSample,newSample),done); + DMFTCHECKHR_GOTO(Do(pInSample, spOutSample.ReleaseAndGetAddressOf()), done); if (m_spObjectWrapped) { - if (SUCCEEDED(hr = m_spObjectWrapped->PassThrough( pOutSample ))) - { - //@@@@README There is a very bad bug in the pipeline that the device transform manager - // is not releasing the reference on the sample when it is passed to the device MFT so any - // sample produced has to be referenced matched in the deviceMFT so that the net reference remains one - // This goes against the ownership rules in Com, but this bug has existed in the pipeline so far, - // so until we rev the interface we will have to live with it - // - if (newSample) - { - // If we produce the sample, then we have to release the sample - SAFE_RELEASE(pOutSample); - } - } - + DMFTCHECKHR_GOTO(m_spObjectWrapped->PassThrough(spOutSample.Get()), done); } done: @@ -326,7 +306,7 @@ HRESULT CVideoProcTee::SetMediaTypes(_In_ IMFMediaType* pInMediaType, _In_ IMFMe ComPtr spTransform; DMFTCHECKHR_GOTO(CWrapTee::SetMediaTypes(pInMediaType, pOutMediaType),done); DMFTCHECKHR_GOTO(Configure(pInMediaType, pOutMediaType, spTransform.GetAddressOf()), done); - m_spVideoProcessor = spTransform.Detach(); + m_spVideoProcessor = spTransform; // // Start streaming // @@ -380,6 +360,15 @@ HRESULT CVideoProcTee::CreateAllocator() return hr; } +CVideoProcTee::~CVideoProcTee() +{ + if (m_spPrivateAllocator.Get()) + { + (VOID)m_spPrivateAllocator->UninitializeSampleAllocator(); + m_spPrivateAllocator = nullptr; + } +} + // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@// // @@@@ README: Video Processor functions below // @@ -412,10 +401,9 @@ HRESULT CXvptee::StopStreaming() HRESULT hr = S_OK; CAutoLock Lock(m_Lock); SetAsyncStatus(MF_E_SHUTDOWN); - DMFTCHECKHR_GOTO(Transform()->MFTProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0), done); // Flush the stream - DMFTCHECKHR_GOTO(Transform()->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), done); // Notify end of stream - DMFTCHECKHR_GOTO(Transform()->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0), done); // Notify end of streaming -done: + Transform()->MFTProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); // Flush the stream + Transform()->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0); // Notify end of stream + Transform()->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0); // Notify end of streaming return hr; } @@ -429,7 +417,7 @@ outpin should be in Open state for the sample to reach the XVP and consequetivel Output Pin. --*/ -STDMETHODIMP CXvptee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample, _Inout_ bool &newSample) +STDMETHODIMP CXvptee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample) { HRESULT hr = S_OK; MFT_OUTPUT_DATA_BUFFER outputSample; @@ -474,7 +462,6 @@ STDMETHODIMP CXvptee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSamp if (spXVPOutputSample.Get()) { - newSample = true; *ppOutSample = spXVPOutputSample.Detach(); } done: @@ -554,11 +541,6 @@ CDecoderTee::~CDecoderTee() { (VOID)StopStreaming(); MFUnlockWorkQueue(m_dwCameraStreamWorkQueueId); - if (m_spPrivateAllocator) - { - m_spPrivateAllocator->UninitializeSampleAllocator(); - m_spPrivateAllocator = nullptr; - } } HRESULT CDecoderTee::StartStreaming() @@ -584,9 +566,9 @@ HRESULT CDecoderTee::StopStreaming() if (spTransform.Get()) { ComPtr spShutdown; - DMFTCHECKHR_GOTO(spTransform->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, m_dwMFTInputId), done); - DMFTCHECKHR_GOTO(spTransform->MFTProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0), done); - DMFTCHECKHR_GOTO(spTransform->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0), done); + spTransform->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, m_dwMFTInputId); + spTransform->MFTProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); + spTransform->MFTProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0); // Shut it down if (SUCCEEDED(spTransform->QueryInterface(IID_PPV_ARGS(&spShutdown)))) { @@ -595,7 +577,6 @@ HRESULT CDecoderTee::StopStreaming() spTransform = nullptr; } -done: return hr; } @@ -675,14 +656,13 @@ STDMETHODIMP CDecoderTee::Configure(_In_opt_ IMFMediaType *inType, } -STDMETHODIMP CDecoderTee::Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **ppoutSample, _Inout_ bool &newSample) +STDMETHODIMP CDecoderTee::Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **ppoutSample) { HRESULT hr = S_OK; ComPtr spOutputSample; CAutoLock lock(m_Lock); ComPtr spTransform = Transform(); - newSample = false; DMFTCHECKNULL_GOTO(ppoutSample, done, E_INVALIDARG); *ppoutSample = nullptr; DMFTCHECKHR_GOTO(GetAsyncStatus(), done); @@ -983,6 +963,7 @@ HRESULT CDecoderTee::ConfigDecoder(_In_ IMFTransform* pTransform, _In_ GUID guid GUID guidMajorType; GUID guidSubtype; DWORD dwMediaTypeIndex = 0; + DWORD dwFlags = 0; ComPtr spDxgiManager; UNREFERENCED_PARAMETER(guidSubType); DMFTCHECKNULL_GOTO(pTransform, done, E_INVALIDARG); @@ -1050,6 +1031,18 @@ HRESULT CDecoderTee::ConfigDecoder(_In_ IMFTransform* pTransform, _In_ GUID guid // Try to set output type on the MJPG decoder. DMFTCHECKHR_GOTO(pTransform->MFTSetOutputType(m_dwMFTOutputId, spMediaType.Get(), 0), done); + if (S_OK != (spMediaType->IsEqual(m_pOutputMediaType.Get(), &dwFlags))) + { + ComPtr spXvpTee = new (std::nothrow) CXvptee(m_spObjectWrapped.Get(), m_streamCategory); + DMFTCHECKNULL_GOTO(spXvpTee.Get(), done, E_OUTOFMEMORY); + (VOID)spXvpTee->SetD3DManager(m_spDeviceManagerUnk.Get()); + DMFTCHECKHR_GOTO(spXvpTee->SetMediaTypes(spMediaType.Get(), m_pOutputMediaType.Get()), done); + m_spObjectWrapped = spXvpTee; + m_pOutputMediaType = spMediaType; + //Recreate the Allocator + DMFTCHECKHR_GOTO(CreateAllocator(), done); + m_bXvpAdded = TRUE; + } done: if (FAILED(hr)) { @@ -1125,7 +1118,7 @@ VOID CDecoderTee::ShutdownTee() CGrayTee::CGrayTee(_In_ Ctee *tee) : CWrapTee(tee),m_transformfn(nullptr) { } -STDMETHODIMP CGrayTee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample, _Inout_ bool &newSample) +STDMETHODIMP CGrayTee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample) { HRESULT hr = S_OK; ComPtr spOutputSample; @@ -1190,7 +1183,6 @@ STDMETHODIMP CGrayTee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSam } if (spOutputSample.Get()) { - newSample = true; *ppOutSample = spOutputSample.Detach(); } done: @@ -1275,7 +1267,7 @@ HRESULT CSampleCopytee::StopStreaming() return S_OK; } -STDMETHODIMP CSampleCopytee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample, _Inout_ bool &newSample) +STDMETHODIMP CSampleCopytee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** ppOutSample) { HRESULT hr = S_OK; @@ -1318,7 +1310,6 @@ STDMETHODIMP CSampleCopytee::Do(_In_ IMFSample *pSample, _Outptr_ IMFSample** pp if (spXVPOutputSample.Get()) { - newSample = true; *ppOutSample = spXVPOutputSample.Detach(); } diff --git a/avstream/sampledevicemft/multipinmfthelpers.h b/avstream/sampledevicemft/multipinmfthelpers.h index 681ca0712..4237dbf42 100644 --- a/avstream/sampledevicemft/multipinmfthelpers.h +++ b/avstream/sampledevicemft/multipinmfthelpers.h @@ -326,7 +326,7 @@ class CWrapTee : public Ctee } STDMETHODIMP PassThrough ( _In_ IMFSample* ); - virtual STDMETHODIMP Do ( _In_ IMFSample* pSample, _Out_ IMFSample ** , _Inout_ bool &newSample) = 0; + virtual STDMETHODIMP Do ( _In_ IMFSample* pSample, _Out_ IMFSample **) = 0; STDMETHODIMP SetMediaTypes(_In_ IMFMediaType* pInMediaType, _In_ IMFMediaType* pOutMediaType); // // Inline functions @@ -395,8 +395,7 @@ class CVideoProcTee: public CWrapTee } return hr; } - virtual ~CVideoProcTee() - {} + virtual ~CVideoProcTee(); protected: CCritSec m_Lock; __inline VOID SetAsyncStatus(_In_ HRESULT hrStatus) @@ -426,7 +425,7 @@ class CXvptee :public CVideoProcTee{ virtual ~CXvptee(); STDMETHOD(StartStreaming)(); STDMETHOD(StopStreaming)(); - STDMETHODIMP Do ( _In_ IMFSample* pSample, _Outptr_ IMFSample **, _Inout_ bool &newSample); + STDMETHODIMP Do ( _In_ IMFSample* pSample, _Outptr_ IMFSample **); STDMETHODIMP Configure ( _In_opt_ IMFMediaType *, _In_opt_ IMFMediaType *, _Outptr_ IMFTransform** ); }; @@ -453,7 +452,7 @@ class CDecoderTee : public CVideoProcTee { } virtual ~CDecoderTee(); - STDMETHODIMP Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **, _Inout_ bool &newSample); + STDMETHODIMP Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **); STDMETHODIMP Configure(_In_opt_ IMFMediaType *, _In_opt_ IMFMediaType *, _Outptr_ IMFTransform**); STDMETHODIMP Invoke(_In_ IMFAsyncResult*); protected: @@ -491,7 +490,7 @@ class CSampleCopytee :public CVideoProcTee { ~CSampleCopytee(); STDMETHOD(StartStreaming)(); STDMETHOD(StopStreaming)(); - STDMETHODIMP Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **, _Inout_ bool &newSample); + STDMETHODIMP Do(_In_ IMFSample* pSample, _Outptr_ IMFSample **); STDMETHODIMP Configure(_In_opt_ IMFMediaType *, _In_opt_ IMFMediaType *, _Outptr_ IMFTransform**); }; @@ -502,7 +501,7 @@ class CGrayTee : public CWrapTee { ~CGrayTee() { } - STDMETHODIMP Do(_In_ IMFSample* pSample, _Out_ IMFSample **, , _Inout_ bool &newSample); + STDMETHODIMP Do(_In_ IMFSample* pSample, _Out_ IMFSample **); STDMETHODIMP Configure(_In_opt_ IMFMediaType *, _In_opt_ IMFMediaType *, _Outptr_ IMFTransform**); private: // Function pointer for the function that transforms the image. diff --git a/avstream/sampledevicemft/stdafx.h b/avstream/sampledevicemft/stdafx.h index 657208cdb..a76118c0f 100644 --- a/avstream/sampledevicemft/stdafx.h +++ b/avstream/sampledevicemft/stdafx.h @@ -54,8 +54,8 @@ using namespace Microsoft::WRL; // //#define MF_DEVICEMFT_ADD_GRAYSCALER_ 1 #define MF_DEVICEMFT_ASYNCPIN_NEEDED 1 -//#define MF_DEVICEMFT_DECODING_MEDIATYPE_NEEDED 0 -#define MF_DEVICEMFT_SET_SPHERICAL_ATTRIBUTES 1 +//#define MF_DEVICEMFT_DECODING_MEDIATYPE_NEEDED 1 +//#define MF_DEVICEMFT_SET_SPHERICAL_ATTRIBUTES 1 //#define MF_DEVICEMFT_ENUM_HW_DECODERS 1 diff --git a/biometrics/adapters/engine_adapter/EngineAdapter.vcxproj b/biometrics/adapters/engine_adapter/EngineAdapter.vcxproj index aa87c108b..4c462ac4c 100644 --- a/biometrics/adapters/engine_adapter/EngineAdapter.vcxproj +++ b/biometrics/adapters/engine_adapter/EngineAdapter.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/biometrics/adapters/sensor_adapter/SensorAdapter.vcxproj b/biometrics/adapters/sensor_adapter/SensorAdapter.vcxproj index 008320a3e..166f8076d 100644 --- a/biometrics/adapters/sensor_adapter/SensorAdapter.vcxproj +++ b/biometrics/adapters/sensor_adapter/SensorAdapter.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/biometrics/adapters/storage_adapter/StorageAdapter.vcxproj b/biometrics/adapters/storage_adapter/StorageAdapter.vcxproj index d9b4caf00..217ba7602 100644 --- a/biometrics/adapters/storage_adapter/StorageAdapter.vcxproj +++ b/biometrics/adapters/storage_adapter/StorageAdapter.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/biometrics/driver/WudfBioUsbSample.inx b/biometrics/driver/WudfBioUsbSample.inx index bd32c0dcb..22e8e1cfb 100644 Binary files a/biometrics/driver/WudfBioUsbSample.inx and b/biometrics/driver/WudfBioUsbSample.inx differ diff --git a/bluetooth/bthecho/bthcli/app/BthEcho.vcxproj b/bluetooth/bthecho/bthcli/app/BthEcho.vcxproj index 382f447b7..2d15392b3 100644 --- a/bluetooth/bthecho/bthcli/app/BthEcho.vcxproj +++ b/bluetooth/bthecho/bthcli/app/BthEcho.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.inx b/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.inx index e6bfeb556..6f326ff3a 100644 Binary files a/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.inx and b/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.inx differ diff --git a/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.vcxproj b/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.vcxproj index 6f79e19b5..389e659e2 100644 --- a/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.vcxproj +++ b/bluetooth/bthecho/bthcli/sys/BthEchoSampleCli.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/bluetooth/bthecho/bthsrv/inst/bthsrvinst.vcxproj b/bluetooth/bthecho/bthsrv/inst/bthsrvinst.vcxproj index c5f3d960b..035024e84 100644 --- a/bluetooth/bthecho/bthsrv/inst/bthsrvinst.vcxproj +++ b/bluetooth/bthecho/bthsrv/inst/bthsrvinst.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.inx b/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.inx index f8f62e886..3079c6d0d 100644 Binary files a/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.inx and b/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.inx differ diff --git a/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.vcxproj b/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.vcxproj index f612a2bc2..6c186f8ec 100644 --- a/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.vcxproj +++ b/bluetooth/bthecho/bthsrv/sys/BthEchoSampleSrv.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/bluetooth/bthecho/common/lib/bthecho.vcxproj b/bluetooth/bthecho/common/lib/bthecho.vcxproj index 27ac5cc62..329d8f306 100644 --- a/bluetooth/bthecho/common/lib/bthecho.vcxproj +++ b/bluetooth/bthecho/common/lib/bthecho.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary diff --git a/build-dir.cmd b/build-dir.cmd deleted file mode 100644 index 56874f1c4..000000000 --- a/build-dir.cmd +++ /dev/null @@ -1,31 +0,0 @@ -@echo off -setlocal -set logfile=%cd%\build-result.log -del %logfile% 2>nul -call :check_folder . . -goto :eof - -rem ========================================= -rem check_folder -rem $1 - sub-folder name -rem $2 - full path to the sub-folder -rem -:check_folder -set name=%1 -set fullpath=%2 -set name=%name:"=% -set fullpath=%fullpath:"=% -pushd "%name%" -if exist *.sln ( - echo %fullpath% - echo === %fullpath% >> %logfile% - - for /f %%i in ('dir /b *.sln') do ( - msbuild /nologo /v:q /m /t:rebuild %%i >> %logfile% - ) -) else ( - for /d %%i in (*) do ( - call :check_folder "%%i" "%fullpath%/%%i" - ) -) -popd diff --git a/exclusions.csv b/exclusions.csv index 39bc53c7a..af7bb3e31 100644 --- a/exclusions.csv +++ b/exclusions.csv @@ -2,10 +2,8 @@ Path,Reason general\dchu\osrfx2_dchu_base,Wrong Toolset - needs migration general\dchu\osrfx2_dchu_extension_loose,Needs fix for project not found general\dchu\osrfx2_dchu_extension_tight,Wrong Toolset - needs migration -general\simplemediasource,ARM64 LNK1181: cannot open input file 'SimpleMediaSource.lib' general\winhec 2017 lab\toaster driver,Needs input from end user general\winhec 2017 lab\toaster support app,Needs input from end user -network\trans\stmedit,Invalid Win32 architecture network\trans\wfpsampler,Missing INF section; missing libs network\wlan\wdi,Invalid architecture print\oem printer customization plug-in samples\c++,Invalid architecture diff --git a/filesys/cdfs/cdfs.vcxproj b/filesys/cdfs/cdfs.vcxproj index 5e053a300..9a32ad6ca 100644 --- a/filesys/cdfs/cdfs.vcxproj +++ b/filesys/cdfs/cdfs.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/filesys/fastfat/fastfat.vcxproj b/filesys/fastfat/fastfat.vcxproj index 09c805a23..8ad4848e8 100644 --- a/filesys/fastfat/fastfat.vcxproj +++ b/filesys/fastfat/fastfat.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/filesys/fastfat/lockctrl.c b/filesys/fastfat/lockctrl.c index 58aacdcaf..1cb183fbd 100644 --- a/filesys/fastfat/lockctrl.c +++ b/filesys/fastfat/lockctrl.c @@ -666,7 +666,7 @@ Return Value: } // - // Acquire exclusive access to the Fcb and enqueue the Irp if we didn't + // Acquire shared access to the Fcb and enqueue the Irp if we didn't // get access // diff --git a/filesys/miniFilter/MetadataManager/fmm.inf b/filesys/miniFilter/MetadataManager/fmm.inf index 5c39ed069..caf4bc8fc 100644 Binary files a/filesys/miniFilter/MetadataManager/fmm.inf and b/filesys/miniFilter/MetadataManager/fmm.inf differ diff --git a/filesys/miniFilter/NameChanger/NameChanger.inf b/filesys/miniFilter/NameChanger/NameChanger.inf index cd74fb44c..36b99019b 100644 Binary files a/filesys/miniFilter/NameChanger/NameChanger.inf and b/filesys/miniFilter/NameChanger/NameChanger.inf differ diff --git a/filesys/miniFilter/avscan/avscan.inf b/filesys/miniFilter/avscan/avscan.inf index 2162f0b4d..26fb6c22c 100644 Binary files a/filesys/miniFilter/avscan/avscan.inf and b/filesys/miniFilter/avscan/avscan.inf differ diff --git a/filesys/miniFilter/cancelSafe/cancelSafe.inf b/filesys/miniFilter/cancelSafe/cancelSafe.inf index 132eea1e5..d526b3dc4 100644 Binary files a/filesys/miniFilter/cancelSafe/cancelSafe.inf and b/filesys/miniFilter/cancelSafe/cancelSafe.inf differ diff --git a/filesys/miniFilter/cdo/cdo.inf b/filesys/miniFilter/cdo/cdo.inf index 52dc6c068..c51cae2c9 100644 Binary files a/filesys/miniFilter/cdo/cdo.inf and b/filesys/miniFilter/cdo/cdo.inf differ diff --git a/filesys/miniFilter/change/change.inf b/filesys/miniFilter/change/change.inf index 9a495e76c..86a7b868d 100644 Binary files a/filesys/miniFilter/change/change.inf and b/filesys/miniFilter/change/change.inf differ diff --git a/filesys/miniFilter/ctx/ctx.inf b/filesys/miniFilter/ctx/ctx.inf index 27a7f6742..39e935afb 100644 Binary files a/filesys/miniFilter/ctx/ctx.inf and b/filesys/miniFilter/ctx/ctx.inf differ diff --git a/filesys/miniFilter/delete/delete.inf b/filesys/miniFilter/delete/delete.inf index aa974b472..b9a572fe2 100644 Binary files a/filesys/miniFilter/delete/delete.inf and b/filesys/miniFilter/delete/delete.inf differ diff --git a/filesys/miniFilter/minispy/minispy.inf b/filesys/miniFilter/minispy/minispy.inf index c5cc24bb5..c210097cd 100644 Binary files a/filesys/miniFilter/minispy/minispy.inf and b/filesys/miniFilter/minispy/minispy.inf differ diff --git a/filesys/miniFilter/nullFilter/nullFilter.c b/filesys/miniFilter/nullFilter/nullFilter.c index 9944db135..6b75c1f53 100644 --- a/filesys/miniFilter/nullFilter/nullFilter.c +++ b/filesys/miniFilter/nullFilter/nullFilter.c @@ -28,7 +28,6 @@ Module Name: // Global variables //--------------------------------------------------------------------------- -#define NULL_FILTER_FILTER_NAME L"NullFilter" typedef struct _NULL_FILTER_DATA { diff --git a/filesys/miniFilter/nullFilter/nullFilter.inf b/filesys/miniFilter/nullFilter/nullFilter.inf index 5f1c45c21..0e710e2d8 100644 Binary files a/filesys/miniFilter/nullFilter/nullFilter.inf and b/filesys/miniFilter/nullFilter/nullFilter.inf differ diff --git a/filesys/miniFilter/passThrough/passThrough.inf b/filesys/miniFilter/passThrough/passThrough.inf index 91d59655e..6db4d0d07 100644 Binary files a/filesys/miniFilter/passThrough/passThrough.inf and b/filesys/miniFilter/passThrough/passThrough.inf differ diff --git a/filesys/miniFilter/scanner/scanner.inf b/filesys/miniFilter/scanner/scanner.inf index df5cc857e..762f5eec7 100644 Binary files a/filesys/miniFilter/scanner/scanner.inf and b/filesys/miniFilter/scanner/scanner.inf differ diff --git a/filesys/miniFilter/simrep/simrep.inf b/filesys/miniFilter/simrep/simrep.inf index 2d01803d2..93632e330 100644 Binary files a/filesys/miniFilter/simrep/simrep.inf and b/filesys/miniFilter/simrep/simrep.inf differ diff --git a/filesys/miniFilter/swapBuffers/swapBuffers.inf b/filesys/miniFilter/swapBuffers/swapBuffers.inf index 34298e6ba..ad88200e1 100644 Binary files a/filesys/miniFilter/swapBuffers/swapBuffers.inf and b/filesys/miniFilter/swapBuffers/swapBuffers.inf differ diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx index 73b6d10e4..39bd54684 100644 Binary files a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx and b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx differ diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx index 62c305cb2..045fc91fe 100644 Binary files a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx and b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx differ diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx index 29b8e8ec1..a762b235e 100644 Binary files a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx and b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx differ diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx index 62c305cb2..045fc91fe 100644 Binary files a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx and b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx differ diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx index 28f1dd0bd..17670efae 100644 Binary files a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx and b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx differ diff --git a/general/PLX9x5x/sys/Pci9x5x.vcxproj b/general/PLX9x5x/sys/Pci9x5x.vcxproj index de71cdb92..d319a2841 100644 --- a/general/PLX9x5x/sys/Pci9x5x.vcxproj +++ b/general/PLX9x5x/sys/Pci9x5x.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/PLX9x5x/sys/pci9x5x.inx b/general/PLX9x5x/sys/pci9x5x.inx index 675a2a2ca..8fdb2eea1 100644 Binary files a/general/PLX9x5x/sys/pci9x5x.inx and b/general/PLX9x5x/sys/pci9x5x.inx differ diff --git a/general/SimpleMediaSource/README.md b/general/SimpleMediaSource/README.md index 4467f16b2..baa17a301 100644 --- a/general/SimpleMediaSource/README.md +++ b/general/SimpleMediaSource/README.md @@ -27,6 +27,11 @@ For more information, see the accompanying documentation at [Frame Server Custom 1. Deploy the driver package with the following command: - `devcon dp_add SimpleMediaSourceDriver.inf` + `devgen /add /bus ROOT /hardwareid root\SimpleMediaSource` + `pnputil /add-driver SimpleMediaSourceDriver.inf /install` -1. In Device Manager, locate **SimpleMediaSource Capture Source**, under the Camera category. Open the Microsoft Camera App, switch cameras if necessary until the camera is streaming from the SimpleMediaSource. You should see a scrolling black and white gradient. +1. Verify installation with Device Manager, locate **SimpleMediaSource Capture Source**, under the Camera category. If device does not appear there, check %windir%\inf\setupapi.dev.log for installation logs. The device instance ID will be available as the output of the devgen command and can be used as input to pnputil to determine status of the device. + + `pnputil /enum-devices /instanceid "" /deviceids /services /stack /drivers` + +1. Open the Microsoft Camera App, switch cameras if necessary until the camera is streaming from the SimpleMediaSource. You should see a scrolling black and white gradient. diff --git a/general/SimpleMediaSource/SimpleMediaSource.sln b/general/SimpleMediaSource/SimpleMediaSource.sln index f6bd620c2..95ba61dab 100644 --- a/general/SimpleMediaSource/SimpleMediaSource.sln +++ b/general/SimpleMediaSource/SimpleMediaSource.sln @@ -19,8 +19,10 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM.ActiveCfg = Debug|Win32 - {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM64.ActiveCfg = Debug|Win32 + {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM.ActiveCfg = Debug|ARM + {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM.Build.0 = Debug|ARM + {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|ARM64.Build.0 = Debug|ARM64 {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|x64.ActiveCfg = Debug|x64 {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|x64.Build.0 = Debug|x64 {43AD9BF7-E765-48FE-9826-71A8F2CB12DD}.Debug|x86.ActiveCfg = Debug|Win32 diff --git a/general/SimpleMediaSource/SimpleMediaSourceDriver/SimpleMediaSourceDriver.inf b/general/SimpleMediaSource/SimpleMediaSourceDriver/SimpleMediaSourceDriver.inf index dabb3237f..d9f054029 100644 Binary files a/general/SimpleMediaSource/SimpleMediaSourceDriver/SimpleMediaSourceDriver.inf and b/general/SimpleMediaSource/SimpleMediaSourceDriver/SimpleMediaSourceDriver.inf differ diff --git a/general/SystemDma/wdm/exe/SystemDmaApp.vcxproj b/general/SystemDma/wdm/exe/SystemDmaApp.vcxproj index 636d5d5f9..eaf152f46 100644 --- a/general/SystemDma/wdm/exe/SystemDmaApp.vcxproj +++ b/general/SystemDma/wdm/exe/SystemDmaApp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/SystemDma/wdm/sys/SDma.vcxproj b/general/SystemDma/wdm/sys/SDma.vcxproj index 76c512c3f..57c4d115b 100644 --- a/general/SystemDma/wdm/sys/SDma.vcxproj +++ b/general/SystemDma/wdm/sys/SDma.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx index 2e7e0ad37..2fff1924a 100644 Binary files a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx and b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx differ diff --git a/general/cancel/exe/canclapp.vcxproj b/general/cancel/exe/canclapp.vcxproj index d69432134..e1c065912 100644 --- a/general/cancel/exe/canclapp.vcxproj +++ b/general/cancel/exe/canclapp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/cancel/startio/cancel.vcxproj b/general/cancel/startio/cancel.vcxproj index 6aac3614e..80f03006e 100644 --- a/general/cancel/startio/cancel.vcxproj +++ b/general/cancel/startio/cancel.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/cancel/sys/cancel.vcxproj b/general/cancel/sys/cancel.vcxproj index a5c258274..e10bd5827 100644 --- a/general/cancel/sys/cancel.vcxproj +++ b/general/cancel/sys/cancel.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/echo/kmdf/driver/AutoSync/echo.inx b/general/echo/kmdf/driver/AutoSync/echo.inx index 43ff49d22..cd83b6c0e 100644 Binary files a/general/echo/kmdf/driver/AutoSync/echo.inx and b/general/echo/kmdf/driver/AutoSync/echo.inx differ diff --git a/general/echo/kmdf/driver/AutoSync/echo.vcxproj b/general/echo/kmdf/driver/AutoSync/echo.vcxproj index 0dc8b18ea..09263c87a 100644 --- a/general/echo/kmdf/driver/AutoSync/echo.vcxproj +++ b/general/echo/kmdf/driver/AutoSync/echo.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/echo/kmdf/driver/DriverSync/echo_2.inx b/general/echo/kmdf/driver/DriverSync/echo_2.inx index f4ece1a73..b4cf3c25b 100644 Binary files a/general/echo/kmdf/driver/DriverSync/echo_2.inx and b/general/echo/kmdf/driver/DriverSync/echo_2.inx differ diff --git a/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj b/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj index 7640e6c4b..b5da58a8f 100644 --- a/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj +++ b/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/echo/kmdf/exe/echoapp.vcxproj b/general/echo/kmdf/exe/echoapp.vcxproj index 8fb2f51f9..bdbd9cc54 100644 --- a/general/echo/kmdf/exe/echoapp.vcxproj +++ b/general/echo/kmdf/exe/echoapp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/echo/umdf/Comsup.cpp b/general/echo/umdf/Comsup.cpp deleted file mode 100644 index fd2984700..000000000 --- a/general/echo/umdf/Comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/general/echo/umdf/Comsup.h b/general/echo/umdf/Comsup.h deleted file mode 100644 index b96fd9828..000000000 --- a/general/echo/umdf/Comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/general/echo/umdf/Device.cpp b/general/echo/umdf/Device.cpp deleted file mode 100644 index 77110e8ed..000000000 --- a/general/echo/umdf/Device.cpp +++ /dev/null @@ -1,415 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the sample driver's - device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "initguid.h" - -#include "device.tmh" - -DEFINE_GUID (GUID_DEVINTERFACE_ECHO, - 0xcdc35b6e, 0xbe4, 0x4936, 0xbf, 0x5f, 0x55, 0x37, 0x38, 0xa, 0x7c, 0x1a); -// {CDC35B6E-0BE4-4936-BF5F-5537380A7C1A} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice = NULL; - IWDFDeviceInitialize2 *fxDeviceInit2; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // Set retrieval mode to direct I/O. This needs to be done before the call - // to CreateDevice. - // - hr = FxDeviceInit->QueryInterface(IID_PPV_ARGS(&fxDeviceInit2)); - - if (SUCCEEDED(hr)) - { - // - // WdfDeviceIoBufferedOrDirect for read/write and ioctrl operations. - // UMDF defaults to direct-I/O when the device is not running in a shared - // wudfhost process, and it defaults to buffered-I/O otherwise. Direct I/O - // is not allowed when the device is pooled. - // - // - fxDeviceInit2->SetIoTypePreference(WdfDeviceIoBufferRetrievalDeferred, - WdfDeviceIoBufferedOrDirect, - WdfDeviceIoBufferedOrDirect); - - SAFE_RELEASE(fxDeviceInit2); - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - PCMyQueue defaultQueue; - - HRESULT hr; - - hr = CMyQueue::CreateInstance(m_FxDevice, &defaultQueue); - - if (FAILED(hr)) - { - return hr; - } - - hr = defaultQueue->Configure(); - - if (SUCCEEDED(hr)) - { - // - // In case of success store defaultQueue in our member - // The reference is transferred to m_DefaultQueue - // - - m_Queue = defaultQueue; - } - else - { - // - // In case of failure release the reference - // - - defaultQueue->Release(); - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_ECHO, - NULL); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the sample driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the sample is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackSelfManagedIo))) { - *Object = QueryIPnpCallbackSelfManagedIo(); - hr = S_OK; - } else { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnSelfManagedIoInit( - _In_ IWDFDevice * pWdfDevice - ) -/*++ - - Routine Description: - - This method is called to allow driver to initialize any resources - that driver might need to process I/O. - - Echo driver needs a thread to process completions. We initialize - this thread here - - Arguments: - - pWdfDevice - framework device object for which to initialze resources - - Return Value: - - S_OK in case of success - HRESULT correponding to error returned by CreateThread, in case of failure - ---*/ -{ - HRESULT hr = S_OK; - - UNREFERENCED_PARAMETER(pWdfDevice); - - - m_ThreadHandle = CreateThread( NULL, // Default Security Attrib. - 0, // Initial Stack Size, - CMyQueue::CompletionThread, // Thread Func - (LPVOID)m_Queue, // Arg to Thread Func is Queue - 0, // Creation Flags - NULL ); // Don't need the Thread Id. - - if (m_ThreadHandle == NULL) { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - - return hr; -} - -void -CMyDevice::OnSelfManagedIoCleanup( - _In_ IWDFDevice * pWdfDevice - ) -/*++ - - Routine Description: - - This method is called to allow driver to cleanup any resources - that driver allocated to process I/O. - - It is critical that, in this routine driver wait for all of the - threads which it created to exit. Otherwise those threads could - continue to execute when framework unloads the driver which - would lead to a crash. - - Echo driver created a thread to handle completions. We wait for - that thread to exit in this routine - - Arguments: - - pWdfDevice - framework device object for which to cleanup resources - - Return Value: - - None - ---*/ -{ - // - // Kill the thread and - // wait for the thread to die. - // - - UNREFERENCED_PARAMETER(pWdfDevice); - - if (m_ThreadHandle) { - - // - // Ask queue to set terminate flag which will make - // the thread exit - // - m_Queue->SetExitThread(); - - // - // Wait for the thread to exit - // - - WaitForSingleObject(m_ThreadHandle, INFINITE); - - // - // Close the thread handle - // - - CloseHandle(m_ThreadHandle); - m_ThreadHandle = NULL; - } - - // - // Release the reference we took on the queue callback object - // to keep it alive until the thread exits - // - - SAFE_RELEASE(m_Queue); -} - diff --git a/general/echo/umdf/Device.h b/general/echo/umdf/Device.h deleted file mode 100644 index 70147c113..000000000 --- a/general/echo/umdf/Device.h +++ /dev/null @@ -1,217 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Echo sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#include "queue.h" - -// -// Class for the iotrace driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackSelfManagedIo -{ - -// -// Private data members. -// -private: - - IWDFDevice *m_FxDevice; - - // - // Completion Thread handle used by queue callback object - // - HANDLE m_ThreadHandle; - - // - // Our queue callback object - // Strong reference - since we pass it to the thread we create - // - CMyQueue *m_Queue; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) - { - m_FxDevice = NULL; - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - IPnpCallbackSelfManagedIo * - QueryIPnpCallbackSelfManagedIo( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IPnpCallbackSelfManagedIo methods - // - - // - // We implement this interface to create and tear down - // our completion thread - // - // It is critical that we wait for all the threads we create - // to exit during OnSelfManagedIoCleanup, otherwise thread - // may continue to execute when framework unloads the driver, - // leading to a crash - // - // We don't manage any I/O separate from the queue, so apart - // from OnSelfManagedIoInit and OnSelfManagedIoCleanup, other - // methods have token implementations - // - - virtual - void - STDMETHODCALLTYPE - OnSelfManagedIoCleanup( - _In_ IWDFDevice * pWdfDevice - ); - - virtual - void - STDMETHODCALLTYPE - OnSelfManagedIoFlush( - _In_ IWDFDevice * pWdfDevice - ) - { - UNREFERENCED_PARAMETER( pWdfDevice ); - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoInit( - _In_ IWDFDevice * pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoSuspend( - _In_ IWDFDevice * pWdfDevice - ) - { - UNREFERENCED_PARAMETER( pWdfDevice ); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoRestart( - _In_ IWDFDevice * pWdfDevice - ) - { - UNREFERENCED_PARAMETER( pWdfDevice ); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoStop( - _In_ IWDFDevice * pWdfDevice - ) - { - UNREFERENCED_PARAMETER( pWdfDevice ); - - return S_OK; - } -}; diff --git a/general/echo/umdf/Driver.cpp b/general/echo/umdf/Driver.cpp deleted file mode 100644 index 1428a08ae..000000000 --- a/general/echo/umdf/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/general/echo/umdf/Driver.h b/general/echo/umdf/Driver.h deleted file mode 100644 index 643ea5a57..000000000 --- a/general/echo/umdf/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/general/echo/umdf/Echo.rc b/general/echo/umdf/Echo.rc deleted file mode 100644 index 2a26d85ca..000000000 --- a/general/echo/umdf/Echo.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// Echo.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF Echo User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "UMDFEcho" -#define VER_ORIGINALFILENAME_STR "UMDFEcho.dll" - -#include "common.ver" diff --git a/general/echo/umdf/Queue.cpp b/general/echo/umdf/Queue.cpp deleted file mode 100644 index f366fe31a..000000000 --- a/general/echo/umdf/Queue.cpp +++ /dev/null @@ -1,545 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - - -#include "internal.h" - -// -// IUnknown implementation -// - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// delete critical section. -// - - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Arguments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - if (m_Buffer) { - delete [] m_Buffer; - } - - if (m_InitCritSec) { - ::DeleteCriticalSection(&m_Crit); - } -} - - -// -// Initialize -HRESULT -CMyQueue::CreateInstance( - _In_ IWDFDevice *FxDevice, - _Out_ PCMyQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Arguments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicating success or failure - ---*/ -{ - CMyQueue *pMyQueue = new CMyQueue; - HRESULT hr; - - if (pMyQueue == NULL) { - return E_OUTOFMEMORY; - } - - hr = pMyQueue->Initialize(FxDevice); - - if (SUCCEEDED(hr)) - { - *Queue = pMyQueue; - } - else - { - pMyQueue->Release(); - } - return hr; -} - -HRESULT -CMyQueue::Initialize( - _In_ IWDFDevice *FxDevice - ) -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Initialize the critical section before we continue - // - - if (!InitializeCriticalSectionAndSpinCount(&m_Crit,0x80000400)) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit; - } - m_InitCritSec = TRUE; - - // - // Create the framework queue - // - - { - IUnknown *unknown = QueryIUnknown(); - hr = FxDevice->CreateIoQueue(unknown, - TRUE, - WdfIoQueueDispatchSequential, - TRUE, - FALSE, - &fxQueue); - unknown->Release(); - } - - if (FAILED(hr)) - { - goto Exit; - } - - m_FxQueue = fxQueue; - - fxQueue->Release(); - -Exit: - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Arguments: - - Follows COM specifications - -Return Value: - - HRESULT indicating success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) { - *Object = QueryIQueueCallbackWrite(); - hr = S_OK; - } else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackRead))) { - *Object = QueryIQueueCallbackRead(); - hr = S_OK; - } else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) { - *Object = QueryIQueueCallbackDeviceIoControl(); - hr = S_OK; - } else { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Length of input buffer - OutputBufferSizeInBytes - Length of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - - UNREFERENCED_PARAMETER(pWdfQueue); - UNREFERENCED_PARAMETER(ControlCode); - UNREFERENCED_PARAMETER(InputBufferSizeInBytes); - UNREFERENCED_PARAMETER(OutputBufferSizeInBytes); - - pWdfRequest->Complete(S_OK); - return; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - - Write dispatch routine - IQueueCallbackWrite - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Length of bytes in the write buffer - - Allocate and copy data to local buffer -Return Value: - - VOID - ---*/ -{ - - HRESULT hr; - IWDFMemory* pRequestMemory = NULL; - IWDFIoRequest2 * pWdfRequest2 = NULL; - - UNREFERENCED_PARAMETER(pWdfQueue); - - // - // Handle Zero length writes. - // - - if (!BytesToWrite) { - pWdfRequest->CompleteWithInformation(S_OK, 0); - return; - } - - if( BytesToWrite > MAX_WRITE_LENGTH ) { - - pWdfRequest->CompleteWithInformation(HRESULT_FROM_WIN32(ERROR_MORE_DATA), 0); - return; - } - - // Release previous buffer if set - - if( m_Buffer != NULL ) { - delete [] m_Buffer; - m_Buffer = NULL; - m_Length = 0L; - } - - // Allocate Buffer - - m_Buffer = new UCHAR[BytesToWrite]; - if (m_Buffer == NULL) { - pWdfRequest->Complete(E_OUTOFMEMORY); - m_Length = 0L; - return; - } - - // Get memory object - hr = pWdfRequest->QueryInterface(IID_PPV_ARGS(&pWdfRequest2)); - - if (FAILED(hr)) { - goto Exit; - } - - hr = pWdfRequest2->RetrieveInputMemory(&pRequestMemory); - - if (FAILED(hr)) { - goto Exit; - } - - // Copy from memory object to our buffer - - hr = pRequestMemory->CopyToBuffer(0, m_Buffer, BytesToWrite); - - if (FAILED(hr)) { - goto Exit; - } - - // - // Release memory object. - // - SAFE_RELEASE(pRequestMemory); - - // - // Save the information so that we can use it - // to complete the request later. - // - - Lock(); - - m_Length = (ULONG) BytesToWrite; - m_XferredBytes = m_Length; - m_CurrentRequest = pWdfRequest2; - - Unlock(); - -Exit: - - if (FAILED(hr)) { - if (pWdfRequest2) { - pWdfRequest2->CompleteWithInformation(hr, 0); - } - delete [] m_Buffer; - m_Buffer = NULL; - SAFE_RELEASE(pRequestMemory); - } - - // - // This is an early release. pWdfRequest2 will be released, when the request is completed - // - SAFE_RELEASE(pWdfRequest2); - - return; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T SizeInBytes - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - SizeInBytes - Length of bytes in the read buffer - - Copy available data into the read buffer -Return Value: - - VOID - ---*/ -{ - IWDFMemory* pRequestMemory = NULL; - IWDFIoRequest2 * pWdfRequest2 = NULL; - HRESULT hr; - - UNREFERENCED_PARAMETER(pWdfQueue); - - // - // Handle Zero length reads. - // - - if (!SizeInBytes) { - pWdfRequest->CompleteWithInformation(S_OK, 0); - return; - } - - if (m_Buffer == NULL) { - pWdfRequest->CompleteWithInformation(HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER), SizeInBytes); - return; - } - - if (m_Length < SizeInBytes) { - SizeInBytes = m_Length; - } - - // - // Get memory object - // - - hr = pWdfRequest->QueryInterface(IID_PPV_ARGS(&pWdfRequest2)); - - if (FAILED(hr)) { - goto Exit; - } - - hr = pWdfRequest2->RetrieveOutputMemory(&pRequestMemory ); - - if (FAILED(hr)) { - goto Exit; - } - - // Copy from buffer to memory object - - hr = pRequestMemory->CopyFromBuffer(0, m_Buffer, SizeInBytes); - - if (FAILED(hr)) { - goto Exit; - } - - // - // Release memory object. - // - - SAFE_RELEASE(pRequestMemory); - - // - // Save the information so that we can use it - // to complete the request later. - // - - Lock(); - - m_CurrentRequest = pWdfRequest2; - m_XferredBytes = SizeInBytes; - - Unlock(); - -Exit: - - if (FAILED(hr)) { - if (pWdfRequest2) { - pWdfRequest2->CompleteWithInformation(hr, 0); - } - SAFE_RELEASE(pRequestMemory); - } - - // - // This is an early release. pWdfRequest2 will be released, when the request is completed - // - SAFE_RELEASE(pWdfRequest2); - - return; -} - -DWORD -CMyQueue::CompletionThread( - PVOID ThreadParameter - ) -/*++ - -Routine Description: - - - This routine is called from the thread started to complete - I/O requests. It sleeps for TIMER_PERIOD and then completes - the current request. Note that it has to release the lock - before it calls the request complete method. - -Arguments: - - ThreadParameter - This is a pointer to the Queue object. - -Return Value: - - VOID - ---*/ -{ - CMyQueue *pQueue = (CMyQueue *)ThreadParameter; - IWDFIoRequest2 *request; - SIZE_T bytesXferred = 0; - - for (;;) { - - // - // Block for a fixed time and then complete the request. - // - - Sleep(TIMER_PERIOD); - - pQueue->Lock(); - - // - // Process the current request. - // - - request = pQueue->m_CurrentRequest; - - if (request) { - bytesXferred = pQueue->m_XferredBytes; - } - - // - // Reset values. - // - - pQueue->m_CurrentRequest = NULL; - pQueue->m_XferredBytes = 0; - - - pQueue->Unlock(); - - if (request) { - request->CompleteWithInformation(S_OK, bytesXferred); - } - - // - // If thread needs to be terminated - // - - if (pQueue->m_ExitThread) { - ExitThread(0); - } - - } - -} diff --git a/general/echo/umdf/Queue.h b/general/echo/umdf/Queue.h deleted file mode 100644 index c4b28c976..000000000 --- a/general/echo/umdf/Queue.h +++ /dev/null @@ -1,213 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// Set max write length for testing -#define MAX_WRITE_LENGTH (40*1024) - -// Set timer period in ms -#define TIMER_PERIOD 100 - -// -// Queue Callback Object. -// - -class CMyQueue : - public IQueueCallbackDeviceIoControl, - public IQueueCallbackRead, - public IQueueCallbackWrite, - public CUnknown -{ - PVOID m_Buffer; // Current buffer - ULONG m_Length; // Length of the buffer - SIZE_T m_XferredBytes; // Amount of bytes transferred for the current request - IWDFIoRequest2 *m_CurrentRequest; // Current request - CRITICAL_SECTION m_Crit; // Lock to protect updates to CMyQueue fields - BOOLEAN m_ExitThread; // If TRUE Terminate thread. - BOOLEAN m_InitCritSec; // If TRUE lock initialized - - IWDFIoQueue *m_FxQueue; - - CMyQueue() : - m_Buffer(NULL), - m_Length (0), - m_CurrentRequest(NULL), - m_XferredBytes(0), - m_ExitThread(FALSE), - m_InitCritSec(FALSE), - m_FxQueue(NULL) - { - } - - virtual ~CMyQueue(); - - _Acquires_lock_(this->m_Crit) - __inline - void - Lock( - ) - { - ::EnterCriticalSection(&m_Crit); - } - - _Releases_lock_(this->m_Crit) - __inline - void - Unlock( - ) - { - ::LeaveCriticalSection(&m_Crit); - } - - HRESULT - Initialize( - _In_ IWDFDevice *FxDevice - ); - -public: - - // - // Completion thread routine. - // - - static DWORD CompletionThread( PVOID ThreadParameter); - - // - // Sets the flag to make thread exit - // - - void - SetExitThread() - { - m_ExitThread = TRUE; - } - - static - HRESULT - CreateInstance( - _In_ IWDFDevice *FxDevice, - _Out_ PCMyQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackRead * - QueryIQueueCallbackRead( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) { - return CUnknown::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) { - return CUnknown::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // IQueueCallbackDeviceIoControl - // - virtual - VOID - STDMETHODCALLTYPE - OnDeviceIoControl( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); - - // IQueueCallbackWrite - // - virtual - VOID - STDMETHODCALLTYPE - OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // IQueueCallbackRead - // - virtual - VOID - STDMETHODCALLTYPE - OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); -}; diff --git a/general/echo/umdf/README.md b/general/echo/umdf/README.md deleted file mode 100644 index 241e633da..000000000 --- a/general/echo/umdf/README.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -page_type: sample -description: "Demonstrates how to use UMDF version 1 to write a driver and demonstrates best practices." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Echo Sample (UMDF Version 1) - -This sample demonstrates how to use User-Mode Driver Framework (UMDF) version 1 to write a driver and demonstrates best practices. - -It also demonstrates the use of a default Serial Dispatch I/O Queue, its request start events, cancellation event, and synchronizing with another thread. The preferred I/O retrieval mode is set to Direct I/O. So, whenever a request is received by the framework, UMDF looks at the size of the buffer and determines, whether it should copy the buffer (if the length is less than 2 full pages) or map it (if the length is greater or equal to 2 full pages). - -This sample driver is a minimal driver meant to demonstrate the usage of the User-Mode Driver Framework. It is not intended for use in a production environment. - -## Related technologies - -[User-Mode Driver Framework](https://docs.microsoft.com/windows-hardware/drivers/wdf/getting-started-with-umdf-version-2) - -## Testing - -To test the Echo driver, you can run echoapp.exe which is built from \\echo\\exe. - -First install the device as described above. Then run echoapp.exe. - -```cmd -D:\>echoapp /? -Usage: -Echoapp.exe --- Send single write and read request synchronously -Echoapp.exe -Async --- Send 100 reads and writes asynchronously -Exit the app anytime by pressing Ctrl-C - -D:\>echoapp -DevicePath: \\?\root#sample#0000#{cdc35b6e-0be4-4936-bf5f-5537380a7c1a} -Opened device successfully -512 Pattern Bytes Written successfully -512 Pattern Bytes Read successfully -Pattern Verified successfully - -D:\>echoapp -Async -DevicePath: \\?\root#sample#0000#{cdc35b6e-0be4-4936-bf5f-5537380a7c1a} -Opened device successfully -Starting AsyncIo -Number of bytes written by request number 0 is 1024 -Number of bytes read by request number 0 is 1024 -Number of bytes read by request number 1 is 1024 -Number of bytes written by request number 2 is 1024 -Number of bytes read by request number 2 is 1024 -Number of bytes written by request number 3 is 1024 -Number of bytes read by request number 3 is 1024 -Number of bytes written by request number 4 is 1024 -Number of bytes read by request number 4 is 1024 -Number of bytes written by request number 5 is 1024 -Number of bytes read by request number 5 is 1024 -Number of bytes written by request number 6 is 1024 -Number of bytes read by request number 6 is 1024 -Number of bytes written by request number 7 is 1024 -Number of bytes read by request number 7 is 1024 -Number of bytes written by request number 8 is 1024 -Number of bytes read by request number 8 is 1024 -Number of bytes written by request number 9 is 1024 -Number of bytes read by request number 9 is 1024 -Number of bytes written by request number 10 is 1024 -Number of bytes read by request number 10 is 1024 -Number of bytes written by request number 11 is 1024 -... -``` - -Note that the reads and writes are performed by independent threads in the echo test application. As a result the order of the output may not exactly match what you see above. - -## File Manifest - -comsup.cpp and comsup.h - -- COM Support code - specifically base classes which provide implementations for the standard COM interfaces IUnknown and IClassFactory which are used throughout this sample. - -- The implementation of IClassFactory is designed to create instances of the CMyDriver class. If you should change the name of your base driver class, you would also need to modify this file. - -dllsup.cpp - -- DLL Support code - provides the DLL's entry point as well as the single required export (DllGetClassObject). - -- These depend on comsup.cpp to perform the necessary class creation. - -exports.def - -- This file lists the functions that the driver DLL exports. - -internal.h - -- This is the main header file for this driver. - -Driver.cpp and Driver.h - -- DriverEntry and events on the driver object. - -Device.cpp and Device.h - -- The Events on the device object. - -Queue.cpp and Queue.h - -- Contains Events on the I/O Queue Objects. - -Echo.rc - -- Resource file for the driver. - -WUDFEchoDriver.inx - -- File that describes the installation of this driver. The build process converts this into an INF file. - -echodriver.ctl - -- This file lists the WPP trace control GUID(s) for the sample driver. This file can be used with the tracelog command's -guid flag to enable the collection of these trace events within an established trace session. - -- These GUIDs must remain in sync with the trace control GUIDs defined in internal.h. diff --git a/general/echo/umdf/WUDFEchoDriver.inx b/general/echo/umdf/WUDFEchoDriver.inx deleted file mode 100644 index cf8acb0d4..000000000 Binary files a/general/echo/umdf/WUDFEchoDriver.inx and /dev/null differ diff --git a/general/echo/umdf/WUDFEchoDriver.vcxproj b/general/echo/umdf/WUDFEchoDriver.vcxproj deleted file mode 100644 index 1de35ce7f..000000000 --- a/general/echo/umdf/WUDFEchoDriver.vcxproj +++ /dev/null @@ -1,262 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {13CC3E04-E27E-4E44-90DE-CFBED92D7130} - $(MSBuildProjectName) - 1 - Debug - Win32 - {9838DCDC-C817-4EA5-B7E8-B3F97F2B138A} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFEchoDriver - - - WUDFEchoDriver - - - WUDFEchoDriver - - - WUDFEchoDriver - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/echo/umdf/WUDFEchoDriver.vcxproj.Filters b/general/echo/umdf/WUDFEchoDriver.vcxproj.Filters deleted file mode 100644 index 8a23705a7..000000000 --- a/general/echo/umdf/WUDFEchoDriver.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {CF73CF52-2BA2-434D-8E38-8F730D54F150} - - - h;hpp;hxx;hm;inl;inc;xsd - {6D44B960-AD87-4EA1-80E4-D63DF6914D51} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {9542D238-C8CE-44BC-9307-50CEDCCA5F25} - - - inf;inv;inx;mof;mc; - {D77C3549-2C94-49EB-909E-54EB79474A98} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/general/echo/umdf/dllsup.cpp b/general/echo/umdf/dllsup.cpp deleted file mode 100644 index e7200a284..000000000 --- a/general/echo/umdf/dllsup.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Echo Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the echo driver uses - L"Microsoft\\UMDF\\Echo" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -HRESULT -STDAPICALLTYPE -DllGetClassObject( - _In_ REFCLSID ClassId, - _In_ REFIID InterfaceId, - _Outptr_ LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/general/echo/umdf/echo.sln b/general/echo/umdf/echo.sln deleted file mode 100644 index cc459eeae..000000000 --- a/general/echo/umdf/echo.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFEchoDriver", "WUDFEchoDriver.vcxproj", "{13CC3E04-E27E-4E44-90DE-CFBED92D7130}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Debug|Win32.ActiveCfg = Debug|Win32 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Debug|Win32.Build.0 = Debug|Win32 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Release|Win32.ActiveCfg = Release|Win32 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Release|Win32.Build.0 = Release|Win32 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Debug|x64.ActiveCfg = Debug|x64 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Debug|x64.Build.0 = Debug|x64 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Release|x64.ActiveCfg = Release|x64 - {13CC3E04-E27E-4E44-90DE-CFBED92D7130}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/general/echo/umdf/echodriver.ctl b/general/echo/umdf/echodriver.ctl deleted file mode 100644 index a0ce20896..000000000 --- a/general/echo/umdf/echodriver.ctl +++ /dev/null @@ -1 +0,0 @@ -d93fb470-afb1-4af8-860e-75f726c66f6b WudfEchoDriverTraceGuid diff --git a/general/echo/umdf/exports.def b/general/echo/umdf/exports.def deleted file mode 100644 index ec5646395..000000000 --- a/general/echo/umdf/exports.def +++ /dev/null @@ -1,10 +0,0 @@ -; Echo.def : Declares the module parameters. - -; -; TODO: Change the library name here to match your binary name. -; - -LIBRARY "WUDFEchoDriver.DLL" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/general/echo/umdf/internal.h b/general/echo/umdf/internal.h deleted file mode 100644 index 8e5c2d60f..000000000 --- a/general/echo/umdf/internal.h +++ /dev/null @@ -1,114 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Echo - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (d93fb470,afb1,4af8,860e,75f726c66f6b), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\Echo" -#define MYDRIVER_CLASS_ID {0x7ab7dcf5, 0xd1d4, 0x4085, {0x95, 0x47, 0x1d, 0xb9, 0x68, 0xcc, 0xa7, 0x20}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/general/echo/umdf2/driver/AutoSync/echoum.inx b/general/echo/umdf2/driver/AutoSync/echoum.inx index d15e4413e..3734b873a 100644 Binary files a/general/echo/umdf2/driver/AutoSync/echoum.inx and b/general/echo/umdf2/driver/AutoSync/echoum.inx differ diff --git a/general/echo/umdf2/exe/echoapp.vcxproj b/general/echo/umdf2/exe/echoapp.vcxproj index 8fb2f51f9..bdbd9cc54 100644 --- a/general/echo/umdf2/exe/echoapp.vcxproj +++ b/general/echo/umdf2/exe/echoapp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/echo/umdfSocketEcho/Driver/Connection.cpp b/general/echo/umdfSocketEcho/Driver/Connection.cpp deleted file mode 100644 index e28d0c56a..000000000 --- a/general/echo/umdfSocketEcho/Driver/Connection.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Connection.cpp - -Abstract: - - Module for the socket connection specfic routines in the driver. - Makes Connection to the server given server host and port address. - -Environment: - - User mode only - - ---*/ - -#include "internal.h" -#include "connection.tmh" - - -CConnection::CConnection() -/*++ - -Routine Description: - - Constructor for connection object - -Arguments: - - None - -Return Value: - - VOID - ---*/ -{ - - // Initialize the socket member as Invalid - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - m_socket = INVALID_SOCKET; -} - -HRESULT -CConnection::Connect( - IN IWDFDevice *pDevice - ) -/*++ - -Routine Description: - - This routine is for the initialization of the connection object associated with - the File Object . It is invoked from the dispatch OnCreateFile on the default - queue callback of the driver. It socket connection to the client. - -Arguments: - - pDevice = Wdf Device Object - -Return Value: - - S_OK if success , error HRESULT otherwise - ---*/ -{ - - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - HRESULT hr = S_OK; - - addrinfoW* info = NULL ; - - PWSTR hostStr = NULL; - - PWSTR portStr = NULL; - - // - // Reads the host and port strings stored in the device context. - // - - DeviceContext *pContext = NULL; - - hr = pDevice->RetrieveContext((void**)&pContext); - - if ( FAILED(hr) ) - { - - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: unable to retrieve context from wdf device object %!hresult!", - hr - ); - goto Clean0; - - } - - hostStr = pContext->hostStr; - - portStr = pContext->portStr; - - // - // lookup hostname with addrinfo hints; - // - - addrinfoW hints; - - ZeroMemory(&hints,sizeof(hints)); - - hints.ai_family = AF_INET; - - hints.ai_socktype = SOCK_STREAM; - - hints.ai_protocol = IPPROTO_TCP; - - int n = GetAddrInfoW(hostStr, portStr, &hints, &info); - - if (n != 0) - { - DWORD err = WSAGetLastError(); - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to find address/port of host %!winerr!", - err - ); - hr = HRESULT_FROM_WIN32(err); - goto Clean0; - } - - // - // Create a socket with this infomation recvd in getaddrinfo - // - m_socket = socket(info->ai_family,info->ai_socktype,info->ai_protocol); - - if (m_socket == INVALID_SOCKET) - { - DWORD err = WSAGetLastError(); - - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to create socket %!winerr!", - err - ); - - hr = HRESULT_FROM_WIN32(err); - - goto Clean0; - } - - // - // If that succeeds , proceed to connect to the socket - // - - - ATLASSERT(info->ai_addrlen <= 0x7fffffff); - - int nret = connect(m_socket,info->ai_addr,(int)info->ai_addrlen); - - if (nret == SOCKET_ERROR) - { - DWORD err = WSAGetLastError(); - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to connect to host %!winerr!", - err - ); - hr = HRESULT_FROM_WIN32(err); - - goto Clean0; - } - - -Clean0: - - if (info != NULL) - { - FreeAddrInfoW(info); - - } - - if (FAILED(hr) && m_socket != INVALID_SOCKET) - { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - - return hr; - -} - -HANDLE -CConnection::GetSocketHandle( - ) -/*++ - -Routine Description: - - Function returns the socket handle associated with this connection object - -Arguments: - - None - -Return Value: - - Socket handle if valid socket - INVALID_HANDLE_VALUE otherwise - ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - if ( INVALID_SOCKET != m_socket ) - { - return (HANDLE)m_socket ; - } - else - { - return INVALID_HANDLE_VALUE; - } - -} - - -VOID -CConnection::Close() -/*++ - -Routine Description: - - Closes the socket connection to the server associated with this connection object - -Arguments: - - None - -Return Value: - - None ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - if (m_socket != INVALID_SOCKET) - { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - -} diff --git a/general/echo/umdfSocketEcho/Driver/FileContext.h b/general/echo/umdfSocketEcho/Driver/FileContext.h deleted file mode 100644 index dbdda2e40..000000000 --- a/general/echo/umdfSocketEcho/Driver/FileContext.h +++ /dev/null @@ -1,30 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - filecontext.h - -Abstract: - - This header file defines the structure type for file context associated with the file object - -Environment: - - user mode only - -Revision History: - ---*/ - - -#pragma once - -typedef struct _FileContext -{ - CConnection *pConnection ; - - CComPtr pFileTarget; - -}FileContext; diff --git a/general/echo/umdfSocketEcho/Driver/Queue.cpp b/general/echo/umdfSocketEcho/Driver/Queue.cpp deleted file mode 100644 index 242925d4b..000000000 --- a/general/echo/umdfSocketEcho/Driver/Queue.cpp +++ /dev/null @@ -1,580 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - user mode only - -Revision History: - ---*/ - -#include "internal.h" - -#include "queue.tmh" - -CMyQueue::CMyQueue( - ) : - m_FxQueue(NULL), - m_Device(NULL) -{ -} - -// -// Queue destructor. -// - -CMyQueue::~CMyQueue( - VOID - ) -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ CMyDevice * Device - ) -/*++ - -Routine Description: - - Queue Initialize helper routine. - This routine will Create a default parallel queue associated with the Fx device object - and pass the IUnknown for this queue - -Aruments: - Device - Device object pointer - -Return Value: - - S_OK if Initialize succeeds - ---*/ -{ - - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - CComPtr fxQueue; - - HRESULT hr; - - m_Device = Device; - - // - // Create the I/O Queue object. - // - - { - CComPtr pUnk; - - HRESULT hrQI = this->QueryInterface(__uuidof(IUnknown),(void**)&pUnk); - - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - hr = m_Device->GetFxDevice()->CreateIoQueue( - pUnk, - TRUE, - WdfIoQueueDispatchParallel, - TRUE, - FALSE, - &fxQueue - ); - } - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - "Failed to initialize driver queue %!hresult!", - hr - ); - goto Exit; - } - - m_FxQueue = fxQueue; - - -Exit: - - return hr; -} - -HRESULT -CMyQueue::Configure( - VOID - ) -/*++ - -Routine Description: - - Queue configuration function . - It is called after queue object has been succesfully initialized. - -Aruments: - - NONE - - Return Value: - - S_OK if succeeds. - ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - HRESULT hr = S_OK; - - return hr; -} - - -STDMETHODIMP_(void) -CMyQueue::OnCreateFile( - _In_ IWDFIoQueue* pWdfQueue, - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFFile* pWdfFileObject - ) - -/*++ - -Routine Description: - - Create callback from the framework for this default parallel queue - - The create request will create a socket connection , create a file i/o target associated - with the socket handle for this connection and store in the file object context. - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - pWdfFileObject - WDF file object for this create - - Return Value: - - VOID - ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - HRESULT hr = S_OK; - - CComPtr spFileHandleTargetFactory; - - CComPtr pFileTarget; - - CComPtr pDevice; - - HANDLE SocketHandle = NULL; - - pWdfQueue->GetDevice(&pDevice); - - FileContext *pContext = NULL; - - // - // Create new connection object - // - - CConnection *pConnection = new CConnection(); - - if (NULL == pConnection ) - { - hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Could not create connection object %!hresult!", - hr - ); - goto Exit; - } - - // - // Connect to the socket server - // - - hr = pConnection->Connect(pDevice); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Could not connect %!hresult!", - hr - ); - - goto Exit; - - } - - // - // If that succeeds, get socket handle for the connection - // - - if ( NULL == (SocketHandle = pConnection->GetSocketHandle()) ) - { - hr = E_FAIL; - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to obtain valid Socket Handle %!hresult!", - hr - ); - goto Exit; - } - - // - // Create file context for this file object - // - - pContext = new FileContext; - - if (NULL == pContext) - { - hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Could not create file context %!hresult!", - hr - ); - goto Exit; - - } - - // - // QI for IWDFFileHandleTargetFactory from the framework device object. - // Note UmdfDispatcher in Wdf Section in the Inf - // - - hr = pDevice->QueryInterface(IID_PPV_ARGS(&spFileHandleTargetFactory)); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to obtain target factory for creating FileHandle based I/O target %!hresult!", - hr - ); - goto Exit; - } - - // - // If that succeeds, Create a File Handle I/O Target and associate the socket handle with this target - // - - hr = spFileHandleTargetFactory->CreateFileHandleTarget(SocketHandle ,&pFileTarget); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to create framework I/O target %!hresult!", - hr - ); - goto Exit; - } - - - pContext->pFileTarget = pFileTarget; - - pContext->pConnection = pConnection; - - hr = pWdfFileObject->AssignContext(NULL,(void*)pContext); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to Assign Context to this File Object %!hresult!", - hr - ); - goto Exit; - } - - - -Exit: - - if (FAILED(hr)) - { - - if ( pFileTarget ) - { - pFileTarget->DeleteWdfObject(); - } - - if (pConnection != NULL) - { - delete pConnection; - pConnection = NULL; - } - - if (pContext != NULL) - { - delete pContext; - pContext = NULL; - } - - } - - pWdfRequest->Complete(hr); - -} - - -STDMETHODIMP_ (void) -CMyQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - Write callback from the framework for this default parallel queue - - The write request needs to be sent to the file handle i/o target associated with this fileobject - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Lenth of bytes in the write buffer - - Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - UNREFERENCED_PARAMETER(BytesToWrite); - - // Call helper function to send request to i/o target - - SendRequestToFileTarget(pWdfRequest); - - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - return; -} - -STDMETHODIMP_ (void) -CMyQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToRead - ) -/*++ - -Routine Description: - - Read callback from the framework for this default parallel queue - - The read request needs to be sent to the file handle i/o target associated with this fileobject - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToRead - Lenth of bytes in the read buffer - - -Return Value: - - VOID - ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - UNREFERENCED_PARAMETER(pWdfQueue); - UNREFERENCED_PARAMETER(BytesToRead); - - // - // Call helper function to send request to i/o target - // - - SendRequestToFileTarget(pWdfRequest); - - return; -} - -STDMETHODIMP_(void) -CMyQueue::OnCompletion( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pTarget, - _In_ IWDFRequestCompletionParams* pCompletionParams, - _In_ void* pContext -) -/*++ - -Routine Description: - - This routine is invoked when the request is completed by the lower stack location, - in this case the win32 i/o target associated with the file object of this request - - - Arguments: - - pWdfRequest - wdf request - pTarget - wdf target to which request was earlier sent - pCompletionParams - wdf request completion parameters - pContext - Context information , if any - - -Return Value: - - None ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - UNREFERENCED_PARAMETER(pTarget); - UNREFERENCED_PARAMETER(pContext); - - // Complete request from the driver - pWdfRequest->CompleteWithInformation( - pCompletionParams->GetCompletionStatus(), - pCompletionParams->GetInformation()); -} - -VOID -CMyQueue::SendRequestToFileTarget( - _In_ IWDFIoRequest* pWdfRequest -) -/*++ - -Routine Description: - - This is a helper functiom to send R/W requests to the win32 file i/o target - associated with the socket connection for this request. - First, filecontext is retrieved which has the file i/o target where this request needs to be sent. - - -Arguments: - - pWdfRequest - wdf request - -Return Value: - - None - ---*/ -{ - - HRESULT hr; - - FileContext *pContext = NULL; - CComPtr pWdfFile = NULL; - - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - // - // Get the file object for this request - // - - pWdfRequest->GetFileObject(&pWdfFile); - - // - // Retrieve Context from file object - // - - hr = pWdfFile->RetrieveContext((void**)&pContext); - - if (pContext == NULL) - { - if ( SUCCEEDED(hr) ) - { - hr = E_FAIL; - Trace(TRACE_LEVEL_ERROR, - " No Context associated with this file object %!hresult!", - hr); - } - goto Exit; - } - - // - // If that succeeds, set completion callback for the request - // - pWdfRequest->SetCompletionCallback(CComQIPtr(this), - NULL); - - // - // Do not modify the request, format using current type - // - - pWdfRequest->FormatUsingCurrentType(); - - // - // Send the request to the win32 i/o target . This was created in OnCreateFile - // - - hr = pWdfRequest->Send(pContext->pFileTarget, - 0, - 0); -Exit: - - if (FAILED(hr)) - { - Trace(TRACE_LEVEL_ERROR, - "Could not send request to i/o target %!hresult!", - hr); - pWdfRequest->Complete(hr); - } - - return ; -} - -STDMETHODIMP_(void) -CMyQueue::OnCleanup( - _In_ IWDFObject* /*pWdfObject*/ - ) -{ - // - // CMyQueue has a reference to framework device object via m_FxQueue. - // Framework queue object has a reference to CMyQueue object via the callbacks. - // This leads to circular reference and both the objects can't be destroyed until this circular reference is broken. - // To break the circular reference we release the reference to the framework queue object here in OnCleanup. - // - m_FxQueue = NULL; -} diff --git a/general/echo/umdfSocketEcho/Driver/Queue.h b/general/echo/umdfSocketEcho/Driver/Queue.h deleted file mode 100644 index 952e1e0d8..000000000 --- a/general/echo/umdfSocketEcho/Driver/Queue.h +++ /dev/null @@ -1,83 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - user mode only - -Revision History: - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class ATL_NO_VTABLE CMyQueue : - public CComObjectRootEx, - public IQueueCallbackCreate, - public IQueueCallbackRead, - public IQueueCallbackWrite, - public IRequestCallbackRequestCompletion, - public IObjectCleanup -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyQueue) - -BEGIN_COM_MAP(CMyQueue) - COM_INTERFACE_ENTRY(IQueueCallbackCreate) - COM_INTERFACE_ENTRY(IQueueCallbackRead) - COM_INTERFACE_ENTRY(IQueueCallbackWrite) - COM_INTERFACE_ENTRY(IRequestCallbackRequestCompletion) - COM_INTERFACE_ENTRY(IObjectCleanup) -END_COM_MAP() - -public: - //IQueueCallbackRead - STDMETHOD_(void,OnRead)(_In_ IWDFIoQueue* pWdfQueue,_In_ IWDFIoRequest* pWdfRequest,_In_ SIZE_T NumOfBytesToRead); - - //IQueueCallbackWrite - STDMETHOD_(void,OnWrite)(_In_ IWDFIoQueue* pWdfQueue,_In_ IWDFIoRequest* pWdfRequest,_In_ SIZE_T NumOfBytesToWrite); - - //IQueueCallbackCreate - STDMETHOD_(void,OnCreateFile)(_In_ IWDFIoQueue* pWdfQueue,_In_ IWDFIoRequest* pWDFRequest,_In_ IWDFFile* pWdfFileObject); - - // IRequestCallbackRequestCompletion - STDMETHOD_(void,OnCompletion)(_In_ IWDFIoRequest* pWdfRequest,_In_ IWDFIoTarget* pTarget,_In_ IWDFRequestCompletionParams* pCompletionParams,_In_ void* pContext); - - //IObjectCleanup - STDMETHOD_(void,OnCleanup)(_In_ IWDFObject* pWdfObject); - -public: - CMyQueue(); - ~CMyQueue(); - - STDMETHOD(Initialize)(_In_ CMyDevice * Device); - - HRESULT - Configure( - ); - -private: - CComPtr m_FxQueue; - - // - // Unreferenced pointer to the parent device. - // - - CMyDevice * m_Device; - - VOID SendRequestToFileTarget( _In_ IWDFIoRequest* pWdfRequest); -}; diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.inx b/general/echo/umdfSocketEcho/Driver/SocketEcho.inx deleted file mode 100644 index b1475187b..000000000 Binary files a/general/echo/umdfSocketEcho/Driver/SocketEcho.inx and /dev/null differ diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.rc b/general/echo/umdfSocketEcho/Driver/SocketEcho.rc deleted file mode 100644 index cc27b15fa..000000000 --- a/general/echo/umdfSocketEcho/Driver/SocketEcho.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// Skeleton.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF Sample WUDF SocketEcho Driver" -#define VER_INTERNALNAME_STR "SocketEcho" -#define VER_ORIGINALFILENAME_STR "SocketEcho.dll" - -#include "common.ver" diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj b/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj deleted file mode 100644 index 652dd875e..000000000 --- a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj +++ /dev/null @@ -1,251 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {353E2F22-BD87-47F3-A211-90DE8D583D26} - $(MSBuildProjectName) - 1 - 1 - Debug - Win32 - {CE6B3D79-4604-4FAC-8A53-20B7000101FD} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - SocketEcho - - - SocketEcho - - - SocketEcho - - - SocketEcho - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - Dynamic - - - Dynamic - - - Dynamic - - - Dynamic - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\shlwapi.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\shlwapi.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\shlwapi.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\shlwapi.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj.Filters b/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj.Filters deleted file mode 100644 index 1c5cadc5c..000000000 --- a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {76642063-E1CB-43C5-8493-5F651D92F60C} - - - h;hpp;hxx;hm;inl;inc;xsd - {4AB44AAB-2BDE-4DA4-A128-40382366A9F5} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {005AFEBA-780E-49DC-BCB8-4163463DE6D5} - - - inf;inv;inx;mof;mc; - {FDF16DEE-FA54-49E3-BC76-FCFD47F8BF37} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/general/echo/umdfSocketEcho/Driver/connection.h b/general/echo/umdfSocketEcho/Driver/connection.h deleted file mode 100644 index 2b7e23c6a..000000000 --- a/general/echo/umdfSocketEcho/Driver/connection.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Connection.h - -Abstract: - - Header file for the socketecho connection class - -Environment: - - User mode only - - ---*/ -#pragma once - -class CConnection -{ -public: - CConnection(); - HRESULT Connect(IN IWDFDevice *pDevice); - VOID Close(); - HANDLE GetSocketHandle( ); - -private: - SOCKET m_socket; -}; - diff --git a/general/echo/umdfSocketEcho/Driver/device.cpp b/general/echo/umdfSocketEcho/Driver/device.cpp deleted file mode 100644 index 9c3e4db1a..000000000 --- a/general/echo/umdfSocketEcho/Driver/device.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF socketecho sample - driver's device callback object. - - It does not implement either of the PNP interfaces so once the device - is setup, it won't ever get any callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -const GUID GUID_DEVINTERFACE_SOCKETECHO = - {0xcdc35b6e, 0xbe4, 0x4936, { 0xbf, 0x5f, 0x55, 0x37, 0x38, 0xa, 0x7c, 0x1a }}; - - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver* FxDriver, - _In_ IWDFDeviceInitialize* FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - FxDriver - IWDF Driver for this device. - - Return Value: - - status. - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION, "%!FUNC!"); - - CComPtr fxDevice; - HRESULT hr; - BOOL bFilter = FALSE; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // Set the locking model - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // Mark filter if we are a filter - // - - if (bFilter) - { - FxDeviceInit->SetFilter(); - } - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - CComPtr pUnk; - HRESULT hrQI = this->QueryInterface(__uuidof(IUnknown),(void**)&pUnk); - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - hr = FxDriver->CreateDevice(FxDeviceInit, pUnk, &fxDevice); - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - None - - Return Value: - - status - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION, "%!FUNC!"); - - HRESULT hr; - CComObject * defaultQueue = NULL; - - // - // Create a new instance of our queue callback object - // - hr = CComObject::CreateInstance(&defaultQueue); - - if (SUCCEEDED(hr)) - { - defaultQueue->AddRef(); - hr = defaultQueue->Initialize(this); - } - - if (SUCCEEDED(hr)) - { - hr = defaultQueue->Configure(); - } - - // - // Create and Enable Device Interface for this device. - // - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_SOCKETECHO, - NULL); - } - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->AssignDeviceInterfaceState(&GUID_DEVINTERFACE_SOCKETECHO, - NULL, - TRUE); - } - - if (SUCCEEDED(hr)) - { - hr = ReadAndAssignPropertyStoreValue(); - } - - // - // Release the reference we took on the queue callback object. - // The framework took its own references on the object's callback interfaces - // when we called m_FxDevice->CreateIoQueue, and will manage the object's lifetime. - // - SAFE_RELEASE(defaultQueue); - - return hr; -} - -STDMETHODIMP_(void) -CMyDevice::OnCloseFile( - _In_ IWDFFile* pWdfFileObject - ) -/*++ - - Routine Description: - - This method is called when an app closes the file handle to this device. - This will free the context memory associated with this file object, close - the connection object associated with this file object and delete the file - handle i/o target object associated with this file object. - - Arguments: - - pWdfFileObject - the framework file object for which close is handled. - - Return Value: - - None - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION, "%!FUNC!"); - - HRESULT hr = S_OK ; - FileContext *pContext = NULL; - - hr = pWdfFileObject->RetrieveContext((void**)&pContext); - - if (SUCCEEDED(hr) && (pContext != NULL ) ) - { - pContext->pConnection->Close(); - pContext->pFileTarget->DeleteWdfObject(); - - delete pContext->pConnection; - delete pContext; - } - - return ; -} - - -STDMETHODIMP_(void) -CMyDevice::OnCleanupFile( - _In_ IWDFFile* pWdfFileObject - ) -/*++ - - Routine Description: - - This method is when app with open handle device terminates. - - Arguments: - - pWdfFileObject - the framework file object for which close is handled. - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfFileObject); -} - -STDMETHODIMP_(void) -CMyDevice::OnCleanup( - _In_ IWDFObject* pWdfObject - ) -/*++ - - Routine Description: - - This device callback method is invoked by the framework when the WdfObject - is about to be released by the framework. This will free the context memory - associated with the device object. - - Arguments: - - pWdfObject - the framework device object for which OnCleanup. - - Return Value: - - None - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION, "%!FUNC!"); - - HRESULT hr ; - DeviceContext *pContext = NULL; - - WUDF_SAMPLE_DRIVER_ASSERT(pWdfObject == m_FxDevice); - - hr = pWdfObject->RetrieveContext((void**)&pContext); - - if (SUCCEEDED(hr) && (pContext != NULL)) - { - // hostStr is allocated through StrDup, and thus need be freed through LocalFree - // - if (pContext->hostStr != NULL) - { - LocalFree( pContext->hostStr ); - } - - if (pContext->portStr != NULL) - { - LocalFree( pContext->portStr ); - } - - delete pContext; - } -// -//CMyDevice has a reference to framework device object via m_Device. -//Framework device object has a reference to CMyDevice object via the callbacks. -//This leads to circular reference and both the objects can't be destroyed until this circular reference is broken. -//To break the circular reference we release the reference to the framework device object here in OnCleanup. - - m_FxDevice = NULL; -} - -HRESULT -CMyDevice::ReadAndAssignPropertyStoreValue( - VOID - ) -/*++ - - Routine Description: - Helper function for reading property store values and storing them in the - device level context. - - Arguments: - - pWdfFileObject - the framework file object for which close is handled. - - Return Value: - - None - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION, "%!FUNC!"); - - CComPtr pPropStore; - WDF_PROPERTY_STORE_DISPOSITION disposition; - PROPVARIANT val; - HRESULT hr ; - - PropVariantInit(&val); - - DeviceContext *pContext = new DeviceContext; - if (pContext == NULL) - { - hr = E_OUTOFMEMORY; - Trace(TRACE_LEVEL_ERROR, - L"ERROR: Could not create device context object %!hresult!", - hr); - - goto CleanUp; - } - - pContext->hostStr = NULL; - pContext->portStr = NULL; - - // - // Retreive property store for reading drivers custom settings as specified - // in the INF - // - hr = m_FxDevice->RetrieveDevicePropertyStore(L"SocketEcho", - WdfPropertyStoreNormal, - &pPropStore, - &disposition); - if (FAILED(hr)) - { - Trace(TRACE_LEVEL_ERROR, - "Failed to retrieve device property store for reading custom " - "settings as specified in the INF %!hresult!", - hr); - - goto CleanUp; - } - - // - // Get the key for this device with Named value "host" - // - hr = pPropStore->GetNamedValue(L"Host", &val); - if (FAILED(hr)) - { - Trace(TRACE_LEVEL_ERROR, - "Failed to get \"Host\" key value %!hresult!", - hr); - - goto CleanUp; - } - - if (val.vt != VT_LPWSTR) - { - hr = HRESULT_FROM_WIN32(ERROR_BAD_CONFIGURATION); - Trace(TRACE_LEVEL_ERROR, - "Unexpected string format for value in \"Host\" key %!hresult!", - hr); - - goto CleanUp; - } - - pContext->hostStr = StrDup(val.pwszVal); - - // - // Clear property variant for reading next key - // - PropVariantClear(&val); - - // - // Get the key for this device with Named value "Port" - // - hr = pPropStore->GetNamedValue(L"Port", &val); - if (FAILED(hr)) - { - Trace(TRACE_LEVEL_ERROR, - "Failed to get \"Port\" key value %!hresult!", - hr); - - goto CleanUp; - } - - if (val.vt != VT_LPWSTR) - { - hr = HRESULT_FROM_WIN32(ERROR_BAD_CONFIGURATION); - Trace(TRACE_LEVEL_ERROR, - "Unexpected string format for value in \"Port\" key %!hresult!", - hr); - - goto CleanUp; - } - - pContext->portStr = StrDup(val.pwszVal); - - hr = m_FxDevice->AssignContext(NULL, (void*)pContext); - if (FAILED(hr)) - { - Trace(TRACE_LEVEL_ERROR, - "Failed to assign property store value to device %!hresult!", - hr); - - // - // Fall through to clean up and exit ... - // - } - -CleanUp: - - PropVariantClear(&val); - - if (FAILED(hr)) - { - if (pContext != NULL) - { - // hostStr is allocated through StrDup, and thus need be freed through LocalFree - // - if (pContext->hostStr != NULL) - { - LocalFree( pContext->hostStr ); - } - - if (pContext->portStr != NULL) - { - LocalFree( pContext->portStr ); - } - - delete pContext; - } - } - - return hr; -} - diff --git a/general/echo/umdfSocketEcho/Driver/device.h b/general/echo/umdfSocketEcho/Driver/device.h deleted file mode 100644 index 176f10e63..000000000 --- a/general/echo/umdfSocketEcho/Driver/device.h +++ /dev/null @@ -1,70 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the iotrace driver. -// - -class ATL_NO_VTABLE CMyDevice : - public CComObjectRootEx, - public IFileCallbackCleanup, - public IFileCallbackClose, - public IObjectCleanup -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyDevice) - -BEGIN_COM_MAP(CMyDevice) - COM_INTERFACE_ENTRY(IFileCallbackCleanup) - COM_INTERFACE_ENTRY(IFileCallbackClose) - COM_INTERFACE_ENTRY(IObjectCleanup) -END_COM_MAP() - -public: - - //IFileCallbackCleanup - STDMETHOD_(void,OnCleanupFile)(_In_ IWDFFile* pWdfFileObject); - //IFileCallbackClose - STDMETHOD_(void,OnCloseFile)(_In_ IWDFFile* pWdfFileObject); - //IObjectCleanup - STDMETHOD_(void,OnCleanup)(_In_ IWDFObject* pWdfObject); - -public: - - STDMETHOD(Initialize)(_In_ IWDFDriver* pWdfDriver, _In_ IWDFDeviceInitialize* pWdfDeviceInit); - - HRESULT - Configure( - ); - - IWDFDevice * - GetFxDevice( - ) - { - return m_FxDevice; - } - -private: - CComPtr m_FxDevice; - HRESULT ReadAndAssignPropertyStoreValue(); - -}; diff --git a/general/echo/umdfSocketEcho/Driver/devicecontext.h b/general/echo/umdfSocketEcho/Driver/devicecontext.h deleted file mode 100644 index 2bf10d2e9..000000000 --- a/general/echo/umdfSocketEcho/Driver/devicecontext.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - devicecontext.h - -Abstract: - - This header file defines the structure type for device context associated with the device object - -Environment: - - user mode only - -Revision History: - ---*/ - - -#pragma once - - -typedef struct _DeviceContext -{ - PWSTR hostStr; - - PWSTR portStr; - -}DeviceContext; - diff --git a/general/echo/umdfSocketEcho/Driver/dllsup.cpp b/general/echo/umdfSocketEcho/Driver/dllsup.cpp deleted file mode 100644 index 5ec3eb331..000000000 --- a/general/echo/umdfSocketEcho/Driver/dllsup.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Socktecho Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the socktecho uses - L"Microsoft\\UMDF\\Socketecho" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -class CSocketEchoModule : public CAtlDllModuleT< CSocketEchoModule > -{ -}; - - -OBJECT_ENTRY_AUTO(CLSID_MyDriverCoClass, CMyDriver) - - -CSocketEchoModule _AtlModule; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID Reserved - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - UNREFERENCED_PARAMETER( ModuleHandle ); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return _AtlModule.DllMain(Reason, Reserved); -; -} - -_Check_return_ -STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv) -{ - return _AtlModule.DllGetClassObject(rclsid, riid, ppv); -} diff --git a/general/echo/umdfSocketEcho/Driver/driver.cpp b/general/echo/umdfSocketEcho/Driver/driver.cpp deleted file mode 100644 index 4f93691c0..000000000 --- a/general/echo/umdfSocketEcho/Driver/driver.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Socketecho Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -STDMETHODIMP -CMyDriver::OnInitialize( - _In_ IWDFDriver* pWdfDriver - ) - - -/*++ - - Routine Description: - - This routine is invoked by the framework at driver load . - This method will invoke the Winsock Library for using - Winsock API in this driver. - - Arguments: - - pWdfDriver - Framework driver object - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ - -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - UNREFERENCED_PARAMETER(pWdfDriver); - - WORD sockVersion; - WSADATA wsaData; - - sockVersion = MAKEWORD(2, 0); - - int result = WSAStartup(sockVersion, &wsaData); - - if (result != 0) - { - DWORD err = WSAGetLastError(); - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to initialize Winsock 2.0 %!winerr!", - err - ); - return HRESULT_FROM_WIN32(err); - } - - return S_OK; -} - -STDMETHODIMP_(void) -CMyDriver::OnDeinitialize( - _In_ IWDFDriver* pWdfDriver - ) - -/*++ - Routine Description: - - The FX invokes this method when it unloads the driver. - This routine will Cleanup Winsock library - - Arguments: - - pWdfDriver - the Fx driver object. - - Return Value: - - None - - - --*/ - -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - UNREFERENCED_PARAMETER(pWdfDriver); - - WSACleanup(); -} - -STDMETHODIMP -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - Trace( - TRACE_LEVEL_INFORMATION, - "%!FUNC!" - ); - - HRESULT hr; - - CComObject * device = NULL; - - // - // Create a new instance of our device callback object - // - - hr = CComObject::CreateInstance(&device); - - if (SUCCEEDED(hr)) - { - device->AddRef(); - hr = device->Initialize(FxWdfDriver, FxDeviceInit); - } - - // - // If that succeeded then call the device's configure method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference we took on the device callback object. - // The framework took its own references on the object's callback interfaces - // when we called FxWdfDriver->CreateDevice, and will manage the object's lifetime. - // - SAFE_RELEASE(device); - - return hr; -} diff --git a/general/echo/umdfSocketEcho/Driver/driver.h b/general/echo/umdfSocketEcho/Driver/driver.h deleted file mode 100644 index 6affa20fb..000000000 --- a/general/echo/umdfSocketEcho/Driver/driver.h +++ /dev/null @@ -1,53 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Socketecho sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the socktecho sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -extern const GUID CLSID_MyDriverCoClass; - -class ATL_NO_VTABLE CMyDriver : - public CComObjectRootEx, - public CComCoClass, - public IDriverEntry -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyDriver) - -DECLARE_CLASSFACTORY(); - -DECLARE_NO_REGISTRY(); - -BEGIN_COM_MAP(CMyDriver) - COM_INTERFACE_ENTRY(IDriverEntry) -END_COM_MAP() - -public: - // IDriverEntry - STDMETHOD(OnInitialize)(_In_ IWDFDriver* pWdfDriver); - STDMETHOD(OnDeviceAdd)(_In_ IWDFDriver* pWdfDriver, _In_ IWDFDeviceInitialize* pWdfDeviceInit); - STDMETHOD_(void,OnDeinitialize)(_In_ IWDFDriver* pWdfDriver); -}; - diff --git a/general/echo/umdfSocketEcho/Driver/exports.def b/general/echo/umdfSocketEcho/Driver/exports.def deleted file mode 100644 index 2c0b7d49b..000000000 --- a/general/echo/umdfSocketEcho/Driver/exports.def +++ /dev/null @@ -1,6 +0,0 @@ -; Socketecho.def : Declares the module parameters. - -LIBRARY "SocketEcho" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/general/echo/umdfSocketEcho/Driver/internal.h b/general/echo/umdfSocketEcho/Driver/internal.h deleted file mode 100644 index a78754688..000000000 --- a/general/echo/umdfSocketEcho/Driver/internal.h +++ /dev/null @@ -1,117 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Socketecho sample - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the winsock headers before any other windows headers. -// -#include -#include - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Define the tracing flags. -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (64316518,DFE2,42B6,8786,4995E5EC435), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\SocketEcho" -#define MYDRIVER_CLASS_ID { 0x83B87D35, 0x76B8, 0x4920, {0xB4, 0x3C, 0x3B, 0xDE, 0x6B, 0x0E, 0xC5, 0xB8} } - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} -#endif - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_SAMPLE_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -// -// Include the type specific headers. -// -#include -#include - -#include "connection.h" -#include "filecontext.h" -#include "devicecontext.h" -#include "driver.h" -#include "device.h" -#include "queue.h" - -_Analysis_mode_(_Analysis_operator_new_null_) - diff --git a/general/echo/umdfSocketEcho/Exe/internal.h b/general/echo/umdfSocketEcho/Exe/internal.h deleted file mode 100644 index ff1cd863b..000000000 --- a/general/echo/umdfSocketEcho/Exe/internal.h +++ /dev/null @@ -1,18 +0,0 @@ -// internal.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#include -_Analysis_mode_(_Analysis_code_type_user_code_); -#include -#include -#include -#include -#include -#include -#include - -#include "socketechoserver.h" diff --git a/general/echo/umdfSocketEcho/Exe/socketechoserver.cpp b/general/echo/umdfSocketEcho/Exe/socketechoserver.cpp deleted file mode 100644 index bfe5f5467..000000000 --- a/general/echo/umdfSocketEcho/Exe/socketechoserver.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - socketserver.cpp - -Abstract: - - A simple socket server application that listens on a specified port and echoes back data - received. - -Environment: - - User Mode - ---*/ - -#include "internal.h" - - -DWORD -Run( - LPVOID lpThreadParameter - ) - /*++ - -Routine Description: - - This routine is invoked for each thread created for a new connection accepted by the server. - The rcv and send to socket happen in this thread routine. - - -Arguments: - - lpThreadParameter , The Thread parameter which contains socket information - -Return Value: - - Thread Exit Code - - ---*/ -{ - #define DeleteBufferExitThread(dwExitCode) \ - delete[] buffer; \ - buffer = NULL; \ - ExitThread(dwExitCode); - - #define DeleteBufferReturn(dwExitCode) \ - delete[] buffer; \ - buffer = NULL; \ - return dwExitCode; - - int count =0; - - char *buffer = new char[DATA_LENGTH]; - if (NULL == buffer) - { - ExitThread(1); - } - - DWORD Event; - - // - // Look at socket information from thread arg. - // - - - CEchoServer *pThreadData = (CEchoServer*)lpThreadParameter; - if (pThreadData==NULL) - { - DeleteBufferExitThread(1); - } - - SOCKET sClient = pThreadData->m_socket; - HANDLE NetworkEvent = pThreadData->m_NetworkEvent; - WSANETWORKEVENTS NetworkEvents; - printf("Client Start: 0x%Ix\n", sClient); - int actual = 0; - for(;;) - { - if ((Event = WSAWaitForMultipleEvents( - 1, - &NetworkEvent, - FALSE, - WSA_INFINITE, - FALSE)) == WSA_WAIT_FAILED) - { - printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError()); - DeleteBufferReturn(0); - } - - if (WSAEnumNetworkEvents(sClient ,NetworkEvent, &NetworkEvents) == SOCKET_ERROR) - { - printf("WSAEnumNetworkEvents failed with error %d\n", WSAGetLastError()); - DeleteBufferReturn(0); - } - - if (NetworkEvents.lNetworkEvents & FD_READ) - { - if (NetworkEvents.lNetworkEvents & FD_READ && NetworkEvents.iErrorCode[FD_READ_BIT] != 0) - { - printf("FD_READ failed with error %d\n", NetworkEvents.iErrorCode[FD_READ_BIT]); - } - else - { - - actual = recv(sClient,buffer,DATA_LENGTH*sizeof(char),0); - // - // socket connection has been reset ,so bail out . - // - if (actual == 0 || actual == WSAECONNRESET ) - { - printf(" Could not get data , Error : 0x%lx \n",WSAGetLastError()); - break; // socket shut-down - - } - printf("FD_READ read buffer on client 0x%Ix with length %d \n",sClient,actual); - count = send(sClient, (const char*)buffer,actual,0); - if ( count == SOCKET_ERROR ) - { - if ( WSAGetLastError()== WSAEWOULDBLOCK ) - { - printf(" Could not send data as resource is unavaliable , do not retry until next Write event \n"); - } - else - { - printf(" Could not send data , Error : 0x%lx \n",WSAGetLastError()); - break; - } - } - else - { - printf("FD_WRITE write buffer on client 0x%Ix with length %d \n",sClient,count); - } - } - } - // - // if there is a write network event and there is data to write , write that - // - if (NetworkEvents.lNetworkEvents & FD_WRITE) - { - if (NetworkEvents.lNetworkEvents & FD_WRITE && NetworkEvents.iErrorCode[FD_WRITE_BIT] != 0) - { - printf("FD_WRITE failed with error %d\n", NetworkEvents.iErrorCode[FD_WRITE_BIT]); - } - else - { - count = send(sClient, (const char*)buffer,actual,0); - if ( count == SOCKET_ERROR ) - { - if ( WSAGetLastError()== WSAEWOULDBLOCK ) - { - printf(" Could not send data as resource is unavaliable , do not retry until next Write event "); - } - else - { - printf(" Could not send data , Error : 0x%lx \n",WSAGetLastError()); - break; - } - } - else - { - printf("FD_WRITE write buffer on client 0x%Ix with length %d \n",sClient,count); - } - actual = 0; - } - } - if (NetworkEvents.lNetworkEvents & FD_CLOSE) - { - shutdown(sClient,FD_READ|FD_WRITE); - printf(" recived a close from client : 0x%Ix \n",sClient); - closesocket(sClient); - DeleteBufferExitThread(0); - } - } - - DeleteBufferReturn(1); - -} - -CEchoServer::CEchoServer( - SOCKET socketclient - ) -/*++ - -Routine Description: - - This is the constructor routine for CEchoServer class. This is called for each instance of new - connection accepted by the server . - -Arguments: - - Socket received from the accept - -Return Value: - - None . - ---*/ -{ - m_socket = socketclient; - m_NetworkEvent = WSACreateEvent(); - printf("socket created : 0x%Ix \n", m_socket); - -} - -void -CEchoServer::Start() -/*++ - -Routine Description: - - This routine is to Start the thread which will rcv and send the data recieved on this instance of socket connection. - - -Arguments: - - None. - -Return Value: - - None. ---*/ -{ - - - if(WSAEventSelect( - m_socket, - m_NetworkEvent, - FD_READ|FD_WRITE|FD_CLOSE)== SOCKET_ERROR) - { - printf("Error in Event Select,Cannot start Server thread for this socket \n"); - closesocket(m_socket); - goto Exit; - } -// -// Create thread to read/write data to this socket -// - - HANDLE hRunThread = CreateThread( - NULL, // Default Security Attrib. - 0, // Initial Stack Size, - (LPTHREAD_START_ROUTINE) Run, // Thread Func - this, // Arg to Thread Func. - 0, // Creation Flags - NULL // Don't need the Thread Id. - ); - if (NULL == hRunThread) - { - printf(" Could not create socket server run thread : 0x%lx \n", GetLastError()); - closesocket(m_socket); - goto Exit; - } - -Exit: - - return ; - } - -void -SocketServerMain( - _In_ unsigned short uPort - ) -/*++ - -Routine Description: - - This routine is the main entry for the app when the app is configured to - be a socket server. - It creates a a listening socket for incoming conenctions. - - -Arguments: - - uPort - Port Number that the socket server binds to - -Return Value: - - None. ---*/ -{ - - - SOCKET ListenSocket; - int iResult; - #pragma warning( suppress: 24002 ) // suppress warning for IPv6 ,currently IPv4 specific - sockaddr_in service ; - - // Initialize Winsock 2.2 - WSADATA wsaData; - iResult = WSAStartup(MAKEWORD(2,2), &wsaData); - if ( NO_ERROR != iResult ) - { - printf("Error at WSAStartup() \n"); - goto Exit; - } - // - // Create a SOCKET for listening for incoming connection requests. - // - ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if ( INVALID_SOCKET == ListenSocket) - { - printf("Error at socket(): %ld\n ", WSAGetLastError()); - goto Cleanup; - } - // The sockaddr_in structure specifies the address family, - // IP address, and port for the socket that is being bound. - service.sin_family = AF_INET; - // - // Suppress overflow warning. - // inet_pton is annotated to write sizeof(IN6_ADDR) bytes to pAddrBuf, - // but it only writes sizeof(IN_ADDR) bytes when Family is AF_INET (IPv4). - // https://msdn.microsoft.com/en-us/library/windows/desktop/cc805844(v=vs.85).aspx - // - #pragma warning( suppress: 26000 ) - iResult = inet_pton(AF_INET, "127.0.0.1", &service.sin_addr); - if (iResult != 1) - { - printf("Error at inet_pton(): %ld\n ", WSAGetLastError()); - closesocket(ListenSocket); - goto Cleanup; - } - service.sin_port = htons(uPort); - if (SOCKET_ERROR == bind( - ListenSocket, - (SOCKADDR*) &service, - sizeof(service) ) ) - { - printf("bind() failed. \n"); - closesocket(ListenSocket); - goto Cleanup; - } - - // - // Listen for incoming connection requests - // on the created socket upto MAX_CONNECTIONS - // - if ( SOCKET_ERROR == listen( - ListenSocket, - MAX_CONNECTIONS ) ) - { - printf("Error listening on socket.\n"); - } - printf("Listening on socket...\n"); - - // - // Set Socket RCVBUF and SNDBUF size to DATA_LENGTH , so large requests are not fragmented . - // - int iOptVal; - int iOptLen = sizeof(int); - - if (getsockopt(ListenSocket, SOL_SOCKET, SO_RCVBUF, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) - { - printf("SO_RCVBUF value: %ld\n", iOptVal); - } - iOptVal = DATA_LENGTH; - iOptLen = sizeof(int); - if (setsockopt(ListenSocket, SOL_SOCKET, SO_RCVBUF, (char*)&iOptVal, iOptLen) != SOCKET_ERROR) - { - printf("Set SO_RCVBUF: ON\n"); - } - iOptLen = sizeof(int); - if (getsockopt(ListenSocket, SOL_SOCKET, SO_RCVBUF, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) - { - printf("SO_RCVBUF Value: %ld\n", iOptVal); - } - iOptLen = sizeof(int); - if (getsockopt(ListenSocket, SOL_SOCKET, SO_SNDBUF, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) - { - printf("SO_SNDBUF value: %ld\n", iOptVal); - } - iOptVal = DATA_LENGTH; - iOptLen = sizeof(int); - if (setsockopt(ListenSocket, SOL_SOCKET, SO_SNDBUF, (char*)&iOptVal, iOptLen) != SOCKET_ERROR) - { - printf("Set SO_SNDBUF: ON\n"); - } - iOptLen = sizeof(int); - if (getsockopt(ListenSocket, SOL_SOCKET, SO_SNDBUF, (char*)&iOptVal, &iOptLen) != SOCKET_ERROR) - { - printf("SO_SNDBUF Value: %ld\n", iOptVal); - } - -// -// Loop the server to start accepting connections from clients on this socket -// - - for(;;) - { - CEchoServer *client = new CEchoServer(accept(ListenSocket,NULL,NULL)); - - if (client) - { - printf("Client connected.\n"); - client->Start(); // Start receiving/sending data on the socket - } - } - -Cleanup: - // - // Invoke Winsock Cleanup - // - - WSACleanup(); - - Exit: - return; - -} -void -Usage() - -/*++ - -Routine Description: - - This routine is invoked to display the usage of this application - -Arguments: - - None. - -Return Value: - - None . ---*/ - -{ - printf("\n\n Usage: \n"); - printf(" ------ \n\n"); - printf(" socketechoapp Display Usage \n"); - printf(" socketechoapp -h Display Usage\n"); - printf(" socketechoapp -p Start the app as server listening on default port\n"); - printf(" socketechoapp -p [port#] Start the app as server listening on this port \n"); - - - -} - - -/* */ -void __cdecl -main( - _In_ int argc, - _In_reads_(argc) char* argv[] - ) - -/*++ - -Routine Description: - - - -Arguments: - - None. - -Return Value: - - None. ---*/ -{ - unsigned short argIndex = 1 ; - unsigned short uPort = DEFAULT_PORT_ADDRESS ; - - - if (argc < 2) - { - Usage(); - goto Exit; - } - -// -// look at second arg and check for either -h which indicates user asked for help in Usage -// of this commandline -// - - if (!strcmp(*(argv+argIndex),"-h")) - { - Usage(); - goto Exit; - } -// -// check if its -p and proceed with otherwise show usage -// - else if (!strcmp(*(argv+argIndex),"-p")) - { - // - // look at third arg, which should be the port# - // - if ( ++argIndex < argc ) - { - uPort = (unsigned short)atoi(*(argv+(argIndex))); - } - SocketServerMain(uPort); - - } - else - { - Usage(); - goto Exit; - } - -Exit: - return; - -} - - diff --git a/general/echo/umdfSocketEcho/Exe/socketechoserver.h b/general/echo/umdfSocketEcho/Exe/socketechoserver.h deleted file mode 100644 index f71bc48b9..000000000 --- a/general/echo/umdfSocketEcho/Exe/socketechoserver.h +++ /dev/null @@ -1,48 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - sockechoserver.h - -Abstract: - - Header file for the socket server module of the socketecho application - -Environment: - - User mode only - ---*/ - -#pragma once - - -#define MAX_CONNECTIONS 5 -#define DEFAULT_PORT_ADDRESS 6000 -#define DATA_LENGTH 1024*40 - -void -SocketServerMain( - _In_ unsigned short uPort - ); - - // - // Class definition for CEchoServer Class - // -class CEchoServer -{ - - public: - - SOCKET m_socket; - HANDLE m_NetworkEvent; - - - - CEchoServer(SOCKET socketclient); - void Start(); - -}; - diff --git a/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj b/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj deleted file mode 100644 index e226bb5c9..000000000 --- a/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj +++ /dev/null @@ -1,190 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {70A0F94B-0D04-4AB4-A653-733AC0210EBC} - $(MSBuildProjectName) - Debug - Win32 - {0C41C62B-B1D0-4A46-B431-6DA1A153FDC0} - - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - - $(IntDir) - - - - - - - - - - - - - - - - socketechoserver - - - socketechoserver - - - socketechoserver - - - socketechoserver - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - - - %(AdditionalDependencies);user32.lib;Ws2_32.lib - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - - - %(AdditionalDependencies);user32.lib;Ws2_32.lib - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - - - %(AdditionalDependencies);user32.lib;Ws2_32.lib - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - - - %(AdditionalDependencies);user32.lib;Ws2_32.lib - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH) - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj.Filters b/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj.Filters deleted file mode 100644 index daed19de8..000000000 --- a/general/echo/umdfSocketEcho/Exe/socketechoserver.vcxproj.Filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {6F82EFE8-0818-4BAE-A52F-C72D9E63CAD6} - - - h;hpp;hxx;hm;inl;inc;xsd - {448C5D48-4FD2-4DA5-964C-3EF201A3ED31} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {439980EC-B0F0-45A7-AF18-E832E564F57D} - - - - - Source Files - - - \ No newline at end of file diff --git a/general/echo/umdfSocketEcho/README.md b/general/echo/umdfSocketEcho/README.md deleted file mode 100644 index d4a6077f0..000000000 --- a/general/echo/umdfSocketEcho/README.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -page_type: sample -description: "Demonstrates how to use UMDF version 1 to write a driver and demonstrates best practices." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# UMDF SocketEcho Sample (UMDF Version 1) - -The UMDF SocketEcho sample demonstrates how to use the User-Mode Driver Framework (UMDF) to write a driver and demonstrates best practices. - -This sample also demonstrates how to use a default parallel dispatch I/O queue, use a Microsoft Win32 dispatcher, and handle a socket handle by using a Win32 file I/O target. - -## Related technologies - -[User-Mode Driver Framework](https://docs.microsoft.com/windows-hardware/drivers/wdf/getting-started-with-umdf-version-2) - -## Code Tour - -This sample driver is a minimal driver that is intended to demonstrate how to use UMDF. It is not intended for use in a production environment. - -- **CMyDriver::OnInitialize** in **driver.cpp** is called by the framework when the driver loads. This method initiates use of the Winsock Library. - -- **CMyDriver::OnDeviceAdd** in **driver.cpp** is called by the framework to install the driver on a device stack. OnDeviceAdd creates a device callback object, and then calls IWDFDriver::CreateDevice to create an framework device object and to associate the device callback object with the framework device object. - -- **CMyQueue::OnCreateFile** in **queue.cpp** is called by the framework to create a socket connection, create a file i/o target that is associated with the socket handle for this connection, and store the socket handle in the file object context. - -## Installation - -In Visual Studio, you can press F5 to build the sample and then deploy it to a target machine. For more information, see [Deploying a Driver to a Test Computer](https://docs.microsoft.com/windows-hardware/drivers/develop/deploying-a-driver-to-a-test-computer). Alternatively, you can install the sample from the command line. - -To test this sample, you must have a test computer. This test computer can be a second computer or, if necessary, your development computer. - -To install the UMDF Echo sample driver from the command line, do the following: - -1. Copy the driver binary and the socketecho.inf file to a directory on your test computer (for example, C:\\ socketechoSample.) - -1. Copy the UMDF coinstaller, WUDFUpdate\_*MMmmmm*.dll, from the \\redist\\wdf\\\ directory to the same directory (for example, C:\\socketechoSample). - - > [!NOTE] - > You can obtain redistributable framework updates by downloading the *wdfcoinstaller.msi* package from [WDK 8 Redistributable Components](https://go.microsoft.com/fwlink/p/?LinkID=253170). This package performs a silent install into the directory of your Windows Driver Kit (WDK) installation. You will see no confirmation that the installation has completed. You can verify that the redistributables have been installed on top of the WDK by ensuring there is a redist\\wdf directory under the root directory of the WDK, %ProgramFiles(x86)%\\Windows Kits\\8.0. - -1. Navigate to the directory that contains the INF file and binaries (for example, cd /d c:\\socketechoSample), and run DevCon.exe as follows: - - `devcon.exe install socketecho.inf WUDF\\socketecho` - - You can find DevCon.exe in the \\tools directory of the WDK (for example, \\tools\\devcon\\i386\\devcon.exe). - -To update the socketecho driver after you make any changes, do the following: - -1. Increment the version number in the INF file. This change is not necessary, but it will help ensure that Plug and Play (PnP) selects your new driver as a better match for the device. - -1. Copy the updated driver binary and the socketecho.inf file to a directory on your test computer (for example, C:\\ socketechoSample.) - -1. Navigate to the directory that contains the INF file and binaries (for example, cd /d c:\\ socketechoSample), and run devcon.exe as follows: - - `devcon.exe update socketecho.inf WUDF\\socketecho` - -To test this sample drivers on a checked operating system that you have installed (in contrast to the standard retail installations), you must modify the INF file to use the checked version of the UMDF co-installer. That is, you must do the following: - -1. In the INX file, replace all occurrences of WudfUpdate\_*MMmmmm*.dll with WudfUpdate\_*MMmmmm*\_chk.dll. - -1. Copy the WudfUpdate\_*MMmmmm*\_chk.dll file from the \\redist\\wdf\\\ directory to your driver package instead of WudfUpdate\_*MMmmmm*.dll. - -1. If WdfCoinstaller*MMmmmm*.dll or WinUsbCoinstaller.dll is included in your driver package, repeat step 1 and step 2 for them. - -## Testing - -To test the SocketEcho driver, you can run socketechoserver.exe, which is built from the \\echo\\umdfSocketEcho\\Exe directory, and echoapp.exe, which is built from the Kernel-Mode Driver Framework (KMDF) samples in the \\echo\\kmdf directory. - -First, you must install the device as described earlier. Then, run socketechoserver.exe from a Command Prompt window. - -`D:\\\>socketechoserver -h` - -## Usage - -socketechoserver usage - -```cmd -D:\>socketechoserver -h - -socketechoserver -p Start the app as server listening on default port -socketechoserver -p [port\#] Start the app as server listening on this port - -D:\>socketechoserver -p - -Listening on socket... -``` - -In another Command Prompt window, run echoapp.exe. - -```cmd -D:\>echoapp - -DevicePath: \\\\?\\root\#sample\#0000\#{ e5e65b0c-82c8-4689-96d4-f77837971990} - -Opened device successfully - -512 Pattern Bytes Written successfully -512 Pattern Bytes Read successfully - -Pattern Verified successfully - -D:\>echoapp -Async - -DevicePath: \\?\root\#sample\#0000\#{cdc35b6e-0be4-4936-bf5f-5537380a7c1a} - -Opened device successfully - -Starting AsyncIo - -Number of bytes written by request number 0 is 1024 -Number of bytes read by request number 0 is 1024 -Number of bytes written by request number 1 is 1024 -Number of bytes read by request number 1 is 1024 -Number of bytes written by request number 2 is 1024 -Number of bytes read by request number 2 is 1024 -Number of bytes written by request number 3 is 1024 -Number of bytes read by request number 3 is 1024 -Number of bytes written by request number 4 is 1024 -Number of bytes read by request number 4 is 1024 -Number of bytes written by request number 5 is 1024 -Number of bytes read by request number 5 is 1024 -Number of bytes written by request number 6 is 1024 -Number of bytes read by request number 6 is 1024 -Number of bytes written by request number 7 is 1024 -Number of bytes read by request number 7 is 1024 -Number of bytes written by request number 8 is 1024 -Number of bytes read by request number 8 is 1024 -Number of bytes written by request number 9 is 1024 -Number of bytes read by request number 9 is 1024 -Number of bytes written by request number 10 is 1024 -Number of bytes read by request number 10 is 1024 -Number of bytes written by request number 11 is 1024 -... -``` - -> [!NOTE] -> Independent threads perform the reads and writes in the echo test application. As a result, the order of the output might not exactly match what you see in the preceding output example. - -## File Manifest - -**Dllsup.cpp**: The DLL support code that provides the DLL's entry point and the single required export (DllGetClassObject). diff --git a/general/echo/umdfSocketEcho/Test.txt b/general/echo/umdfSocketEcho/Test.txt deleted file mode 100644 index 5ae50e29f..000000000 --- a/general/echo/umdfSocketEcho/Test.txt +++ /dev/null @@ -1 +0,0 @@ -Testing git hub actions. diff --git a/general/echo/umdfSocketEcho/umdfsocketecho.sln b/general/echo/umdfSocketEcho/umdfsocketecho.sln deleted file mode 100644 index 775550f57..000000000 --- a/general/echo/umdfSocketEcho/umdfsocketecho.sln +++ /dev/null @@ -1,46 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Driver", "Driver", "{5926AA26-ED89-4B86-ADD3-6415A17996DF}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{17E8DD65-7DC7-4D59-96A0-52A20C036403}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SocketEcho", "Driver\SocketEcho.vcxproj", "{353E2F22-BD87-47F3-A211-90DE8D583D26}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "socketechoserver", "Exe\socketechoserver.vcxproj", "{70A0F94B-0D04-4AB4-A653-733AC0210EBC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Debug|Win32.ActiveCfg = Debug|Win32 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Debug|Win32.Build.0 = Debug|Win32 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Release|Win32.ActiveCfg = Release|Win32 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Release|Win32.Build.0 = Release|Win32 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Debug|x64.ActiveCfg = Debug|x64 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Debug|x64.Build.0 = Debug|x64 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Release|x64.ActiveCfg = Release|x64 - {353E2F22-BD87-47F3-A211-90DE8D583D26}.Release|x64.Build.0 = Release|x64 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Debug|Win32.ActiveCfg = Debug|Win32 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Debug|Win32.Build.0 = Debug|Win32 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Release|Win32.ActiveCfg = Release|Win32 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Release|Win32.Build.0 = Release|Win32 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Debug|x64.ActiveCfg = Debug|x64 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Debug|x64.Build.0 = Debug|x64 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Release|x64.ActiveCfg = Release|x64 - {70A0F94B-0D04-4AB4-A653-733AC0210EBC}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {353E2F22-BD87-47F3-A211-90DE8D583D26} = {5926AA26-ED89-4B86-ADD3-6415A17996DF} - {70A0F94B-0D04-4AB4-A653-733AC0210EBC} = {17E8DD65-7DC7-4D59-96A0-52A20C036403} - EndGlobalSection -EndGlobal diff --git a/general/event/exe/event.vcxproj b/general/event/exe/event.vcxproj index 430000f46..03a276bec 100644 --- a/general/event/exe/event.vcxproj +++ b/general/event/exe/event.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/event/wdm/event.vcxproj b/general/event/wdm/event.vcxproj index b82f72b05..cf701e3cc 100644 --- a/general/event/wdm/event.vcxproj +++ b/general/event/wdm/event.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/ioctl/kmdf/exe/nonpnpapp.vcxproj b/general/ioctl/kmdf/exe/nonpnpapp.vcxproj index aff8e836a..0fd29fb5a 100644 --- a/general/ioctl/kmdf/exe/nonpnpapp.vcxproj +++ b/general/ioctl/kmdf/exe/nonpnpapp.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/ioctl/kmdf/sys/nonpnp.vcxproj b/general/ioctl/kmdf/sys/nonpnp.vcxproj index 90a56bcf3..6050a8254 100644 --- a/general/ioctl/kmdf/sys/nonpnp.vcxproj +++ b/general/ioctl/kmdf/sys/nonpnp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/ioctl/wdm/exe/ioctlapp.vcxproj b/general/ioctl/wdm/exe/ioctlapp.vcxproj index 226320d9c..582af4ca2 100644 --- a/general/ioctl/wdm/exe/ioctlapp.vcxproj +++ b/general/ioctl/wdm/exe/ioctlapp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/ioctl/wdm/sys/sioctl.vcxproj b/general/ioctl/wdm/sys/sioctl.vcxproj index 66c2fe71c..8781185f9 100644 --- a/general/ioctl/wdm/sys/sioctl.vcxproj +++ b/general/ioctl/wdm/sys/sioctl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/obcallback/control/ObCallbackTestCtrl.vcxproj b/general/obcallback/control/ObCallbackTestCtrl.vcxproj index 0f407b4f5..80b7eba82 100644 --- a/general/obcallback/control/ObCallbackTestCtrl.vcxproj +++ b/general/obcallback/control/ObCallbackTestCtrl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/obcallback/driver/ObCallbackTest.vcxproj b/general/obcallback/driver/ObCallbackTest.vcxproj index 4f5c92d61..28b3f60e5 100644 --- a/general/obcallback/driver/ObCallbackTest.vcxproj +++ b/general/obcallback/driver/ObCallbackTest.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/pcidrv/kmdf/HW/PCIDRV.vcxproj b/general/pcidrv/kmdf/HW/PCIDRV.vcxproj index fe456c2c3..11a432bb0 100644 --- a/general/pcidrv/kmdf/HW/PCIDRV.vcxproj +++ b/general/pcidrv/kmdf/HW/PCIDRV.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/pcidrv/kmdf/genpci.inx b/general/pcidrv/kmdf/genpci.inx index b10b695ab..f85814145 100644 Binary files a/general/pcidrv/kmdf/genpci.inx and b/general/pcidrv/kmdf/genpci.inx differ diff --git a/general/perfcounters/kcs/kcs.vcxproj b/general/perfcounters/kcs/kcs.vcxproj index 6afa9d83a..ae15fb1c9 100644 --- a/general/perfcounters/kcs/kcs.vcxproj +++ b/general/perfcounters/kcs/kcs.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/registry/regfltr/exe/regctrl.vcxproj b/general/registry/regfltr/exe/regctrl.vcxproj index 35c4e0518..61ba2e53e 100644 --- a/general/registry/regfltr/exe/regctrl.vcxproj +++ b/general/registry/regfltr/exe/regctrl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/registry/regfltr/sys/regfltr.vcxproj b/general/registry/regfltr/sys/regfltr.vcxproj index b50d19724..1c08f5954 100644 --- a/general/registry/regfltr/sys/regfltr.vcxproj +++ b/general/registry/regfltr/sys/regfltr.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/Package/package.VcxProj b/general/toaster/toastDrv/Package/package.VcxProj index 572e08b5b..85af0a9a4 100644 --- a/general/toaster/toastDrv/Package/package.VcxProj +++ b/general/toaster/toastDrv/Package/package.VcxProj @@ -40,12 +40,6 @@ {D15FD911-F2DA-4644-8142-6D22756AD287} - - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F} - - - {F575419D-099B-4DA0-B80C-88D766DD7542} - WindowsKernelModeDriver10.0 diff --git a/general/toaster/toastDrv/README.md b/general/toaster/toastDrv/README.md index fc84c39d8..4c5b52bc6 100644 --- a/general/toaster/toastDrv/README.md +++ b/general/toaster/toastDrv/README.md @@ -10,7 +10,7 @@ products: # Toaster Sample Driver -The Toaster collection is an iterative series of samples that demonstrate fundamental aspects of Windows driver development for both Kernel-Mode Driver Framework (KMDF) and User-Mode Driver Framework (UMDF) version 1. +The Toaster collection is an iterative series of samples that demonstrate fundamental aspects of Windows driver development for both Kernel-Mode Driver Framework (KMDF). All the samples work with a hypothetical toaster bus, over which toaster devices can be connected to a PC. @@ -76,89 +76,3 @@ As an alternative to building the Toaster sample in Visual Studio, you can build For more information about using MSBuild to build a driver package, see [Building a Driver with Visual Studio and the WDK](https://docs.microsoft.com/windows-hardware/drivers/develop/building-a-driver). -## UMDF Toaster File Manifest - -### WUDFToaster.idl - -Component Interface file - -### WUDFToaster.cpp - -DLL Support code - provides the DLL's entry point as well as the DllGetClassObject export. - -### WUDFToaster.def - -This file lists the functions that the driver DLL exports. - -### stdafx.h - -This is the main header file for the sample driver. - -### driver.cpp and driver.h (WUDFToaster) - -Definition and implementation of the IDriverEntry callbacks in CDriver class. - -### device.cpp and device.h (WUDFToaster) - -Definition and implementation of various interfaces and their callbacks in CDevice class. Add your PnP and Power interfaces specific for your hardware. - -### queue.cpp and queue.h - -Definition and implementation of the base queue callback class (CQueue). IQueueCallbackDevicekIoControl, IQueueCallbackRead and IQueueCallBackWrite callbacks are implemented to handle I/O control requests. - -### WUDFToaster.rc - -This file defines resource information for the WUDF Toaster sample driver. - -### WUDFToaster.inf - -Sample INF for installing the sample WUDF Toaster driver under the Toaster class of devices. - -### WUDFtoaster.ctl, internal.h - -This file lists the WPP trace control GUID(s) for the sample driver. This file can be used with the tracelog command's -guid flag to enable the collection of these trace events within an established trace session. -These GUIDs must remain in sync with the trace control guids defined in internal.h. - -## Toastmon File Manifest - -### comsup.cpp and comsup.h - -Boilerplate COM Support code - specifically base classes which provide implementations for the standard COM interfaces IUnknown and IClassFactory which are used throughout the sample. -The implementation of IClassFactory is designed to create instances of the CMyDriver class. If you should change the name of your base driver class, you would also need to modify this file. - -### dllsup.cpp - -Boilerplate DLL Support code - provides the DLL's entry point as well as the single required export (DllGetClassObject). -These depend on comsup.cpp to perform the necessary class creation. - -### exports.def - -This file lists the functions that the driver DLL exports. - -### internal.h - -This is the main header file for the ToastMon driver - -### driver.cpp and driver.h (Toastmon) - -Definition and implementation of the driver callback class for the ToastMon sample. - -### device.cpp and device.h (Toastmon) - -Definition and implementation of the device callback class for the ToastMon sample. This is mostly boilerplate, but also registers for RemoteInterface Arrival notifications. When a RemoteInterface arrival callback occurs, it calls CreateRemoteInterface and creates a CMyRemoteTarget callback object to handle I/O on that RemoteInterface. - -### RemoteTarget.cpp and RemoteTarget.h - -Definition and implementation of the remote target callback class for the ToastMon sample. - -### list.h - -Doubly-linked-list code - -### ToastMon.rc - -This file defines resource information for the ToastMon sample driver. - -### UMDFToastMon.inf - -Sample INF for installing the Skeleton driver to control a root enumerated device with a hardware ID of UMDFSamples\\ToastMon diff --git a/general/toaster/toastDrv/exe/enum/Enum.vcxproj b/general/toaster/toastDrv/exe/enum/Enum.vcxproj index 3638bd18d..3b8bcbb62 100644 --- a/general/toaster/toastDrv/exe/enum/Enum.vcxproj +++ b/general/toaster/toastDrv/exe/enum/Enum.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/toastDrv/exe/notify/notify.c b/general/toaster/toastDrv/exe/notify/notify.c index 3362ce3d9..15e5a615b 100644 --- a/general/toaster/toastDrv/exe/notify/notify.c +++ b/general/toaster/toastDrv/exe/notify/notify.c @@ -35,7 +35,7 @@ Revision History: // Annotation to indicate to prefast that this is nondriver user-mode code. // #include -_Analysis_mode_(_Analysis_code_type_user_code_) +_Analysis_mode_(_Analysis_code_type_user_code_) #include #include @@ -494,7 +494,7 @@ HandleDeviceInterfaceChange( if(!GetDeviceDescription(dip->dbcc_name, - (PBYTE)deviceInfo->DeviceName, + deviceInfo->DeviceName, sizeof(deviceInfo->DeviceName), &deviceInfo->SerialNo)) { MessageBox(hWnd, TEXT("GetDeviceDescription failed"), TEXT("Error!"), MB_OK); @@ -783,7 +783,7 @@ EnumExistingDevices( // Get the device details such as friendly name and SerialNo // if(!GetDeviceDescription(deviceInterfaceDetailData->DevicePath, - (PBYTE)deviceInfo->DeviceName, + deviceInfo->DeviceName, sizeof(deviceInfo->DeviceName), &deviceInfo->SerialNo)){ goto Error; @@ -873,7 +873,7 @@ BOOLEAN Cleanup(HWND hWnd) BOOL GetDeviceDescription( _In_ LPTSTR DevPath, - _Out_writes_bytes_(OutBufferLen) PBYTE OutBuffer, + _Out_writes_bytes_(OutBufferLen) PTSTR OutBuffer, _In_ ULONG OutBufferLen, _In_ PULONG SerialNo ) @@ -917,14 +917,14 @@ GetDeviceDescription( if(!SetupDiGetDeviceRegistryProperty(hardwareDeviceInfo, &deviceInfoData, SPDRP_FRIENDLYNAME, &dwRegType, - OutBuffer, + (PBYTE) OutBuffer, OutBufferLen, NULL)) { if(!SetupDiGetDeviceRegistryProperty(hardwareDeviceInfo, &deviceInfoData, SPDRP_DEVICEDESC, &dwRegType, - OutBuffer, + (PBYTE) OutBuffer, OutBufferLen, NULL)){ goto Error; diff --git a/general/toaster/toastDrv/exe/notify/notify.h b/general/toaster/toastDrv/exe/notify/notify.h index 98db2918b..7bddb5474 100644 --- a/general/toaster/toastDrv/exe/notify/notify.h +++ b/general/toaster/toastDrv/exe/notify/notify.h @@ -154,7 +154,7 @@ BOOLEAN Cleanup( BOOL GetDeviceDescription( _In_ LPTSTR DevPath, - _Out_writes_bytes_(OutBufferLen) PBYTE OutBuffer, + _Out_writes_bytes_(OutBufferLen) PTSTR OutBuffer, _In_ ULONG OutBufferLen, _In_ PULONG SerialNo ); diff --git a/general/toaster/toastDrv/exe/notify/notify.vcxproj b/general/toaster/toastDrv/exe/notify/notify.vcxproj index 38bb67b7b..6a4c3d439 100644 --- a/general/toaster/toastDrv/exe/notify/notify.vcxproj +++ b/general/toaster/toastDrv/exe/notify/notify.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/toastDrv/exe/toast/toast.vcxproj b/general/toaster/toastDrv/exe/toast/toast.vcxproj index a8787a634..8c0739a04 100644 --- a/general/toaster/toastDrv/exe/toast/toast.vcxproj +++ b/general/toaster/toastDrv/exe/toast/toast.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/toastDrv/exe/wmi/WmiToast.vcxproj b/general/toaster/toastDrv/exe/wmi/WmiToast.vcxproj index 9be78de1d..d740026ba 100644 --- a/general/toaster/toastDrv/exe/wmi/WmiToast.vcxproj +++ b/general/toaster/toastDrv/exe/wmi/WmiToast.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx index 55f07bda2..f557b6e38 100644 Binary files a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx and b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx differ diff --git a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.vcxproj b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.vcxproj index d71efb105..deddc2c70 100644 --- a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.vcxproj +++ b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/bus/static/StatBus.vcxproj b/general/toaster/toastDrv/kmdf/bus/static/StatBus.vcxproj index 3894601b3..089dc141d 100644 --- a/general/toaster/toastDrv/kmdf/bus/static/StatBus.vcxproj +++ b/general/toaster/toastDrv/kmdf/bus/static/StatBus.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/bus/static/statbus.inx b/general/toaster/toastDrv/kmdf/bus/static/statbus.inx index 544c87ed0..094bce096 100644 Binary files a/general/toaster/toastDrv/kmdf/bus/static/statbus.inx and b/general/toaster/toastDrv/kmdf/bus/static/statbus.inx differ diff --git a/general/toaster/toastDrv/kmdf/filter/filter.inx b/general/toaster/toastDrv/kmdf/filter/filter.inx index a8538010e..8a2ca0062 100644 Binary files a/general/toaster/toastDrv/kmdf/filter/filter.inx and b/general/toaster/toastDrv/kmdf/filter/filter.inx differ diff --git a/general/toaster/toastDrv/kmdf/filter/generic/filter.vcxproj b/general/toaster/toastDrv/kmdf/filter/generic/filter.vcxproj index fbfe0c696..4a949834b 100644 --- a/general/toaster/toastDrv/kmdf/filter/generic/filter.vcxproj +++ b/general/toaster/toastDrv/kmdf/filter/generic/filter.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/filter/sideband/filter.vcxproj b/general/toaster/toastDrv/kmdf/filter/sideband/filter.vcxproj index b9dbcbf1d..0bcd8cc16 100644 --- a/general/toaster/toastDrv/kmdf/filter/sideband/filter.vcxproj +++ b/general/toaster/toastDrv/kmdf/filter/sideband/filter.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx index 1b81d480b..b91edc1b1 100644 Binary files a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx and b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx differ diff --git a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.vcxproj b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.vcxproj index 7c8764727..20b24f1b5 100644 --- a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.vcxproj +++ b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx index aac793078..549f20e1f 100644 Binary files a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx and b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx differ diff --git a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.vcxproj b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.vcxproj index 111886692..757978dd8 100644 --- a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.vcxproj +++ b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.inx b/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.inx index a63a6c5c6..0c1a410b5 100644 Binary files a/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.inx and b/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.inx differ diff --git a/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.vcxproj b/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.vcxproj index 3d1468bcb..f32bcee18 100644 --- a/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.vcxproj +++ b/general/toaster/toastDrv/kmdf/toastmon/wdftoastmon.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/general/toaster/toastDrv/toaster.sln b/general/toaster/toastDrv/toaster.sln index 0d1c2e6c0..551f7a75c 100644 --- a/general/toaster/toastDrv/toaster.sln +++ b/general/toaster/toastDrv/toaster.sln @@ -37,12 +37,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Bus", "Bus", "{320825A6-82C EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dynamic", "Dynamic", "{4A994F2B-05BD-4CED-9157-45B29777740D}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Toastmon", "Toastmon", "{16ECEF20-C217-4477-8C88-E8A231CC23B8}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Umdf", "Umdf", "{82276D55-C8B4-4C84-98FE-83F10C898FA0}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Func", "Func", "{9BEE50D5-9D78-4CA3-A535-75904B21C448}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "package", "Package\package.VcxProj", "{30FFB863-CECC-4E27-85F1-8DAC2256FC2F}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WmiToast", "exe\wmi\WmiToast.vcxproj", "{869C08D1-A32F-49C7-9831-2ADB52F241B6}" @@ -67,10 +61,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StatBus", "kmdf\bus\static\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynambus", "kmdf\bus\dynamic\dynambus.vcxproj", "{E5E1F492-05BB-45A3-B09F-F643DC1C6B03}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFToastMon", "umdf\Toastmon\WUDFToastMon.vcxproj", "{F575419D-099B-4DA0-B80C-88D766DD7542}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFToaster", "umdf\func\WUDFToaster.vcxproj", "{3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -175,22 +165,6 @@ Global {E5E1F492-05BB-45A3-B09F-F643DC1C6B03}.Debug|x64.Build.0 = Debug|x64 {E5E1F492-05BB-45A3-B09F-F643DC1C6B03}.Release|x64.ActiveCfg = Release|x64 {E5E1F492-05BB-45A3-B09F-F643DC1C6B03}.Release|x64.Build.0 = Release|x64 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Debug|Win32.ActiveCfg = Debug|Win32 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Debug|Win32.Build.0 = Debug|Win32 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Release|Win32.ActiveCfg = Release|Win32 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Release|Win32.Build.0 = Release|Win32 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Debug|x64.ActiveCfg = Debug|x64 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Debug|x64.Build.0 = Debug|x64 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Release|x64.ActiveCfg = Release|x64 - {F575419D-099B-4DA0-B80C-88D766DD7542}.Release|x64.Build.0 = Release|x64 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Debug|Win32.ActiveCfg = Debug|Win32 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Debug|Win32.Build.0 = Debug|Win32 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Release|Win32.ActiveCfg = Release|Win32 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Release|Win32.Build.0 = Release|Win32 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Debug|x64.ActiveCfg = Debug|x64 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Debug|x64.Build.0 = Debug|x64 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Release|x64.ActiveCfg = Release|x64 - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -208,8 +182,6 @@ Global {B39F6628-73BA-4AC3-863A-EA20892F1EFD} = {9577224D-E994-4E6E-BE11-FF456B8A4D46} {6C6E0C23-5B37-4BBB-8909-435078D49364} = {A69FDC71-8327-494A-9840-CF684E74965C} {E5E1F492-05BB-45A3-B09F-F643DC1C6B03} = {4A994F2B-05BD-4CED-9157-45B29777740D} - {F575419D-099B-4DA0-B80C-88D766DD7542} = {16ECEF20-C217-4477-8C88-E8A231CC23B8} - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F} = {9BEE50D5-9D78-4CA3-A535-75904B21C448} {C1205C19-4601-4DF6-A222-91CC30C12284} = {B1177A9B-61C5-4747-B40A-9F36D83CE9A0} {26B8AB05-2BE2-4266-AB19-BA912C0ACFA1} = {B1177A9B-61C5-4747-B40A-9F36D83CE9A0} {D2F3C374-F164-4E08-A5FE-F902972C57F9} = {B1177A9B-61C5-4747-B40A-9F36D83CE9A0} @@ -224,7 +196,5 @@ Global {A69FDC71-8327-494A-9840-CF684E74965C} = {320825A6-82C4-42DE-91A3-EE5994B74EC3} {320825A6-82C4-42DE-91A3-EE5994B74EC3} = {57D2095B-0A01-4F4C-A5D8-50F40DC155D0} {4A994F2B-05BD-4CED-9157-45B29777740D} = {320825A6-82C4-42DE-91A3-EE5994B74EC3} - {16ECEF20-C217-4477-8C88-E8A231CC23B8} = {82276D55-C8B4-4C84-98FE-83F10C898FA0} - {9BEE50D5-9D78-4CA3-A535-75904B21C448} = {82276D55-C8B4-4C84-98FE-83F10C898FA0} EndGlobalSection EndGlobal diff --git a/general/toaster/toastDrv/umdf/Toastmon/Device.cpp b/general/toaster/toastDrv/umdf/Toastmon/Device.cpp deleted file mode 100644 index 5b2bde411..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/Device.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF sample driver's - device callback object. - - This sample demonstrates how to register for PnP event notification - for an interface class, and how to handle arrival events. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice * MyDevice - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - MyDevice - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice myDevice; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - myDevice = new CMyDevice(); - - if (NULL == myDevice) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = myDevice->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *MyDevice = myDevice; - } - else - { - myDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - Then it registers for toaster device notifications. - - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - CComPtr fxDevice; - HRESULT hr; - - // - // Save a weak reference to the Fx driver object. We'll need it to create - // CMyRemoteTarget objects. - // - - m_FxDriver = FxDriver; - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - { - IUnknown *unknown = this->QueryIUnknown(); - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - CComPtr fxDevice2; - if (SUCCEEDED(hr)) - { - // - // Q.I. for the latest version of this interface. - // - hr = fxDevice->QueryInterface(IID_PPV_ARGS(&fxDevice2)); - } - - if (SUCCEEDED(hr)) - { - // - // Store a weak reference to the IWDFDevice2 interface. Since this object - // is partnered with the framework object they have the same lifespan - - // there is no need for an additional reference. - // - - m_FxDevice = fxDevice2; - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - // - // Register for TOASTER device interface change notification. - // We will get OnRemoteInterfaceArrival() calls when a remote toaster - // device is started. - // - // Arrival notification will be sent for all existing and future toaster - // devices. - // - // The framework will take care of unregistration when the device unloads. - // - hr = m_FxDevice->RegisterRemoteInterfaceNotification(&GUID_DEVINTERFACE_TOASTER, - true); - - return hr; -} - - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if(IsEqualIID(InterfaceId, __uuidof(IPnpCallbackRemoteInterfaceNotification))) - { - *Object = QueryIPnpCallbackRemoteInterfaceNotification(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// IPnpCallbackRemoteInterfaceNotification -// - -void -STDMETHODCALLTYPE -CMyDevice::OnRemoteInterfaceArrival( - _In_ IWDFRemoteInterfaceInitialize * FxRemoteInterfaceInit - ) -/*++ - - Routine Description: - - This method is called by the framework when a new remote interface has come - online. These calls will only occur one at a time. - - Arguments: - - FxRemoteInterfaceInit - An identifier for the remote interface. - ---*/ -{ - HRESULT hr = S_OK; - - - // - // Create a new FX remote interface object and assign a NULL callback - // object since we don't care to handle any remote interface level events - // that occur. - // - - CComPtr fxRemoteInterface; - - hr = m_FxDevice->CreateRemoteInterface(FxRemoteInterfaceInit, - NULL, - &fxRemoteInterface); - - // - // Create an instance of CMyRemoteTarget which will open the remote device - // and post I/O requests to it. - // - - PCMyRemoteTarget myRemoteTarget = NULL; - if (SUCCEEDED(hr)) - { - hr = CMyRemoteTarget::CreateInstance(this, - m_FxDriver, - m_FxDevice, - fxRemoteInterface, - &myRemoteTarget); - } - - if (SUCCEEDED(hr)) - { - if (myRemoteTarget != NULL) - { - // - // Add to our list - // - InsertHeadList(&m_MyRemoteTargets, &myRemoteTarget->m_Entry); - - // - // Release, since framework will keep a reference - // - myRemoteTarget->Release(); - } - } - - if (FAILED(hr)) - { - if (fxRemoteInterface != NULL) - { - // - // We failed to create the CMyRemoteTarget, delete the - // RemoteInterface object - // - fxRemoteInterface->DeleteWdfObject(); - } - } -} - diff --git a/general/toaster/toastDrv/umdf/Toastmon/Device.h b/general/toaster/toastDrv/umdf/Toastmon/Device.h deleted file mode 100644 index c457a8da8..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/Device.h +++ /dev/null @@ -1,162 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "initguid.h" - - -//{781EF630-72B2-11d2-B852-00C04FAD5171} -DEFINE_GUID(GUID_DEVINTERFACE_TOASTER, 0x781EF630, 0x72B2, 0x11d2, 0xB8, 0x52, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); - - -// -// Class for the sample device. -// - -class CMyDevice : public CUnknown, - public IPnpCallbackRemoteInterfaceNotification -{ - // - // Private data members. - // -private: - - // - // Weak reference to the WDF device object. - // - - IWDFDevice2 *m_FxDevice; - - // - // Weak reference to the WDF driver object - // - - IWDFDriver *m_FxDriver; - - // - // Head of remote target list - // - - LIST_ENTRY m_MyRemoteTargets; - - // - // Private methods. - // -private: - - // - // Protected methods - // -protected: - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_FxDriver(NULL) - { - InitializeListHead(&m_MyRemoteTargets); - } - - HRESULT - Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ); - - // - // Public methods - // -public: - - // - // The factory method used to create an instance of this driver. - // - static - HRESULT - CreateInstance( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice * MyDevice - ); - - HRESULT - Configure( - VOID - ); - - ~CMyDevice( - VOID - ) - { - ATLASSERT(IsListEmpty(&m_MyRemoteTargets)); - } - - // - // COM methods - // -public: - - // - // IUnknown methods. - // - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IPnpCallbackRemoteInterfaceNotification - // - void - STDMETHODCALLTYPE - OnRemoteInterfaceArrival( - _In_ IWDFRemoteInterfaceInitialize * FxRemoteInterfaceInit - ); - IPnpCallbackRemoteInterfaceNotification * - QueryIPnpCallbackRemoteInterfaceNotification( - VOID - ) - { - AddRef(); - return static_cast(this); - } - -}; diff --git a/general/toaster/toastDrv/umdf/Toastmon/Driver.cpp b/general/toaster/toastDrv/umdf/Toastmon/Driver.cpp deleted file mode 100644 index adf74dc09..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/Driver.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver * MyDriver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - MyDriver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver myDriver; - HRESULT hr; - - // - // Allocate the callback object. - // - - myDriver = new CMyDriver(); - - if (NULL == myDriver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = myDriver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *MyDriver = myDriver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - myDriver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - PCMyDevice myDevice = NULL; - - HRESULT hr; - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxDriver, FxDeviceInit, &myDevice); - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = myDevice->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != myDevice) - { - myDevice->Release(); - } - - return hr; -} diff --git a/general/toaster/toastDrv/umdf/Toastmon/Driver.h b/general/toaster/toastDrv/umdf/Toastmon/Driver.h deleted file mode 100644 index aecb97655..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/Driver.h +++ /dev/null @@ -1,146 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -// -// This class handles driver events for the sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, - public IDriverEntry -{ - // - // Private data members. - // -private: - - // - // Private methods. - // -private: - - // - // Returns a referenced pointer to the IDriverEntry interface. - // - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver * MyDriver - ); - - // - // COM methods - // -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver * /* FxDriver */ - ) - { - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver * /* FxDriver */ - ) - { - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class because of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.cpp b/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.cpp deleted file mode 100644 index 88ea7f8a6..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - RemoteTarget.cpp - -Abstract: - - This module contains the implementation of the UMDF sample driver's - remote interface and remote target callback object. - - This sample demonstrates how to open the remote target and register - and respond to device change notification. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "remotetarget.tmh" - - -DWORD WINAPI _ThreadProc( - _In_ LPVOID lpParameter - ) -{ - CMyRemoteTarget *MyRemoteTarget = (CMyRemoteTarget*)lpParameter; - - return MyRemoteTarget->ThreadProc(); -} - -HRESULT -CMyRemoteTarget::CreateInstance( - _In_ CMyDevice * MyDevice, - _In_ IWDFDriver * FxDriver, - _In_ IWDFDevice2 * FxDevice, - _In_ IWDFRemoteInterface * FxRemoteInterface, - _Out_ PCMyRemoteTarget * MyRemoteTarget - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the driver's - remote target callback object. - - Arguments: - - FxRemoteInterfaceInit - An identifier that specifies the remote toaster device. - - MyDevice - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyRemoteTarget myRemoteTarget; - HRESULT hr; - - // - // Allocate a new instance of the remote target class. - // - - myRemoteTarget = new CMyRemoteTarget(); - - if (NULL == myRemoteTarget) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = myRemoteTarget->Initialize(MyDevice, - FxDriver, - FxDevice, - FxRemoteInterface); - - if (SUCCEEDED(hr)) - { - *MyRemoteTarget = myRemoteTarget; - } - else - { - myRemoteTarget->Release(); - } - - return hr; -} - -HRESULT -CMyRemoteTarget::Initialize( - _In_ CMyDevice * MyDevice, - _In_ IWDFDriver * FxDriver, - _In_ IWDFDevice2 * FxDevice, - _In_ IWDFRemoteInterface * FxRemoteInterface - ) -/*++ - - Routine Description: - - This method initializes the remote target callback object and creates - the partner remote target object. - - Arguments: - - FxRemoteInterface - the identifier for the remote toaster device. - - Return Value: - - status. - ---*/ -{ - HRESULT hr; - - CComPtr fxWriteRequest; - CComPtr fxReadRequest; - - // - // Save a weak reference to the class that created us - // so we can notify it when we get removed - // - - m_MyDevice = MyDevice; - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the CMyRemoteTarget). We pass that - // to the various Create* calls, which take their own reference if - // everything works. - // - - IUnknown * unknown = this->QueryIUnknown(); - - - // - // Create a new FX remote target object and assign the new callback - // object to handle any remote target level events that occur. - // - hr = FxDevice->CreateRemoteTarget(unknown, - FxRemoteInterface, - &m_FxTarget); - - if (SUCCEEDED(hr)) - { - // - // Open and start the remote target. Note that this sample doesn't - // perform any impersonation, so we're running as "Local Service" - // since that is what UMDF driver runs as. - // - // Make sure that your Toaster devices all have security ACLs that - // permit "Local Service" to access the device. The Win7 toaster - // sample driver INFs have been updated for this. However, if you - // had previously installed pre-Win7 versions of the Toaster sample - // driver, the security settings will not be updated by a new driver - // install, unless the Toaster device class key is deleted. - // - - hr = m_FxTarget->OpenRemoteInterface(FxRemoteInterface, - NULL, - GENERIC_READ | GENERIC_WRITE, - NULL); - } - - if (SUCCEEDED(hr)) - { - // - // Create a new FX request object and assign the new callback - // object to handle any request level events that occur. - // - hr = FxDevice->CreateRequest(unknown, - FxRemoteInterface, - &fxWriteRequest); - } - - if (SUCCEEDED(hr)) - { - // - // We want to save the newer IWDFIoRequest2 interface instead. - // - hr = fxWriteRequest->QueryInterface(IID_PPV_ARGS(&m_FxWriteRequest)); - } - - if (SUCCEEDED(hr)) - { - // - // Create a buffer for the write request - // - hr = FxDriver->CreateWdfMemory(WRITE_BUF_SIZE, - NULL, - FxRemoteInterface, - &m_FxWriteMemory); - } - - if (SUCCEEDED(hr)) - { - // - // Create a new FX remote target object and assign the new callback - // object to handle any remote target level events that occur. - // - hr = FxDevice->CreateRequest(unknown, - FxRemoteInterface, - &fxReadRequest); - } - - if (SUCCEEDED(hr)) - { - // - // We want to save the newer IWDFIoRequest2 interface instead. - // - hr = fxReadRequest->QueryInterface(IID_PPV_ARGS(&m_FxReadRequest)); - } - - if (SUCCEEDED(hr)) - { - // - // Create a buffer for the read request - // - hr = FxDriver->CreateWdfMemory(READ_BUF_SIZE, - NULL, - FxRemoteInterface, - &m_FxReadMemory); - } - - if (SUCCEEDED(hr)) - { - // - // Create/Start the thread which will post I/O requests to the remote - // target. - // - // NOTE: This would not be a typical driver pattern. Normally, your - // driver would receive some I/O from another caller and you'd - // use this I/O as a trigger to post I/O to the remote target. - // You may choose to forward the request directly with no changes, - // modify the request before sending, or create an entirely - // separate request. - // - m_hThread = CreateThread(NULL, - 0, - _ThreadProc, - this, - 0, - NULL); - - if (m_hThread == NULL) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - - unknown->Release(); - - return hr; -} - -DWORD WINAPI CMyRemoteTarget::ThreadProc( - VOID - ) -/*++ - - Routine Description: - - This method is the main loop for a thread that posts I/O requests to - the remote target. The main loop continues until the remote target - is deleted, which happens in the Dispose() method. - ---*/ -{ - BOOL bContinue = TRUE; - - while(bContinue) - { - Sleep(100); - - switch(m_FxTarget->GetState()) - { - case WdfIoTargetStarted: - PostIoRequests(); - break; - - case WdfIoTargetClosedForQueryRemove: - break; - - case WdfIoTargetClosed: - case WdfIoTargetDeleted: - default: - bContinue = false; - break; - } - } - - return 0; -} - -void -CMyRemoteTarget::PostIoRequests( - VOID - ) -{ - HRESULT hr; - - if (!m_WriteInProgress) - { - // - // Mark that the request has been sent, so we don't try to send - // again before the completion routine runs. - // - m_WriteInProgress = true; - - hr = m_FxTarget->FormatRequestForWrite(m_FxWriteRequest, - NULL, - m_FxWriteMemory, - 0, - 0); - - if (SUCCEEDED(hr)) - { - m_FxWriteRequest->SetCompletionCallback(this, NULL); - - hr = m_FxWriteRequest->Send(m_FxTarget, 0, 0); - } - - if (FAILED(hr)) - { - m_WriteInProgress = false; - } - } - - if (!m_ReadInProgress) - { - // - // Mark that the request has been sent, so we don't try to send - // again before the completion routine runs. - // - m_ReadInProgress = true; - - hr = m_FxTarget->FormatRequestForRead(m_FxReadRequest, - NULL, - m_FxReadMemory, - 0, - 0); - - if (SUCCEEDED(hr)) - { - m_FxReadRequest->SetCompletionCallback(this, NULL); - - hr = m_FxReadRequest->Send(m_FxTarget, 0, 0); - } - - if (FAILED(hr)) - { - m_ReadInProgress = true; - } - } -} - -HRESULT -CMyRemoteTarget::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID * Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if(IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - *Object = QueryIRequestCallbackRequestCompletion(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IRemoteTargetCallbackRemoval))) - { - *Object = QueryIRemoteTargetCallbackRemoval(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IObjectCleanup))) - { - *Object = QueryIObjectCleanup(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// IRequestCallbackRequestCompletion -// -void -STDMETHODCALLTYPE -CMyRemoteTarget::OnCompletion( - _In_ IWDFIoRequest * FxRequest, - _In_ IWDFIoTarget * /* FxTarget */, - _In_ IWDFRequestCompletionParams * /* Params */, - _In_ void* /* Context */ - ) -{ - IWDFRequestCompletionParams * CompletionParams; - - FxRequest->GetCompletionParams(&CompletionParams); - - if (CompletionParams->GetCompletedRequestType() == WdfRequestRead) - { - m_FxReadRequest->Reuse(E_FAIL); - m_ReadInProgress = false; - } - if (CompletionParams->GetCompletedRequestType() == WdfRequestWrite) - { - m_FxWriteRequest->Reuse(E_FAIL); - m_WriteInProgress = false; - } - - CompletionParams->Release(); -} - -// -// IRemoteTargetCallbackRemoval -// -BOOL -STDMETHODCALLTYPE -CMyRemoteTarget::OnRemoteTargetQueryRemove( - _In_ IWDFRemoteTarget * /* FxTarget */ - ) -{ - m_FxTarget->CloseForQueryRemove(); - - // - // Return FALSE if you want to VETO the Query - // - - return TRUE; -} - -VOID -STDMETHODCALLTYPE -CMyRemoteTarget::OnRemoteTargetRemoveCanceled( - _In_ IWDFRemoteTarget * /* FxTarget */ - ) -{ - if (FAILED(m_FxTarget->Reopen())) - { - m_FxTarget->Close(); - } -} - -VOID -STDMETHODCALLTYPE -CMyRemoteTarget::OnRemoteTargetRemoveComplete( - _In_ IWDFRemoteTarget * /* FxTarget */ - ) -{ - // - // The remote device has been removed, so we close the target for good. - // The rest of cleanup will occur when the framework handles the removal - // of the RemoteInterface - // - - m_FxTarget->Close(); -} - - -// -// IObjectCleanup -// - -void -STDMETHODCALLTYPE -CMyRemoteTarget::OnCleanup( - _In_ IWDFObject * /* FxObject */ - ) -{ - if (m_hThread != NULL) - { - if (m_FxTarget->GetState() != WdfIoTargetClosed) - { - // - // Close the target if it's still open. - // - // If the target has already gone through RemoveComplete, it should - // already be closed. - // - // If the Target interface is disabled without the device being - // removed, the target will still be open until now. - // - // If the ToastMon device itself is removed while a target is - // still active, we'll now close it. - // - m_FxTarget->Close(); - } - - // - // Wait for the Thread to complete - // - WaitForSingleObject(m_hThread, INFINITE); - - CloseHandle(m_hThread); - - m_hThread = NULL; - - // - // Remove ourselves from the list of Remote Targets - // - RemoveEntryList(&m_Entry); - } - - m_FxTarget = NULL; - m_FxWriteRequest = NULL; - m_FxReadRequest = NULL; -} - diff --git a/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.h b/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.h deleted file mode 100644 index 15d91dad5..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/RemoteTarget.h +++ /dev/null @@ -1,228 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - RemoteTarget.h - -Abstract: - - This module contains the type definitions for the UMDF sample - driver's remote target callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -#define READ_BUF_SIZE 100 -#define WRITE_BUF_SIZE 120 - - -class CMyRemoteTarget : public CUnknown, - public IRequestCallbackRequestCompletion, - public IRemoteTargetCallbackRemoval, - public IObjectCleanup -{ - // - // Public data members. - // -public: - - // - // This is the Entry for the list of Remote Targets. - // The List head is held by CMyDevice. - // - LIST_ENTRY m_Entry; - - - // - // Private data members. - // -private: - - CMyDevice * m_MyDevice; // Weak reference - - // - // The handle for a thread to post I/O requests to the remote target - // - HANDLE m_hThread; - - CComPtr m_FxTarget; - - bool m_WriteInProgress; - CComPtr m_FxWriteRequest; - CComPtr m_FxWriteMemory; - - bool m_ReadInProgress; - CComPtr m_FxReadRequest; - CComPtr m_FxReadMemory; - - // - // Private methods. - // -private: - - void - PostIoRequests( - VOID - ); - - // - // Protected methods - // -protected: - - CMyRemoteTarget( - VOID - ) : - m_MyDevice(NULL), - m_hThread(NULL), - m_WriteInProgress(false), - m_ReadInProgress(false) - - { - } - - HRESULT - Initialize( - _In_ CMyDevice * MyDevice, - _In_ IWDFDriver * FxDriver, - _In_ IWDFDevice2 * FxDevice, - _In_ IWDFRemoteInterface * FxRemoteInterface - ); - - // - // Public methods - // -public: - - // - // The factory method used to create an instance of this driver. - // - static - HRESULT - CreateInstance( - _In_ CMyDevice * MyDevice, - _In_ IWDFDriver * FxDriver, - _In_ IWDFDevice2 * FxDevice, - _In_ IWDFRemoteInterface * FxRemoteInterface, - _Out_ PCMyRemoteTarget * MyRemoteTarget - ); - - ~CMyRemoteTarget( - VOID - ) - { - } - - DWORD WINAPI - ThreadProc( - VOID - ); - - // - // COM methods - // -public: - - // - // IUnknown methods. - // - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID * Object - ); - - // - // IRequestCallbackRequestCompletion - // - void - STDMETHODCALLTYPE - OnCompletion( - _In_ IWDFIoRequest * FxRequest, - _In_ IWDFIoTarget * /* FxTarget */, - _In_ IWDFRequestCompletionParams * /* Params */, - _In_ void* /* Context */ - ); - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IRemoteTargetCallbackRemoval - // - BOOL - STDMETHODCALLTYPE - OnRemoteTargetQueryRemove( - _In_ IWDFRemoteTarget * /* FxTarget */ - ); - VOID - STDMETHODCALLTYPE - OnRemoteTargetRemoveCanceled( - _In_ IWDFRemoteTarget * /* FxTarget */ - ); - VOID - STDMETHODCALLTYPE - OnRemoteTargetRemoveComplete( - _In_ IWDFRemoteTarget * /* FxTarget */ - ); - IRemoteTargetCallbackRemoval * - QueryIRemoteTargetCallbackRemoval( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IObjectCleanup - // - void - STDMETHODCALLTYPE - OnCleanup( - _In_ IWDFObject* /* FxObject */ - ); - IObjectCleanup * - QueryIObjectCleanup( - VOID - ) - { - AddRef(); - return static_cast(this); - } - -}; diff --git a/general/toaster/toastDrv/umdf/Toastmon/ToastMon.rc b/general/toaster/toastDrv/umdf/Toastmon/ToastMon.rc deleted file mode 100644 index 57983bbc8..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/ToastMon.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// ToastMon.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF ToastMon User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "ToastMon" -#define VER_ORIGINALFILENAME_STR "ToastMon.dll" - -#include "common.ver" diff --git a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.inx b/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.inx deleted file mode 100644 index 245b304e6..000000000 Binary files a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.inx and /dev/null differ diff --git a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj b/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj deleted file mode 100644 index 3648d85f5..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj +++ /dev/null @@ -1,285 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {F575419D-099B-4DA0-B80C-88D766DD7542} - $(MSBuildProjectName) - 1 - false - true - Debug - Win32 - {439EDE87-12DD-4F6D-8C22-A8AC9DAEF4B2} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - $(InfArch) - true - .\$(IntDir)\WUDFToastMon.inf - - - true - true - internal.h - - - - WUDFToastMon - Dynamic - - - WUDFToastMon - Dynamic - - - WUDFToastMon - Dynamic - - - WUDFToastMon - Dynamic - - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - sha256 - - - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - sha256 - - - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - sha256 - - - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - sha256 - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\oleaut32.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\oleaut32.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\oleaut32.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\oleaut32.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj.Filters b/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj.Filters deleted file mode 100644 index 890e83d67..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/WUDFToastMon.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {FDA736D6-A855-4CED-9C9E-B6FF707C26E1} - - - h;hpp;hxx;hm;inl;inc;xsd - {03AC1F65-1B83-4D8E-9D06-DF35B5085EA7} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {E8FFB961-9B2B-4A4A-8F75-5F933AF32C60} - - - inf;inv;inx;mof;mc; - {C6C8B61F-CD41-4ACB-AC13-2E7A02CC94A0} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/general/toaster/toastDrv/umdf/Toastmon/comsup.cpp b/general/toaster/toastDrv/umdf/Toastmon/comsup.cpp deleted file mode 100644 index fd2984700..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/general/toaster/toastDrv/umdf/Toastmon/comsup.h b/general/toaster/toastDrv/umdf/Toastmon/comsup.h deleted file mode 100644 index b96fd9828..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/general/toaster/toastDrv/umdf/Toastmon/dllsup.cpp b/general/toaster/toastDrv/umdf/Toastmon/dllsup.cpp deleted file mode 100644 index 8b4b5426d..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/dllsup.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. See internal.h for definition. - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - - DisableThreadLibraryCalls(ModuleHandle); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -HRESULT -STDAPICALLTYPE -DllGetClassObject( - _In_ REFCLSID ClassId, - _In_ REFIID InterfaceId, - _Outptr_ LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/general/toaster/toastDrv/umdf/Toastmon/exports.def b/general/toaster/toastDrv/umdf/Toastmon/exports.def deleted file mode 100644 index f8ac59f6e..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; Exports.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/general/toaster/toastDrv/umdf/Toastmon/internal.h b/general/toaster/toastDrv/umdf/Toastmon/internal.h deleted file mode 100644 index 5a8fc9e2d..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/internal.h +++ /dev/null @@ -1,109 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Include ATL to provide basic COM support. -// - -#define _ATL_FREE_THREADED -#define _ATL_NO_AUTOMATIC_NAMESPACE - -#include -#include - -using namespace ATL; - -extern CComModule _Module; -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyRemoteTarget *PCMyRemoteTarget; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (dee2c67c,6328,48d9,876b,64682c4e9e9b), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\ToastMon" -#define MYDRIVER_CLASS_ID { 0x8d4ec202, 0x1076, 0x4895, {0xa0, 0x72, 0x29, 0x7d, 0xa8, 0x8e, 0x60, 0x05} } - -// -// Include simple doubly-linked list macros -// -#include "list.h" - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "remotetarget.h" -#include "device.h" diff --git a/general/toaster/toastDrv/umdf/Toastmon/list.h b/general/toaster/toastDrv/umdf/Toastmon/list.h deleted file mode 100644 index 38d0b1e90..000000000 --- a/general/toaster/toastDrv/umdf/Toastmon/list.h +++ /dev/null @@ -1,77 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - list.h - -Abstract: - - This module contains doubly linked list macros - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -FORCEINLINE -VOID -InitializeListHead( - IN PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -VOID -InsertHeadList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -InsertTailList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} diff --git a/general/toaster/toastDrv/umdf/func/Device.cpp b/general/toaster/toastDrv/umdf/func/Device.cpp deleted file mode 100644 index eaf0a5455..000000000 --- a/general/toaster/toastDrv/umdf/func/Device.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Device.cpp - - Abstract: - - This file contains the device callback object implementation. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ -#include "stdafx.h" -#include "Device.h" - -#include "internal.h" -#include "device.tmh" - -HRESULT -CDevice::QueryInterface( - _In_ REFIID riid, - _Out_ LPVOID* ppvObject - ) -/*++ - -Routine Description: - - The framework calls this function to determine which callback - interfaces we support. - -Arguments: - - riid - GUID for a given callback interface. - ppvObject - We set this pointer to our object if we support the - interface indicated by riid. - -Return Value: - - HRESULT S_OK - Interface is supported. - ---*/ -{ - if (ppvObject == NULL) - { - return E_INVALIDARG; - } - - *ppvObject = NULL; - - if ( riid == _uuidof(IUnknown) ) - { - *ppvObject = static_cast(this); - } - else if ( riid == _uuidof(IPnpCallbackHardware) ) - { - *ppvObject = static_cast(this); - } - else - { - return E_NOINTERFACE; - } - - this->AddRef(); - - return S_OK; -} - - -ULONG CDevice::AddRef() -/*++ - -Routine Description: - - Increments the ref count on this object. - -Arguments: - - None. - -Return Value: - - ULONG - new ref count. - ---*/ -{ - LONG cRefs = InterlockedIncrement( &m_cRefs ); - - return cRefs; -} - - -_At_(this, __drv_freesMem(object)) -ULONG CDevice::Release() -/*++ - -Routine Description: - - Decrements the ref count on this object. - -Arguments: - - None. - -Return Value: - - ULONG - new ref count. - ---*/ -{ - LONG cRefs; - - cRefs = InterlockedDecrement( &m_cRefs ); - - if( 0 == cRefs ) - { - delete this; - } - - return cRefs; -} - - -HRESULT -CDevice::OnPrepareHardware( - _In_ IWDFDevice* pDevice) -/*++ - -Routine Description: - - The framework calls this function after IDriverEntry::OnDeviceAdd - returns and before the device enters the working power state. - This callback prepares the device and the driver to enter the working - state after enumeration. - -Arguments: - - pWdfDevice - A pointer to the IWDFDevice interface for the device - object of the device to make accessible. - -Return Value: - - S_OK in case of success - HRESULT correponding to one of the error codes that are defined in Winerror.h. - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - Trace(TRACE_LEVEL_INFORMATION,"%!FUNC!"); - - // - // Get the device name. - // Get the length to allocate first - // - - hr = pDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = pDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - } - - // - // Do your hardware operations here - // - - delete[] deviceName; - - return hr; -} - -HRESULT -CDevice::OnReleaseHardware( - _In_ IWDFDevice* /*pDevice*/) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. The framework - calls this callback after the device exits from the working power - state but before its queues are purged. - - -Arguments: - - pWdfDevice - A pointer to the IWDFDevice interface for the device object - of the device that is no longer accessible. - - -Return Value: - HRESULT - Always succeeds. ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION,"%!FUNC!"); - - return S_OK; -} - - - diff --git a/general/toaster/toastDrv/umdf/func/Device.h b/general/toaster/toastDrv/umdf/func/Device.h deleted file mode 100644 index 4bb68dc70..000000000 --- a/general/toaster/toastDrv/umdf/func/Device.h +++ /dev/null @@ -1,78 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Device.h - - Abstract: - - This file contains the class definition for device callback object. - - Environment: - - Windows User-Mode Driver Framework (UMDF) - ---*/ - -#pragma once -#include "resource.h" -#include "WUDFToaster.h" - -// -// To inform the framework about the callbacks we are interested in, we -// simply derive from the desired set of interfaces. -// -class CDevice : public IPnpCallbackHardware -{ -public: - CDevice() : m_cRefs(0) - { - } - - -public: - - // - // Static method that creates a device callback object. - // - static HRESULT CreateInstance(_Out_ IUnknown ** ppUnkwn) - { - *ppUnkwn = NULL; - -#pragma warning( suppress : 6014 )// PFD ISSUE: counted memory locks - CDevice *pMyDevice = new CDevice(); - - if (NULL == pMyDevice) - { - return E_OUTOFMEMORY; - } - - return (pMyDevice->QueryInterface( __uuidof(IUnknown), (void **) ppUnkwn )); - } - - // - // IUnknown - // - virtual HRESULT __stdcall QueryInterface(_In_ REFIID riid, _Out_ LPVOID* ppvObject); - virtual ULONG __stdcall AddRef(); - _At_(this, __drv_freesMem(object)) - virtual ULONG __stdcall Release(); - - - // IPnpCallbackHardware - // - virtual HRESULT __stdcall OnPrepareHardware(_In_ IWDFDevice* pDevice); - virtual HRESULT __stdcall OnReleaseHardware(_In_ IWDFDevice* pDevice); - - // - // TODO: Add your interfaces here - // - -private: - - LONG m_cRefs; - -}; - diff --git a/general/toaster/toastDrv/umdf/func/Driver.cpp b/general/toaster/toastDrv/umdf/func/Driver.cpp deleted file mode 100644 index 053217b95..000000000 --- a/general/toaster/toastDrv/umdf/func/Driver.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Driver.cpp - - Abstract: - - This file contains the implementation for the driver object. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "stdafx.h" -#include "Driver.h" -#include "Device.h" -#include "Queue.h" - -#include "internal.h" -#include "driver.tmh" - -//Idle setting for the Toaster device -#define IDLEWAKE_TIMEOUT_MSEC 6000 - - -HRESULT -CDriver::OnDeviceAdd( - _In_ IWDFDriver* pDriver, - _In_ IWDFDeviceInitialize* pDeviceInit - ) -/*++ - -Routine Description: - - The framework calls this function when a device is being added to - the driver stack. - -Arguments: - - IWDFDriver - Framework interface. The driver uses this - interface to create device objects. - IWDFDeviceInitialize - Framework interface. The driver uses this - interface to set device parameters before - creating the device obeject. - -Return Value: - - HRESULT S_OK - Device added successfully - ---*/ -{ - IUnknown *pDeviceCallback = NULL; - IWDFDevice *pIWDFDevice = NULL; - IWDFDevice2 *pIWDFDevice2 = NULL; - IUnknown *pIUnkQueue = NULL; - - // - // UMDF Toaster is a function driver so set is as the power policy owner (PPO) - // - pDeviceInit->SetPowerPolicyOwnership(TRUE); - - // - // Create our device callback object. - // - HRESULT hr = CDevice::CreateInstance(&pDeviceCallback); - - // - // Ask the framework to create a device object for us. - // We pass in the callback object and device init object - // as creation parameters. - // - if (SUCCEEDED(hr)) - { - hr = pDriver->CreateDevice(pDeviceInit, - pDeviceCallback, - &pIWDFDevice); - } - - // - // Create the queue callback object. - // - - if (SUCCEEDED(hr)) - { - hr = CQueue::CreateInstance(&pIUnkQueue); - } - - // - // Configure the default queue. We pass in our queue callback - // object to inform the framework about the callbacks we want. - // - - if (SUCCEEDED(hr)) - { - IWDFIoQueue * pDefaultQueue = NULL; - hr = pIWDFDevice->CreateIoQueue( - pIUnkQueue, - TRUE, // bDefaultQueue - WdfIoQueueDispatchParallel, - TRUE, // bPowerManaged - FALSE, // bAllowZeroLengthRequests - &pDefaultQueue); - SAFE_RELEASE(pDefaultQueue); - } - - // - // Enable the device interface. - // - - if (SUCCEEDED(hr)) - { - hr = pIWDFDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_TOASTER, - NULL); - } - - // - // IWDFDevice2 interface is an extension of IWDFDevice interface that enables - // Idle and Wake support. - // - - // - // Get a pointer to IWDFDevice2 interface - // - - if (SUCCEEDED(hr)) - { - hr = pIWDFDevice->QueryInterface(__uuidof(IWDFDevice2), (void**) &pIWDFDevice2); - } - - // - // Since this is a virtual device we tell the framework that we cannot wake - // ourself if we sleep in S0. Only way the device can be brought to D0 is if - // the device recieves an I/O from the system. - // - - if (SUCCEEDED(hr)) - { - - hr = pIWDFDevice2->AssignS0IdleSettings( - IdleCannotWakeFromS0, - PowerDeviceD3, //the lowest-powered device sleeping state - IDLEWAKE_TIMEOUT_MSEC, //idle timeout - IdleAllowUserControl, //user can control the device's idle behavior. - WdfTrue); - - } - - // - // TODO: Add the Idle and Wake suupport specific for your hardware - // - - SAFE_RELEASE(pDeviceCallback); - SAFE_RELEASE(pIWDFDevice); - SAFE_RELEASE(pIWDFDevice2); - SAFE_RELEASE(pIUnkQueue); - - return hr; -} - -VOID -CDriver::OnDeinitialize( - _In_ IWDFDriver * /* pDriver */ - ) -/*++ - -Routine Description: - - The framework calls this function just before de-initializing itself. All - WDF framework resources should be released by driver before returning from this call. - -Arguments: - -Return Value: - ---*/ -{ - return ; -} - -HRESULT -CDriver::OnInitialize( - _In_ IWDFDriver * /* pDriver */ - ) -/*++ - -Routine Description: - - The framework calls this function just after loading the driver. The driver can - perform any global, device independent intialization in this routine. - -Arguments: - -Return Value: - ---*/ -{ - return S_OK; -} - - diff --git a/general/toaster/toastDrv/umdf/func/Driver.h b/general/toaster/toastDrv/umdf/func/Driver.h deleted file mode 100644 index b60cffb51..000000000 --- a/general/toaster/toastDrv/umdf/func/Driver.h +++ /dev/null @@ -1,59 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Driver.h - - Abstract: - - This file contains the class definition for the driver object. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "resource.h" -#include "WUDFToaster.h" - -class ATL_NO_VTABLE CDriver : - public CComObjectRootEx, - public CComCoClass, - public IDriverEntry -{ -public: - CDriver() - { - } - - DECLARE_REGISTRY_RESOURCEID(IDR_TOASTERDRIVER) - DECLARE_NOT_AGGREGATABLE(CDriver) - - // - // The driver object suppports the IDriverEntry interface. - // - BEGIN_COM_MAP(CDriver) - COM_INTERFACE_ENTRY(IDriverEntry) - END_COM_MAP() - -public: - // - // IDriverEntry - // - STDMETHOD (OnDeviceAdd)( - _In_ IWDFDriver *pDriver, - _In_ IWDFDeviceInitialize *pDeviceInit - ); - STDMETHOD (OnInitialize)( - _In_ IWDFDriver* pDriver - ); - STDMETHOD_ (void, OnDeinitialize)( - _In_ IWDFDriver* pDriver - ); -}; - -OBJECT_ENTRY_AUTO(__uuidof(WUDFToaster), CDriver) diff --git a/general/toaster/toastDrv/umdf/func/Queue.cpp b/general/toaster/toastDrv/umdf/func/Queue.cpp deleted file mode 100644 index dec296a06..000000000 --- a/general/toaster/toastDrv/umdf/func/Queue.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Queue.cpp - - Abstract: - - This file contains the queue callback object implementation. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "stdafx.h" -#include "Queue.h" -#include -#include - - -#include "internal.h" -#include "queue.tmh" - -HRESULT -CQueue::QueryInterface( - _In_ REFIID riid, - _Out_ LPVOID* ppvObject - ) -/*++ - -Routine Description: - - The framework calls this function to determine which callback - interfaces we support. - -Arguments: - - riid - GUID for a given callback interface. - ppvObject - We set this pointer to our object if we support the - interface indicated by riid. - -Return Value: - - HRESULT S_OK - Interface is supported. - ---*/ -{ - if (ppvObject == NULL) - { - return E_INVALIDARG; - } - *ppvObject = NULL; - - if ( riid == _uuidof(IUnknown) ) - { - *ppvObject = static_cast (this); - } - else if ( riid == _uuidof(IQueueCallbackDeviceIoControl) ) - { - *ppvObject = static_cast(this); - } - else if ( riid == _uuidof(IQueueCallbackRead) ) - { - *ppvObject = static_cast(this); - } - else if ( riid == _uuidof(IQueueCallbackWrite) ) - { - *ppvObject = static_cast(this); - } - else - { - return E_NOINTERFACE; - } - - this->AddRef(); - - return S_OK; -} - - - -ULONG CQueue::AddRef() -/*++ - -Routine Description: - - Increments the ref count on this object. - -Arguments: - - None. - -Return Value: - - ULONG - new ref count. - ---*/ -{ - LONG cRefs = InterlockedIncrement( &m_cRefs ); - return cRefs; -} - -_At_(this, __drv_freesMem(object)) -ULONG CQueue::Release() -/*++ - -Routine Description: - - Decrements the ref count on this object. - -Arguments: - - None. - -Return Value: - - ULONG - new ref count. - ---*/ -{ - LONG cRefs; - - cRefs = InterlockedDecrement( &m_cRefs ); - - if( 0 == cRefs ) - { - delete this; - } - - return cRefs; -} - - -void -CQueue::OnDeviceIoControl( - _In_ IWDFIoQueue* pQueue, - _In_ IWDFIoRequest* pRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T /*InputBufferSizeInBytes*/, - _In_ SIZE_T /*OutputBufferSizeInBytes*/ - ) -/*++ - -Routine Description: - - The framework calls this function when somone has called - DeviceIoControl on the device. - -Arguments: - -Return Value: - None - ---*/ -{ - HRESULT hr = S_OK; - IWDFDevice *pDevice = NULL; - - Trace(TRACE_LEVEL_INFORMATION,"%!FUNC!"); - - // - // Retrieve the queue's parent device object - // - pQueue->GetDevice(&pDevice); - - WUDF_TEST_DRIVER_ASSERT(pDevice); - - switch (ControlCode) - { - case IOCTL_TOASTER_DONT_DISPLAY_IN_UI_DEVICE: - - // - // This is just an example on how to hide your device in the - // device manager. Please remove your code when you adapt this - // sample for your hardware. - // - pDevice->SetPnpState(WdfPnpStateDontDisplayInUI, WdfTrue); - pDevice->CommitPnpState(); - - break; - - default: - hr = E_FAIL; //invalid request - - Trace(TRACE_LEVEL_ERROR,"%!FUNC! Invalid IOCTL %!hresult!",hr); - } - pRequest->Complete(hr); - - return; -} - -void -CQueue::OnRead( - _In_ IWDFIoQueue* /* pQueue */, - _In_ IWDFIoRequest* pRequest, - _In_ SIZE_T SizeInBytes - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Arguments: - - pQueue - Framework Queue instance - pRequest - Framework Request instance - SizeInBytes - Length of bytes in the read buffer - - Copy available data into the read buffer - -Return Value: - None. - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION,"%!FUNC!"); - - // - // No need to check for zero-length reads. - // - // The framework queue is created with the flag bAllowZeroLengthRequests = FALSE. - // FALSE indicates that the framework completes zero-length I/O requests instead - // of putting them in the I/O queue. - // - - // - // TODO: Put your Read request processing here - // - - pRequest->CompleteWithInformation(S_OK, SizeInBytes); - - return; - -} - -void -CQueue::OnWrite( - _In_ IWDFIoQueue * /* pQueue */, - _In_ IWDFIoRequest * pRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - Write dispatch routine - IQueueCallbackWrite - -Arguments: - - pQueue - Framework Queue instance - pRequest - Framework Request instance - BytesToWrite - Length of bytes in the write buffer - - Allocate and copy data to local buffer - -Return Value: - None. - ---*/ -{ - Trace(TRACE_LEVEL_INFORMATION,"%!FUNC!"); - - // - // No need to check for zero-length writes. - // - - // - // TODO: Put your Write request processing here - // - - pRequest->CompleteWithInformation(S_OK, BytesToWrite); - - return; -} - diff --git a/general/toaster/toastDrv/umdf/func/Queue.h b/general/toaster/toastDrv/umdf/func/Queue.h deleted file mode 100644 index 6668ac355..000000000 --- a/general/toaster/toastDrv/umdf/func/Queue.h +++ /dev/null @@ -1,96 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - Queue.h - - Abstract: - - This file contains the class definition for the queue - callback object. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "WUDFToaster.h" - -class CQueue : - public IQueueCallbackDeviceIoControl, - public IQueueCallbackRead, - public IQueueCallbackWrite -{ - public: - - CQueue() : m_cRefs(0) - { - } - - public: - - // - // Static method that creates a queue callback object. - // - static HRESULT CreateInstance(_Out_ IUnknown **ppUkwn) - { - *ppUkwn = NULL; - -#pragma warning( suppress : 6014 )// PFD ISSUE: counted memory locks - CQueue *pMyQueue = new CQueue(); - - if (NULL == pMyQueue) - { - return E_OUTOFMEMORY; - } - return (pMyQueue->QueryInterface(__uuidof(IUnknown), (void **)ppUkwn )); - } - - // - // IUnknown - // - virtual HRESULT __stdcall QueryInterface(_In_ REFIID riid, _Out_ LPVOID* ppvObject); - virtual ULONG __stdcall AddRef(); - _At_(this, __drv_freesMem(object)) - virtual ULONG __stdcall Release(); - - // - // IQueueCallbackDeviceIoControl - // - virtual void __stdcall OnDeviceIoControl( - _In_ IWDFIoQueue* pQueue, - _In_ IWDFIoRequest* pRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); - - // - // IQueueCallbackRead - // - virtual void __stdcall OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); - - // - // IQueueCallbackWrite - // - virtual void __stdcall OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // - // TODO: Add your interfaces here - // - - private: - LONG m_cRefs; -}; diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.cpp b/general/toaster/toastDrv/umdf/func/WUDFToaster.cpp deleted file mode 100644 index fd66163d9..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - WUDFToaster.cpp - - Abstract: - - Implementation of DLL Exports. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "stdafx.h" -#include "resource.h" - -#include "WUDFToaster.h" - -#include "internal.h" -#include "WUDFToaster.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -class CToasterDriverModule : public CAtlDllModuleT< CToasterDriverModule > -{ -public : - DECLARE_LIBID(LIBID_WUDFToasterLib) -}; - -CToasterDriverModule _AtlModule; - -// DLL Entry Point -extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) -{ - hInstance; - - if(dwReason == DLL_PROCESS_ATTACH) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if(dwReason == DLL_PROCESS_DETACH) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return _AtlModule.DllMain(dwReason, lpReserved); -} - -// Returns a class factory to create an object of the requested type -_Check_return_ -STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv) -{ - return _AtlModule.DllGetClassObject(rclsid, riid, ppv); -} - -// Used to determine whether the DLL can be unloaded by OLE -STDAPI DllCanUnloadNow(void) -{ - return _AtlModule.DllCanUnloadNow(); -} - -// DllRegisterServer - Adds entries to the system registry -STDAPI DllRegisterServer(void) -{ - // registers object, typelib and all interfaces in typelib - HRESULT hr = _AtlModule.DllRegisterServer(); - return hr; -} - -// DllUnregisterServer - Removes entries from the system registry -STDAPI DllUnregisterServer(void) -{ - HRESULT hr = _AtlModule.DllUnregisterServer(); - return hr; -} diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.ctl b/general/toaster/toastDrv/umdf/func/WUDFToaster.ctl deleted file mode 100644 index cfcbb8668..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.ctl +++ /dev/null @@ -1,2 +0,0 @@ -9B6DE419-5658-46c9-A358-54FDEBB6B89D WudfToasterTraceGuid - diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.def b/general/toaster/toastDrv/umdf/func/WUDFToaster.def deleted file mode 100644 index 4aa746ad4..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.def +++ /dev/null @@ -1,6 +0,0 @@ -; WUDFToaster.def : Declares the module parameters. - -LIBRARY "WUDFToaster.DLL" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.idl b/general/toaster/toastDrv/umdf/func/WUDFToaster.idl deleted file mode 100644 index da21b41e8..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.idl +++ /dev/null @@ -1,40 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - WUDFToaster.idl - - Abstract: - - Definition of the WUDF Toaster sample's COM class - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -import "oaidl.idl"; -import "ocidl.idl"; -import "wudfddi.idl"; - -[ - uuid(04170C5A-388E-410f-9BAA-E7724196AD17), - version(1.0), - helpstring("WUDF Toaster Driver 1.0 Type Library") -] -library WUDFToasterLib -{ - importlib("stdole2.tlb"); - [ - uuid(5ED5997F-FAED-4a35-BA74-FCF7B43AEBA7), - helpstring("WudfToaster Class") - ] - coclass WUDFToaster - { - [default] interface IDriverEntry; - }; -}; - diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.inx b/general/toaster/toastDrv/umdf/func/WUDFToaster.inx deleted file mode 100644 index e804dcffa..000000000 Binary files a/general/toaster/toastDrv/umdf/func/WUDFToaster.inx and /dev/null differ diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.rc b/general/toaster/toastDrv/umdf/func/WUDFToaster.rc deleted file mode 100644 index 74453a023..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.rc +++ /dev/null @@ -1,22 +0,0 @@ -//--------------------------------------------------------------------------- -// Skeleton.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include -#include "resource.h" - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF User-Mode Toaster Driver Sample" -#define VER_INTERNALNAME_STR "WUDFToaster" -#define VER_ORIGINALFILENAME_STR "WUDFToaster.dll" - -#include "common.ver" diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj b/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj deleted file mode 100644 index e9c01e325..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj +++ /dev/null @@ -1,338 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {3A32C2D4-D40F-4DB8-9F25-ABB21CEB7C7F} - $(MSBuildProjectName) - 1 - false - true - Debug - Win32 - {8FD6D25D-F593-45DB-AF96-6F358E01587B} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - ;%(AdditionalIncludeDirectories) - stdAfx.h - Use - $(IntDir)\stdafx.pch - - - true - true - internal.h - ;%(AdditionalIncludeDirectories) - stdAfx.h - Use - $(IntDir)\stdafx.pch - - - true - true - internal.h - ;%(AdditionalIncludeDirectories) - stdAfx.h - Use - $(IntDir)\stdafx.pch - - - true - true - internal.h - ;%(AdditionalIncludeDirectories) - stdAfx.h - Use - $(IntDir)\stdafx.pch - - - true - true - internal.h - ;%(AdditionalIncludeDirectories) - stdAfx.h - Use - $(IntDir)\stdafx.pch - - - $(InfArch) - true - true - .\$(IntDir)\WUDFToaster.inf - - - true - true - internal.h - - - - WUDFToaster - - - WUDFToaster - - - WUDFToaster - - - WUDFToaster - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - true - Level4 - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - true - Level4 - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - true - Level4 - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - true - Level4 - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - %(PreprocessorDefinitions);DEBUG - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\uuid.lib;$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\advapi32.lib - WUDFToaster.def - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\uuid.lib;$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\advapi32.lib - WUDFToaster.def - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\uuid.lib;$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\advapi32.lib - WUDFToaster.def - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - - - %(AdditionalIncludeDirectories);.;.\$(IntDir);..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\uuid.lib;$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\advapi32.lib - WUDFToaster.def - - - - - ;%(AdditionalIncludeDirectories) - stdAfx.h - Create - $(IntDir)\stdafx.pch - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj.Filters b/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj.Filters deleted file mode 100644 index b64202cfd..000000000 --- a/general/toaster/toastDrv/umdf/func/WUDFToaster.vcxproj.Filters +++ /dev/null @@ -1,55 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {9ACEB224-90E2-40F2-838C-9F279873D314} - - - h;hpp;hxx;hm;inl;inc;xsd - {150AE92E-5F8C-4B90-B7BE-352ECA0434CD} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {BBE5A5E9-E1F7-47E7-91B7-111A3D0BAE2A} - - - inf;inv;inx;mof;mc; - {CCF62242-AF1C-424F-942F-E11D79A0EF79} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/general/toaster/toastDrv/umdf/func/internal.h b/general/toaster/toastDrv/umdf/func/internal.h deleted file mode 100644 index 1a098a19d..000000000 --- a/general/toaster/toastDrv/umdf/func/internal.h +++ /dev/null @@ -1,114 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Toaster - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CDriver *PCDriver; -typedef class CDevice *PCDevice; -typedef class CQueue *PCQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (9B6DE419,5658,46c9,A358,54FDEBB6B89D), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\WUDF\\Toaster" -#define MYDRIVER_CLASS_ID {0x7ab7dcf5, 0xd1d4, 0x4085, {0x95, 0x47, 0x1d, 0xb9, 0x68, 0xcc, 0xa7, 0x20}} - -// -// Include the type specific headers. -// - -#include "driver.h" -#include "device.h" -#include "queue.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - - - diff --git a/general/toaster/toastDrv/umdf/func/resource.h b/general/toaster/toastDrv/umdf/func/resource.h deleted file mode 100644 index 800c5a813..000000000 --- a/general/toaster/toastDrv/umdf/func/resource.h +++ /dev/null @@ -1,13 +0,0 @@ -#define IDS_PROJNAME 100 -#define IDR_TOASTERDRIVER 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_COMMAND_VALUE 32768 -#define _APS_NEXT_CONTROL_VALUE 201 -#define _APS_NEXT_SYMED_VALUE 105 -#endif -#endif diff --git a/general/toaster/toastDrv/umdf/func/stdAfxsrc.cpp b/general/toaster/toastDrv/umdf/func/stdAfxsrc.cpp deleted file mode 100644 index 15f34744f..000000000 --- a/general/toaster/toastDrv/umdf/func/stdAfxsrc.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "stdAfx.h" \ No newline at end of file diff --git a/general/toaster/toastDrv/umdf/func/stdafx.cpp b/general/toaster/toastDrv/umdf/func/stdafx.cpp deleted file mode 100644 index 16521f2af..000000000 --- a/general/toaster/toastDrv/umdf/func/stdafx.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - stdafx.cpp - - Abstract: - - This is used to build the precompiled header. - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - - -#include "stdafx.h" - -#include "initguid.h" - -DEFINE_GUID (GUID_DEVINTERFACE_TOASTER, - 0x781EF630, 0x72B2, 0x11d2, 0xB8, 0x52, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); -//{781EF630-72B2-11d2-B852-00C04FAD5171} - diff --git a/general/toaster/toastDrv/umdf/func/stdafx.h b/general/toaster/toastDrv/umdf/func/stdafx.h deleted file mode 100644 index 7e4324968..000000000 --- a/general/toaster/toastDrv/umdf/func/stdafx.h +++ /dev/null @@ -1,47 +0,0 @@ -/*++ - - Copyright (c) Microsoft Corporation, All Rights Reserved - - Module Name: - - stdafx.h - - Abstract: - - Include file for standard system include filesor project specific - include files that are used frequently, but are changed infrequently - - Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - - -#pragma once - -#ifndef STRICT -#define STRICT -#endif - - -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0501 // Windows XP and newer. -#endif - -#define _ATL_FREE_THREADED -#define _ATL_NO_AUTOMATIC_NAMESPACE - -// turns off ATL's hiding of some common and often safely ignored warning messages -#define _ATL_ALL_WARNINGS - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} - -#include "resource.h" -#include -#include - -extern const GUID GUID_DEVINTERFACE_TOASTER; - -using namespace ATL; - diff --git a/general/toaster/toastpkg/inf/toastpkg.inf b/general/toaster/toastpkg/inf/toastpkg.inf index f7e45bd95..d1e3fbffa 100644 Binary files a/general/toaster/toastpkg/inf/toastpkg.inf and b/general/toaster/toastpkg/inf/toastpkg.inf differ diff --git a/general/toaster/toastpkg/toastapp/toastapp.vcxproj b/general/toaster/toastpkg/toastapp/toastapp.vcxproj index 99f5d3ed3..86840c1c8 100644 --- a/general/toaster/toastpkg/toastapp/toastapp.vcxproj +++ b/general/toaster/toastpkg/toastapp/toastapp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/toastpkg/toastcd/ToastApp/setup.exe b/general/toaster/toastpkg/toastcd/ToastApp/setup.exe deleted file mode 100644 index 9fcedf961..000000000 Binary files a/general/toaster/toastpkg/toastcd/ToastApp/setup.exe and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/ToastApp/setup.ini b/general/toaster/toastpkg/toastcd/ToastApp/setup.ini deleted file mode 100644 index 81d61154e..000000000 Binary files a/general/toaster/toastpkg/toastcd/ToastApp/setup.ini and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/ToastApp/toastapp.msi b/general/toaster/toastpkg/toastcd/ToastApp/toastapp.msi deleted file mode 100644 index 0bdfaa653..000000000 Binary files a/general/toaster/toastpkg/toastcd/ToastApp/toastapp.msi and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/amd64/toaster.sys b/general/toaster/toastpkg/toastcd/amd64/toaster.sys deleted file mode 100644 index d51da6c40..000000000 Binary files a/general/toaster/toastpkg/toastcd/amd64/toaster.sys and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/amd64/toastva.exe b/general/toaster/toastpkg/toastcd/amd64/toastva.exe deleted file mode 100644 index ebd46df9a..000000000 Binary files a/general/toaster/toastpkg/toastcd/amd64/toastva.exe and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/amd64/tostrco2.dll b/general/toaster/toastpkg/toastcd/amd64/tostrco2.dll deleted file mode 100644 index 58dfab320..000000000 Binary files a/general/toaster/toastpkg/toastcd/amd64/tostrco2.dll and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/autorun.inf b/general/toaster/toastpkg/toastcd/autorun.inf deleted file mode 100644 index ee67cf9a4..000000000 --- a/general/toaster/toastpkg/toastcd/autorun.inf +++ /dev/null @@ -1,12 +0,0 @@ -[AutoRun] -open=i386\toastva.exe -icon=i386\toastva.exe,0 - -[AutoRun.i386] -open=i386\toastva.exe - -[AutoRun.amd64] -open=amd64\toastva.exe - -[DeviceInstall] -DriverPath=\ diff --git a/general/toaster/toastpkg/toastcd/i386/toaster.sys b/general/toaster/toastpkg/toastcd/i386/toaster.sys deleted file mode 100644 index 19184dc9d..000000000 Binary files a/general/toaster/toastpkg/toastcd/i386/toaster.sys and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/i386/toastva.exe b/general/toaster/toastpkg/toastcd/i386/toastva.exe deleted file mode 100644 index 7bbb4a47c..000000000 Binary files a/general/toaster/toastpkg/toastcd/i386/toastva.exe and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/i386/tostrco2.dll b/general/toaster/toastpkg/toastcd/i386/tostrco2.dll deleted file mode 100644 index 3f7b3ed12..000000000 Binary files a/general/toaster/toastpkg/toastcd/i386/tostrco2.dll and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/toastpkg.inf b/general/toaster/toastpkg/toastcd/toastpkg.inf deleted file mode 100644 index f7e45bd95..000000000 --- a/general/toaster/toastpkg/toastcd/toastpkg.inf +++ /dev/null @@ -1,120 +0,0 @@ -;/*++ -; -;Copyright (c) Microsoft Corporation. All rights reserved. -; -; THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY -; KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR -; PURPOSE. -; -;Module Name: -; -; TOASTPKG.INF -; -;Abstract: -; -; INF file for installing toaster device drivers (and, optionally, value- -; added software) via device-specific coinstaller. -; This is a mutlios INF file. Same INF file cab be used on -; x86 and amd64 platforms. -; -;--*/ -[Version] -Signature="$WINDOWS NT$" -Class=TOASTER -ClassGuid={B85B7C50-6A01-11d2-B841-00C04FAD5171} -Provider=%ProviderName% -DriverVer=09/21/2006,6.0.5736.1 -CatalogFile.NTx86 = tostx86.cat -CatalogFile.NTAMD64 = tstamd64.cat -PnpLockdown=1 - -[DestinationDirs] -DefaultDestDir = 12 -CoInstaller_CopyFiles = 11 - -; ================= Class section ===================== - -[ClassInstall32] -Addreg=ToasterClassReg - -[ToasterClassReg] -HKR,,,0,%ClassName% -HKR,,Icon,,100 -HKR,,DeviceCharacteristics,0x10001,0x100 ; Use same security checks on relative opens - -;***************************************** -; Toaster Device Install Section -;***************************************** - -[Manufacturer] -%ToastRUs%=ToastRUs,NTx86, NTamd64 - -[ToastRUs.NTx86] -%ToasterDevice.DeviceDesc%=Toaster_Device, {b85b7c50-6a01-11d2-b841-00c04fad5171}\MsToaster - -[ToastRUs.NTamd64] -%ToasterDevice.DeviceDesc%=Toaster_Device, {b85b7c50-6a01-11d2-b841-00c04fad5171}\MsToaster - - -[Toaster_Device.NT] -CopyFiles=Toaster_Device.NT.Copy -FriendlyNameFormat=%FriendlyNameFormat% - -[Toaster_Device.NT.Copy] -toaster.sys - -[Toaster_Device.NT.HW] -AddReg=Toaster_Device.NT.HW.AddReg - -[Toaster_Device.NT.HW.AddReg] -HKR,,"BeepCount",0x00010003,4 - -;-------------- Service installation - -[Toaster_Device.NT.Services] -AddService = toaster, %SPSVCINST_ASSOCSERVICE%, toaster_Service_Inst - -[toaster_Service_Inst] -DisplayName = %toaster.SVCDESC% -ServiceType = 1 ; SERVICE_KERNEL_DRIVER -StartType = 3 ; SERVICE_DEMAND_START -ErrorControl = 1 ; SERVICE_ERROR_NORMAL -ServiceBinary = %12%\toaster.sys - -;-------------- Coinstaller installation - -[Toaster_Device.NT.CoInstallers] -AddReg=CoInstaller_AddReg -CopyFiles=CoInstaller_CopyFiles - -[CoInstaller_CopyFiles] -tostrco2.dll - -[CoInstaller_AddReg] -HKR,,CoInstallers32,0x00010000,"tostrco2.dll,ToasterCoInstaller" - -[ToastCoInfo] -; Used by the toaster co-installer to figure out where the original media is -; located (so it can launch value-added setup programs). -OriginalInfSourcePath = %1% - -[SourceDisksNames.x86] -1 = %DiskId1%, toastpkg.tag,,\i386 - -[SourceDisksNames.amd64] -1 = %DiskId1%, toastpkg.tag,,\amd64 - -[SourceDisksFiles] -toaster.sys = 1,, -tostrco2.dll = 1,, - -[Strings] -SPSVCINST_ASSOCSERVICE= 0x00000002 -ProviderName = "TODO-Set-Provider" -ToastRUs = "Toast'R'Us" -ClassName = "Toaster" -DiskId1 = "Toaster Device Installation Disk #1" -ToasterDevice.DeviceDesc = "Toaster Package Sample Toaster" -toaster.SVCDESC = "Toaster Device Driver" -FriendlyNameFormat = "ToasterDevice%1!u!" diff --git a/general/toaster/toastpkg/toastcd/toastpkg.tag b/general/toaster/toastpkg/toastcd/toastpkg.tag deleted file mode 100644 index e69de29bb..000000000 diff --git a/general/toaster/toastpkg/toastcd/tostx86.cat b/general/toaster/toastpkg/toastcd/tostx86.cat deleted file mode 100644 index e8b604b5a..000000000 Binary files a/general/toaster/toastpkg/toastcd/tostx86.cat and /dev/null differ diff --git a/general/toaster/toastpkg/toastcd/tstamd64.cat b/general/toaster/toastpkg/toastcd/tstamd64.cat deleted file mode 100644 index cd1a8eb67..000000000 Binary files a/general/toaster/toastpkg/toastcd/tstamd64.cat and /dev/null differ diff --git a/general/toaster/umdf2/README.md b/general/toaster/umdf2/README.md index fb3741c62..a2e6c7c00 100644 --- a/general/toaster/umdf2/README.md +++ b/general/toaster/umdf2/README.md @@ -50,7 +50,7 @@ Before you manually deploy a driver, you must turn on test signing and install a ### View the root enumerated driver in Device Manager -On the target computer, in a Command Prompt window, enter **devmgmt** to open Device Manager. In Device Manager, on the **View** menu, choose **Devices by type**. In the device tree, locate **Sample WDF Toaster Service + Filter** (for example, this might be under the **Toaster** node). +On the target computer, in a Command Prompt window, enter **devmgmt.msc** to open Device Manager. In Device Manager, on the **View** menu, choose **Devices by type**. In the device tree, locate **Sample WDF Toaster Service + Filter** (for example, this might be under the **Toaster** node). In Device Manager, on the **View** menu, choose **Devices by connection**. Locate **Sample WDF Toaster Service + Filter** as a child of the root node of the device tree. diff --git a/general/toaster/umdf2/exe/enum/Enum.vcxproj b/general/toaster/umdf2/exe/enum/Enum.vcxproj index 3638bd18d..3b8bcbb62 100644 --- a/general/toaster/umdf2/exe/enum/Enum.vcxproj +++ b/general/toaster/umdf2/exe/enum/Enum.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/toaster/umdf2/exe/notify/notify.c b/general/toaster/umdf2/exe/notify/notify.c index 3362ce3d9..15e5a615b 100644 --- a/general/toaster/umdf2/exe/notify/notify.c +++ b/general/toaster/umdf2/exe/notify/notify.c @@ -35,7 +35,7 @@ Revision History: // Annotation to indicate to prefast that this is nondriver user-mode code. // #include -_Analysis_mode_(_Analysis_code_type_user_code_) +_Analysis_mode_(_Analysis_code_type_user_code_) #include #include @@ -494,7 +494,7 @@ HandleDeviceInterfaceChange( if(!GetDeviceDescription(dip->dbcc_name, - (PBYTE)deviceInfo->DeviceName, + deviceInfo->DeviceName, sizeof(deviceInfo->DeviceName), &deviceInfo->SerialNo)) { MessageBox(hWnd, TEXT("GetDeviceDescription failed"), TEXT("Error!"), MB_OK); @@ -783,7 +783,7 @@ EnumExistingDevices( // Get the device details such as friendly name and SerialNo // if(!GetDeviceDescription(deviceInterfaceDetailData->DevicePath, - (PBYTE)deviceInfo->DeviceName, + deviceInfo->DeviceName, sizeof(deviceInfo->DeviceName), &deviceInfo->SerialNo)){ goto Error; @@ -873,7 +873,7 @@ BOOLEAN Cleanup(HWND hWnd) BOOL GetDeviceDescription( _In_ LPTSTR DevPath, - _Out_writes_bytes_(OutBufferLen) PBYTE OutBuffer, + _Out_writes_bytes_(OutBufferLen) PTSTR OutBuffer, _In_ ULONG OutBufferLen, _In_ PULONG SerialNo ) @@ -917,14 +917,14 @@ GetDeviceDescription( if(!SetupDiGetDeviceRegistryProperty(hardwareDeviceInfo, &deviceInfoData, SPDRP_FRIENDLYNAME, &dwRegType, - OutBuffer, + (PBYTE) OutBuffer, OutBufferLen, NULL)) { if(!SetupDiGetDeviceRegistryProperty(hardwareDeviceInfo, &deviceInfoData, SPDRP_DEVICEDESC, &dwRegType, - OutBuffer, + (PBYTE) OutBuffer, OutBufferLen, NULL)){ goto Error; diff --git a/general/toaster/umdf2/exe/notify/notify.h b/general/toaster/umdf2/exe/notify/notify.h index 98db2918b..7bddb5474 100644 --- a/general/toaster/umdf2/exe/notify/notify.h +++ b/general/toaster/umdf2/exe/notify/notify.h @@ -154,7 +154,7 @@ BOOLEAN Cleanup( BOOL GetDeviceDescription( _In_ LPTSTR DevPath, - _Out_writes_bytes_(OutBufferLen) PBYTE OutBuffer, + _Out_writes_bytes_(OutBufferLen) PTSTR OutBuffer, _In_ ULONG OutBufferLen, _In_ PULONG SerialNo ); diff --git a/general/toaster/umdf2/filter/generic/filterum.inx b/general/toaster/umdf2/filter/generic/filterum.inx index 4de6d127e..e7e04b65e 100644 Binary files a/general/toaster/umdf2/filter/generic/filterum.inx and b/general/toaster/umdf2/filter/generic/filterum.inx differ diff --git a/general/toaster/umdf2/filter/generic/filterum.vcxproj b/general/toaster/umdf2/filter/generic/filterum.vcxproj index e292101c0..bd2da6467 100644 --- a/general/toaster/umdf2/filter/generic/filterum.vcxproj +++ b/general/toaster/umdf2/filter/generic/filterum.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/general/toaster/umdf2/func/featured/wdffeaturedum.inx b/general/toaster/umdf2/func/featured/wdffeaturedum.inx index c4e79f134..7b5f9c075 100644 Binary files a/general/toaster/umdf2/func/featured/wdffeaturedum.inx and b/general/toaster/umdf2/func/featured/wdffeaturedum.inx differ diff --git a/general/toaster/umdf2/func/featured/wdffeaturedum.vcxproj b/general/toaster/umdf2/func/featured/wdffeaturedum.vcxproj index def844d2e..9bd4dfb73 100644 --- a/general/toaster/umdf2/func/featured/wdffeaturedum.vcxproj +++ b/general/toaster/umdf2/func/featured/wdffeaturedum.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/general/toaster/umdf2/func/simple/wdfsimpleum.inx b/general/toaster/umdf2/func/simple/wdfsimpleum.inx index 44252e4e3..e07cf3a13 100644 Binary files a/general/toaster/umdf2/func/simple/wdfsimpleum.inx and b/general/toaster/umdf2/func/simple/wdfsimpleum.inx differ diff --git a/general/toaster/umdf2/func/simple/wdfsimpleum.vcxproj b/general/toaster/umdf2/func/simple/wdfsimpleum.vcxproj index d12c5713d..05353419e 100644 --- a/general/toaster/umdf2/func/simple/wdfsimpleum.vcxproj +++ b/general/toaster/umdf2/func/simple/wdfsimpleum.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/general/tracing/evntdrv/Eventdrv/Eventdrv.vcxproj b/general/tracing/evntdrv/Eventdrv/Eventdrv.vcxproj index f919e0469..ad45a08e8 100644 --- a/general/tracing/evntdrv/Eventdrv/Eventdrv.vcxproj +++ b/general/tracing/evntdrv/Eventdrv/Eventdrv.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/tracing/evntdrv/evntctrl/evntctrl.vcxproj b/general/tracing/evntdrv/evntctrl/evntctrl.vcxproj index 83d793ef6..4a21b1aab 100644 --- a/general/tracing/evntdrv/evntctrl/evntctrl.vcxproj +++ b/general/tracing/evntdrv/evntctrl/evntctrl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/tracing/tracedriver/tracectl/tracectl.vcxproj b/general/tracing/tracedriver/tracectl/tracectl.vcxproj index fb27137fe..50f62668b 100644 --- a/general/tracing/tracedriver/tracectl/tracectl.vcxproj +++ b/general/tracing/tracedriver/tracectl/tracectl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/general/tracing/tracedriver/tracedrv/tracedrv.vcxproj b/general/tracing/tracedriver/tracedrv/tracedrv.vcxproj index eb78d92c7..121e210cb 100644 --- a/general/tracing/tracedriver/tracedrv/tracedrv.vcxproj +++ b/general/tracing/tracedriver/tracedrv/tracedrv.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/general/umdfSkeleton/README.md b/general/umdfSkeleton/README.md deleted file mode 100644 index 59a5f25b0..000000000 --- a/general/umdfSkeleton/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -page_type: sample -description: "Demonstrates how to use UDMF to write a minimal driver." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# UMDF Driver Skeleton Sample (UMDF Version 1) - -This sample demonstrates how to use version 1 of the User-Mode Driver Framework to write a minimal driver. - -The Skeleton driver will successfully load on a device (either root enumerated or a real hardware device) but does not support any I/O operations. diff --git a/general/umdfSkeleton/Skeleton.rc b/general/umdfSkeleton/Skeleton.rc deleted file mode 100644 index b6ecda7f3..000000000 --- a/general/umdfSkeleton/Skeleton.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// Skeleton.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF Skeleton User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "UMDFSkeleton" -#define VER_ORIGINALFILENAME_STR "UMDFSkeleton.dll" - -#include "common.ver" diff --git a/general/umdfSkeleton/UMDFSkeleton.vcxproj b/general/umdfSkeleton/UMDFSkeleton.vcxproj deleted file mode 100644 index 86f138349..000000000 --- a/general/umdfSkeleton/UMDFSkeleton.vcxproj +++ /dev/null @@ -1,265 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {6C720AF2-E419-4BA6-927C-607BE3E771F1} - $(MSBuildProjectName) - 1 - 1 - 9 - 9 - Debug - Win32 - {B7203DC7-2002-4983-AB0B-E567DC6BD66C} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - UMDFSkeleton - - - UMDFSkeleton - - - UMDFSkeleton - - - UMDFSkeleton - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/general/umdfSkeleton/UMDFSkeleton.vcxproj.Filters b/general/umdfSkeleton/UMDFSkeleton.vcxproj.Filters deleted file mode 100644 index 7da6c076c..000000000 --- a/general/umdfSkeleton/UMDFSkeleton.vcxproj.Filters +++ /dev/null @@ -1,43 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {B6F807E5-006F-4FBD-BB35-CC706D5CB468} - - - h;hpp;hxx;hm;inl;inc;xsd - {66714BFC-1D46-4D92-A154-1C6DFF39E4D4} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {B398CF71-A6A3-49C5-A7EC-47876A953477} - - - inf;inv;inx;mof;mc; - {1A124126-5375-4543-880D-28113FEF151C} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/general/umdfSkeleton/UMDFSkeleton_OSR.inx b/general/umdfSkeleton/UMDFSkeleton_OSR.inx deleted file mode 100644 index 9729eee72..000000000 Binary files a/general/umdfSkeleton/UMDFSkeleton_OSR.inx and /dev/null differ diff --git a/general/umdfSkeleton/UMDFSkeleton_Root.inx b/general/umdfSkeleton/UMDFSkeleton_Root.inx deleted file mode 100644 index abb05491a..000000000 Binary files a/general/umdfSkeleton/UMDFSkeleton_Root.inx and /dev/null differ diff --git a/general/umdfSkeleton/comsup.cpp b/general/umdfSkeleton/comsup.cpp deleted file mode 100644 index fd2984700..000000000 --- a/general/umdfSkeleton/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/general/umdfSkeleton/comsup.h b/general/umdfSkeleton/comsup.h deleted file mode 100644 index 5472338cf..000000000 --- a/general/umdfSkeleton/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/general/umdfSkeleton/device.cpp b/general/umdfSkeleton/device.cpp deleted file mode 100644 index 677f39e60..000000000 --- a/general/umdfSkeleton/device.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton sample driver's - device callback object. - - The skeleton sample device does very little. It does not implement either - of the PNP interfaces so once the device is setup, it won't ever get any - callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the skeleton driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - // - // TODO: Setup your device queues and I/O forwarding. - // - - return S_OK; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the skeleton driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the skeleton is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - return CUnknown::QueryInterface(InterfaceId, Object); -} diff --git a/general/umdfSkeleton/device.h b/general/umdfSkeleton/device.h deleted file mode 100644 index d5e1baa6b..000000000 --- a/general/umdfSkeleton/device.h +++ /dev/null @@ -1,115 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the iotrace driver. -// - -class CMyDevice : public CUnknown -{ - -// -// Private data members. -// -private: - - IWDFDevice *m_FxDevice; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) - { - m_FxDevice = NULL; - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - -}; diff --git a/general/umdfSkeleton/dllsup.cpp b/general/umdfSkeleton/dllsup.cpp deleted file mode 100644 index 3a59f3039..000000000 --- a/general/umdfSkeleton/dllsup.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - UNREFERENCED_PARAMETER( ModuleHandle ); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -HRESULT -STDAPICALLTYPE -DllGetClassObject( - _In_ REFCLSID ClassId, - _In_ REFIID InterfaceId, - _Outptr_ LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/general/umdfSkeleton/driver.cpp b/general/umdfSkeleton/driver.cpp deleted file mode 100644 index 2061ec2d0..000000000 --- a/general/umdfSkeleton/driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/general/umdfSkeleton/driver.h b/general/umdfSkeleton/driver.h deleted file mode 100644 index c5664ac02..000000000 --- a/general/umdfSkeleton/driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the skeleton sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/general/umdfSkeleton/exports.def b/general/umdfSkeleton/exports.def deleted file mode 100644 index a1ab223c2..000000000 --- a/general/umdfSkeleton/exports.def +++ /dev/null @@ -1,10 +0,0 @@ -; Skeleton.def : Declares the module parameters. - -; -; TODO: Change the library name here to match your binary name. -; - -LIBRARY "UMDFSkeleton.DLL" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/general/umdfSkeleton/internal.h b/general/umdfSkeleton/internal.h deleted file mode 100644 index bd8c3c6d5..000000000 --- a/general/umdfSkeleton/internal.h +++ /dev/null @@ -1,90 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Skeleton - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (e7541cdd,30e8,4b50,aeb0,51927330ae64), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\Skeleton" -#define MYDRIVER_CLASS_ID { 0xd4112073, 0xd09b, 0x458f, { 0xa5, 0xaa, 0x35, 0xef, 0x21, 0xee, 0xf5, 0xde } } - - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" diff --git a/general/umdfSkeleton/umdfSkeleton.sln b/general/umdfSkeleton/umdfSkeleton.sln deleted file mode 100644 index c8432e900..000000000 --- a/general/umdfSkeleton/umdfSkeleton.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UMDFSkeleton", "UMDFSkeleton.vcxproj", "{6C720AF2-E419-4BA6-927C-607BE3E771F1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Debug|Win32.ActiveCfg = Debug|Win32 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Debug|Win32.Build.0 = Debug|Win32 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Release|Win32.ActiveCfg = Release|Win32 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Release|Win32.Build.0 = Release|Win32 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Debug|x64.ActiveCfg = Debug|x64 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Debug|x64.Build.0 = Debug|x64 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Release|x64.ActiveCfg = Release|x64 - {6C720AF2-E419-4BA6-927C-607BE3E771F1}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/gpio/samples/simdevice/kmdf/simdevice.inx b/gpio/samples/simdevice/kmdf/simdevice.inx index 48f8a52d7..c758f27a9 100644 Binary files a/gpio/samples/simdevice/kmdf/simdevice.inx and b/gpio/samples/simdevice/kmdf/simdevice.inx differ diff --git a/gpio/samples/simdevice/umdf/simdeviceumdf.inx b/gpio/samples/simdevice/umdf/simdeviceumdf.inx index 3c0def967..ef471b770 100644 Binary files a/gpio/samples/simdevice/umdf/simdeviceumdf.inx and b/gpio/samples/simdevice/umdf/simdeviceumdf.inx differ diff --git a/gpio/samples/simgpio/simgpio.inx b/gpio/samples/simgpio/simgpio.inx index b0a724e29..32ad72fe8 100644 Binary files a/gpio/samples/simgpio/simgpio.inx and b/gpio/samples/simgpio/simgpio.inx differ diff --git a/gpio/samples/simgpio/simgpio.vcxproj b/gpio/samples/simgpio/simgpio.vcxproj index 98e5f591a..83cb53bd4 100644 --- a/gpio/samples/simgpio/simgpio.vcxproj +++ b/gpio/samples/simgpio/simgpio.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/gpio/samples/simgpio_i2c/simgpio_i2c.inx b/gpio/samples/simgpio_i2c/simgpio_i2c.inx index ffe920426..32ec15734 100644 Binary files a/gpio/samples/simgpio_i2c/simgpio_i2c.inx and b/gpio/samples/simgpio_i2c/simgpio_i2c.inx differ diff --git a/gpio/samples/simgpio_i2c/simgpio_i2c.vcxproj b/gpio/samples/simgpio_i2c/simgpio_i2c.vcxproj index ba8bf9e5b..981f6178a 100644 --- a/gpio/samples/simgpio_i2c/simgpio_i2c.vcxproj +++ b/gpio/samples/simgpio_i2c/simgpio_i2c.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/hid/firefly/app/flicker.vcxproj b/hid/firefly/app/flicker.vcxproj index eabedfbb7..4fad04932 100644 --- a/hid/firefly/app/flicker.vcxproj +++ b/hid/firefly/app/flicker.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/hid/firefly/driver/firefly.inx b/hid/firefly/driver/firefly.inx index da7c841cb..caab90fc5 100644 Binary files a/hid/firefly/driver/firefly.inx and b/hid/firefly/driver/firefly.inx differ diff --git a/hid/firefly/driver/firefly.vcxproj b/hid/firefly/driver/firefly.vcxproj index a86c03a8d..1530c39d9 100644 --- a/hid/firefly/driver/firefly.vcxproj +++ b/hid/firefly/driver/firefly.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/hid/firefly/lib/Luminous.vcxproj b/hid/firefly/lib/Luminous.vcxproj index 83515b31e..e879b7fcb 100644 --- a/hid/firefly/lib/Luminous.vcxproj +++ b/hid/firefly/lib/Luminous.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary diff --git a/hid/firefly/sauron/SAURON.vcxproj b/hid/firefly/sauron/SAURON.vcxproj index 4fc980ddf..ae077a7d6 100644 --- a/hid/firefly/sauron/SAURON.vcxproj +++ b/hid/firefly/sauron/SAURON.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/hid/hidusbfx2/hidkmdf/hidkmdf.vcxproj b/hid/hidusbfx2/hidkmdf/hidkmdf.vcxproj index 4e5e456f2..e1352f602 100644 --- a/hid/hidusbfx2/hidkmdf/hidkmdf.vcxproj +++ b/hid/hidusbfx2/hidkmdf/hidkmdf.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/hid/hidusbfx2/sys/hidusbfx2.inx b/hid/hidusbfx2/sys/hidusbfx2.inx index 90153f380..7d65ab567 100644 Binary files a/hid/hidusbfx2/sys/hidusbfx2.inx and b/hid/hidusbfx2/sys/hidusbfx2.inx differ diff --git a/hid/hidusbfx2/sys/hidusbfx2.vcxproj b/hid/hidusbfx2/sys/hidusbfx2.vcxproj index 72916d1e7..8df137b8b 100644 --- a/hid/hidusbfx2/sys/hidusbfx2.vcxproj +++ b/hid/hidusbfx2/sys/hidusbfx2.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/hid/vhidmini2/app/testvhid.vcxproj b/hid/vhidmini2/app/testvhid.vcxproj index e728b88c9..f87a1a075 100644 --- a/hid/vhidmini2/app/testvhid.vcxproj +++ b/hid/vhidmini2/app/testvhid.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/hid/vhidmini2/driver/kmdf/vhidmini.inx b/hid/vhidmini2/driver/kmdf/vhidmini.inx index d16724cab..007f00626 100644 Binary files a/hid/vhidmini2/driver/kmdf/vhidmini.inx and b/hid/vhidmini2/driver/kmdf/vhidmini.inx differ diff --git a/hid/vhidmini2/driver/kmdf/vhidmini.vcxproj b/hid/vhidmini2/driver/kmdf/vhidmini.vcxproj index 4f712d804..d1f5ba70d 100644 --- a/hid/vhidmini2/driver/kmdf/vhidmini.vcxproj +++ b/hid/vhidmini2/driver/kmdf/vhidmini.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/hid/vhidmini2/driver/umdf2/VhidminiUm.inx b/hid/vhidmini2/driver/umdf2/VhidminiUm.inx index 2b449fe75..1911cfba7 100644 Binary files a/hid/vhidmini2/driver/umdf2/VhidminiUm.inx and b/hid/vhidmini2/driver/umdf2/VhidminiUm.inx differ diff --git a/hid/vhidmini2/driver/umdf2/VhidminiUm.vcxproj b/hid/vhidmini2/driver/umdf2/VhidminiUm.vcxproj index a7607db8d..0bc198e8d 100644 --- a/hid/vhidmini2/driver/umdf2/VhidminiUm.vcxproj +++ b/hid/vhidmini2/driver/umdf2/VhidminiUm.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/input/kbfiltr/sys/kbfiltr.inx b/input/kbfiltr/sys/kbfiltr.inx index 6f7db255b..1412bc671 100644 Binary files a/input/kbfiltr/sys/kbfiltr.inx and b/input/kbfiltr/sys/kbfiltr.inx differ diff --git a/input/kbfiltr/sys/kbfiltr.vcxproj b/input/kbfiltr/sys/kbfiltr.vcxproj index f26a765d6..ad4d5a328 100644 --- a/input/kbfiltr/sys/kbfiltr.vcxproj +++ b/input/kbfiltr/sys/kbfiltr.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/input/layout/all_kbds/kbdfr/kbdfr.vcxproj b/input/layout/all_kbds/kbdfr/kbdfr.vcxproj index d42525208..08adb7306 100644 --- a/input/layout/all_kbds/kbdfr/kbdfr.vcxproj +++ b/input/layout/all_kbds/kbdfr/kbdfr.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/input/layout/all_kbds/kbdgr/kbdgr.vcxproj b/input/layout/all_kbds/kbdgr/kbdgr.vcxproj index c59a9625b..c2e9fb827 100644 --- a/input/layout/all_kbds/kbdgr/kbdgr.vcxproj +++ b/input/layout/all_kbds/kbdgr/kbdgr.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/input/layout/fe_kbds/jpn/101/kbd101.vcxproj b/input/layout/fe_kbds/jpn/101/kbd101.vcxproj index 0c56f44cb..40bfd37ee 100644 --- a/input/layout/fe_kbds/jpn/101/kbd101.vcxproj +++ b/input/layout/fe_kbds/jpn/101/kbd101.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/input/layout/fe_kbds/jpn/106/kbd106.vcxproj b/input/layout/fe_kbds/jpn/106/kbd106.vcxproj index 0d14c18d8..70a9e8ad1 100644 --- a/input/layout/fe_kbds/jpn/106/kbd106.vcxproj +++ b/input/layout/fe_kbds/jpn/106/kbd106.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/input/layout/kbdus/kbdus.vcxproj b/input/layout/kbdus/kbdus.vcxproj index 7e14a70b9..2c1fa83a7 100644 --- a/input/layout/kbdus/kbdus.vcxproj +++ b/input/layout/kbdus/kbdus.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/input/moufiltr/moufiltr.inx b/input/moufiltr/moufiltr.inx index fe547b21a..c3cf47c42 100644 Binary files a/input/moufiltr/moufiltr.inx and b/input/moufiltr/moufiltr.inx differ diff --git a/input/moufiltr/moufiltr.vcxproj b/input/moufiltr/moufiltr.vcxproj index bc0ea8fd4..eae59cdb4 100644 --- a/input/moufiltr/moufiltr.vcxproj +++ b/input/moufiltr/moufiltr.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/modem/fakemodem/mdmfake.inx b/network/modem/fakemodem/mdmfake.inx index 688cd08fb..ea95a9adb 100644 Binary files a/network/modem/fakemodem/mdmfake.inx and b/network/modem/fakemodem/mdmfake.inx differ diff --git a/network/ndis/extension/base/sxbase.vcxproj b/network/ndis/extension/base/sxbase.vcxproj index 40b69bc3c..aa23ad514 100644 --- a/network/ndis/extension/base/sxbase.vcxproj +++ b/network/ndis/extension/base/sxbase.vcxproj @@ -21,7 +21,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 StaticLibrary @@ -29,7 +29,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 StaticLibrary diff --git a/network/ndis/extension/samples/forward/msforwardext.inf b/network/ndis/extension/samples/forward/msforwardext.inf index 9d3d587c2..4af1b0fb1 100644 Binary files a/network/ndis/extension/samples/forward/msforwardext.inf and b/network/ndis/extension/samples/forward/msforwardext.inf differ diff --git a/network/ndis/extension/samples/forward/msforwardext.vcxproj b/network/ndis/extension/samples/forward/msforwardext.vcxproj index 959386bc5..7efe88a3c 100644 --- a/network/ndis/extension/samples/forward/msforwardext.vcxproj +++ b/network/ndis/extension/samples/forward/msforwardext.vcxproj @@ -21,7 +21,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -29,7 +29,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -82,6 +82,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib;.\..\..\base\$(IntDir)\sxbase.lib + true true diff --git a/network/ndis/extension/samples/passthrough/mspassthroughext.inf b/network/ndis/extension/samples/passthrough/mspassthroughext.inf index 6a5e0915d..8339e7c8d 100644 Binary files a/network/ndis/extension/samples/passthrough/mspassthroughext.inf and b/network/ndis/extension/samples/passthrough/mspassthroughext.inf differ diff --git a/network/ndis/extension/samples/passthrough/mspassthroughext.vcxproj b/network/ndis/extension/samples/passthrough/mspassthroughext.vcxproj index aaa7da8e2..f18ca5fa7 100644 --- a/network/ndis/extension/samples/passthrough/mspassthroughext.vcxproj +++ b/network/ndis/extension/samples/passthrough/mspassthroughext.vcxproj @@ -21,7 +21,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -29,7 +29,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -82,6 +82,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib;.\..\..\base\$(IntDir)\sxbase.lib + true true diff --git a/network/ndis/filter/filter.h b/network/ndis/filter/filter.h index bf8da200e..c21248d22 100644 --- a/network/ndis/filter/filter.h +++ b/network/ndis/filter/filter.h @@ -115,7 +115,7 @@ typedef struct _QUEUE_HEADER { PQUEUE_ENTRY Head; PQUEUE_ENTRY Tail; -} QUEUE_HEADER, PQUEUE_HEADER; +} QUEUE_HEADER, *PQUEUE_HEADER; #if TRACK_RECEIVES diff --git a/network/ndis/filter/ndislwf.vcxproj b/network/ndis/filter/ndislwf.vcxproj index fa4f9d396..456ac1317 100644 --- a/network/ndis/filter/ndislwf.vcxproj +++ b/network/ndis/filter/ndislwf.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -206,6 +206,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true diff --git a/network/ndis/filter/netlwf.inf b/network/ndis/filter/netlwf.inf index ae7287758..e59b56fbd 100644 Binary files a/network/ndis/filter/netlwf.inf and b/network/ndis/filter/netlwf.inf differ diff --git a/network/ndis/mux/driver/60/miniport.c b/network/ndis/mux/driver/60/miniport.c index e0c3e380b..f30c4b624 100644 --- a/network/ndis/mux/driver/60/miniport.c +++ b/network/ndis/mux/driver/60/miniport.c @@ -710,25 +710,23 @@ Return Value: NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR | NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR; - StatisticsInfo.ifInDiscards = pVElan->RcvCrcErrors + - pVElan->RcvAlignmentErrors + - pVElan->RcvResourceErrors + - pVElan->RcvDmaOverrunErrors + - pVElan->RcvRuntErrors; + StatisticsInfo.ifInDiscards = + (ULONG64)pVElan->RcvCrcErrors + + (ULONG64)pVElan->RcvAlignmentErrors + + (ULONG64)pVElan->RcvResourceErrors + + (ULONG64)pVElan->RcvDmaOverrunErrors + + (ULONG64)pVElan->RcvRuntErrors; #if IEEE_VLAN_SUPPORT - StatisticsInfo.ifInDiscards += (pVElan->RcvVlanIdErrors + - pVElan->RcvFormatErrors); + StatisticsInfo.ifInDiscards += ((ULONG64)pVElan->RcvVlanIdErrors + (ULONG64)pVElan->RcvFormatErrors); #endif - StatisticsInfo.ifInErrors = StatisticsInfo.ifInDiscards - - pVElan->RcvResourceErrors; + (ULONG64)pVElan->RcvResourceErrors; - - StatisticsInfo.ifOutErrors = pVElan->TxAbortExcessCollisions + - pVElan->TxDmaUnderrun + - pVElan->TxLostCRS + - pVElan->TxLateCollisions; + StatisticsInfo.ifOutErrors = (ULONG64)pVElan->TxAbortExcessCollisions + + (ULONG64)pVElan->TxDmaUnderrun + + (ULONG64)pVElan->TxLostCRS + + (ULONG64)pVElan->TxLateCollisions; pInfo = &StatisticsInfo; break; diff --git a/network/ndis/mux/driver/60/mux_mp.inf b/network/ndis/mux/driver/60/mux_mp.inf index 9c5f998c5..f216ac160 100644 Binary files a/network/ndis/mux/driver/60/mux_mp.inf and b/network/ndis/mux/driver/60/mux_mp.inf differ diff --git a/network/ndis/mux/driver/60/muxp.inf b/network/ndis/mux/driver/60/muxp.inf index 836e60e1d..f9c4c04e9 100644 Binary files a/network/ndis/mux/driver/60/muxp.inf and b/network/ndis/mux/driver/60/muxp.inf differ diff --git a/network/ndis/mux/driver/60/novlan/mux.vcxproj b/network/ndis/mux/driver/60/novlan/mux.vcxproj index 33700ad45..758f450fb 100644 --- a/network/ndis/mux/driver/60/novlan/mux.vcxproj +++ b/network/ndis/mux/driver/60/novlan/mux.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -182,6 +182,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true %(AdditionalIncludeDirectories);.. @@ -283,8 +284,21 @@ + + + + + + + + + + + + - + + diff --git a/network/ndis/mux/driver/60/novlan/mux.vcxproj.Filters b/network/ndis/mux/driver/60/novlan/mux.vcxproj.Filters index ff91d92c1..fe979006e 100644 --- a/network/ndis/mux/driver/60/novlan/mux.vcxproj.Filters +++ b/network/ndis/mux/driver/60/novlan/mux.vcxproj.Filters @@ -37,4 +37,12 @@ Resource Files + + + Driver Files + + + Driver Files + + \ No newline at end of file diff --git a/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj b/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj index b521aed62..eb2ff4747 100644 --- a/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj +++ b/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -76,16 +76,16 @@ - muxvlan + mux - muxvlan + mux - muxvlan + mux - muxvlan + mux @@ -194,6 +194,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true %(AdditionalIncludeDirectories);.. @@ -295,8 +296,21 @@ + + + + + + + + + + + + - + + diff --git a/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj.Filters b/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj.Filters index 8bd7f5bf4..64862290a 100644 --- a/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj.Filters +++ b/network/ndis/mux/driver/60/vlan/muxvlan.vcxproj.Filters @@ -37,4 +37,12 @@ Resource Files + + + Driver Files + + + Driver Files + + \ No newline at end of file diff --git a/network/ndis/mux/mux.sln b/network/ndis/mux/mux.sln index 551a21b7d..bf78d7a4c 100644 --- a/network/ndis/mux/mux.sln +++ b/network/ndis/mux/mux.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33213.308 MinimumVisualStudioVersion = 12.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Vlan", "Vlan", "{DFD0A31B-8B62-4BAA-998E-161F01D1A01B}" EndProject @@ -14,41 +14,47 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Notifyob", "Notifyob", "{2CAF23FF-28F8-4D52-B6C9-B76C8BCD5F67}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "muxvlan", "driver\60\vlan\muxvlan.vcxproj", "{015D7470-0FC8-4597-A67E-BD9C754F0681}" + ProjectSection(ProjectDependencies) = postProject + {92E3B437-C258-47FB-8856-D3FEA56A3BCC} = {92E3B437-C258-47FB-8856-D3FEA56A3BCC} + EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mux", "driver\60\novlan\mux.vcxproj", "{B2DE2C37-B3F2-491E-94AE-402A7B4D3308}" + ProjectSection(ProjectDependencies) = postProject + {92E3B437-C258-47FB-8856-D3FEA56A3BCC} = {92E3B437-C258-47FB-8856-D3FEA56A3BCC} + EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mux", "notifyob\mux.vcxproj", "{92E3B437-C258-47FB-8856-D3FEA56A3BCC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {015D7470-0FC8-4597-A67E-BD9C754F0681}.Debug|Win32.ActiveCfg = Debug|Win32 {015D7470-0FC8-4597-A67E-BD9C754F0681}.Debug|Win32.Build.0 = Debug|Win32 - {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|Win32.ActiveCfg = Release|Win32 - {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|Win32.Build.0 = Release|Win32 {015D7470-0FC8-4597-A67E-BD9C754F0681}.Debug|x64.ActiveCfg = Debug|x64 {015D7470-0FC8-4597-A67E-BD9C754F0681}.Debug|x64.Build.0 = Debug|x64 + {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|Win32.ActiveCfg = Release|Win32 + {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|Win32.Build.0 = Release|Win32 {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|x64.ActiveCfg = Release|x64 {015D7470-0FC8-4597-A67E-BD9C754F0681}.Release|x64.Build.0 = Release|x64 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Debug|Win32.ActiveCfg = Debug|Win32 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Debug|Win32.Build.0 = Debug|Win32 - {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|Win32.ActiveCfg = Release|Win32 - {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|Win32.Build.0 = Release|Win32 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Debug|x64.ActiveCfg = Debug|x64 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Debug|x64.Build.0 = Debug|x64 + {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|Win32.ActiveCfg = Release|Win32 + {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|Win32.Build.0 = Release|Win32 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|x64.ActiveCfg = Release|x64 {B2DE2C37-B3F2-491E-94AE-402A7B4D3308}.Release|x64.Build.0 = Release|x64 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Debug|Win32.ActiveCfg = Debug|Win32 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Debug|Win32.Build.0 = Debug|Win32 - {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|Win32.ActiveCfg = Release|Win32 - {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|Win32.Build.0 = Release|Win32 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Debug|x64.ActiveCfg = Debug|x64 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Debug|x64.Build.0 = Debug|x64 + {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|Win32.ActiveCfg = Release|Win32 + {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|Win32.Build.0 = Release|Win32 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|x64.ActiveCfg = Release|x64 {92E3B437-C258-47FB-8856-D3FEA56A3BCC}.Release|x64.Build.0 = Release|x64 EndGlobalSection @@ -56,11 +62,14 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {015D7470-0FC8-4597-A67E-BD9C754F0681} = {DFD0A31B-8B62-4BAA-998E-161F01D1A01B} - {B2DE2C37-B3F2-491E-94AE-402A7B4D3308} = {2D3D13DE-5985-4A6C-8562-3E954D634F1E} - {92E3B437-C258-47FB-8856-D3FEA56A3BCC} = {2CAF23FF-28F8-4D52-B6C9-B76C8BCD5F67} {DFD0A31B-8B62-4BAA-998E-161F01D1A01B} = {BB781269-F74A-43E0-AD7D-DBD32BBF2012} {BB781269-F74A-43E0-AD7D-DBD32BBF2012} = {26B59072-BF66-4E06-83CA-3F4F95378A23} {2D3D13DE-5985-4A6C-8562-3E954D634F1E} = {BB781269-F74A-43E0-AD7D-DBD32BBF2012} + {015D7470-0FC8-4597-A67E-BD9C754F0681} = {DFD0A31B-8B62-4BAA-998E-161F01D1A01B} + {B2DE2C37-B3F2-491E-94AE-402A7B4D3308} = {2D3D13DE-5985-4A6C-8562-3E954D634F1E} + {92E3B437-C258-47FB-8856-D3FEA56A3BCC} = {2CAF23FF-28F8-4D52-B6C9-B76C8BCD5F67} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D56D7C7C-8F28-4702-A8D4-D0FDB5A2756C} EndGlobalSection EndGlobal diff --git a/network/ndis/mux/notifyob/adapter.cpp b/network/ndis/mux/notifyob/adapter.cpp index ea964c7a6..a208aa576 100644 --- a/network/ndis/mux/notifyob/adapter.cpp +++ b/network/ndis/mux/notifyob/adapter.cpp @@ -146,9 +146,13 @@ HRESULT CMuxPhysicalAdapter::LoadConfiguration (VOID) // device IDs of the virtual miniports are stored. // - StringFromGUID2( m_guidAdapter, + int numChars = StringFromGUID2( m_guidAdapter, szAdapterGuid, MAX_PATH+1 ); + if (numChars == 0) { + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } StringCchPrintfW ( szAdapterGuidKey, celems(szAdapterGuidKey), @@ -225,9 +229,14 @@ HRESULT CMuxPhysicalAdapter::LoadConfiguration (VOID) if ( lpMiniportGuid != NULL ) { - CLSIDFromString( lpMiniportGuid, + HRESULT hrResult = CLSIDFromString( lpMiniportGuid, &guidMiniport ); - + + if (hrResult != S_OK) { + + lResult = ERROR_INVALID_PARAMETER; + } + // // Create an instance representing the virtual miniport. // @@ -532,10 +541,16 @@ HRESULT CMuxPhysicalAdapter::ApplyRegistryChanges (ConfigAction eApplyAction) // Open/create and then close the registry key to ensure that it does exist. // - StringFromGUID2( m_guidAdapter, + int numChars = StringFromGUID2( m_guidAdapter, szAdapterGuid, MAX_PATH+1 ); + if (numChars == 0) { + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + + lResult = RegCreateKeyExW( HKEY_LOCAL_MACHINE, c_szAdapterList, 0, @@ -786,9 +801,16 @@ HRESULT CMuxPhysicalAdapter::ApplyPnpChanges( // Notify the driver that one or more virtual miniports have been added. // - StringFromGUID2( guidMiniport, + int numChars = StringFromGUID2( guidMiniport, szMiniportGuid, MAX_PATH+1 ); + if (numChars == 0) { + + CoTaskMemFree(lpszBindName); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + lpDevice = AddDevicePrefix( szMiniportGuid ); if ( lpDevice ) { @@ -865,9 +887,16 @@ HRESULT CMuxPhysicalAdapter::ApplyPnpChanges( if ( eApplyAction != eActRemove ) { - StringFromGUID2( guidMiniport, + int numChars = StringFromGUID2( guidMiniport, szMiniportGuid, MAX_PATH+1 ); + if(numChars == 0) { + + CoTaskMemFree(lpszBindName); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + lpDevice = AddDevicePrefix( szMiniportGuid ); if ( lpDevice ) { diff --git a/network/ndis/mux/notifyob/common.cpp b/network/ndis/mux/notifyob/common.cpp index 24c7b4864..5ca2ca7f7 100644 --- a/network/ndis/mux/notifyob/common.cpp +++ b/network/ndis/mux/notifyob/common.cpp @@ -328,6 +328,7 @@ HRESULT HrFindInstance (INetCfg *pnc, ULONG ulCount; BOOL found; HRESULT hr; + int numChars; TraceMsg( L"-->HrFindInstance.\n" ); @@ -336,10 +337,17 @@ HRESULT HrFindInstance (INetCfg *pnc, if ( hr == S_OK ) { - StringFromGUID2( guidInstance, + numChars = StringFromGUID2( guidInstance, szGuid, MAX_PATH+1 ); + if (numChars == 0) { + + ReleaseObj(pencc); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + TraceMsg( L" Looking for component with InstanceGuid %s\n", szGuid ); @@ -353,10 +361,20 @@ HRESULT HrFindInstance (INetCfg *pnc, if ( hr == S_OK ) { - StringFromGUID2( guid, + numChars = StringFromGUID2( guid, szGuid, MAX_PATH+1 ); + if (numChars == 0) { + + ReleaseObj(pncc); + + ReleaseObj(pencc); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + + TraceMsg( L" Found component with InstanceGuid %s\n", szGuid ); diff --git a/network/ndis/mux/notifyob/dllmain.cpp b/network/ndis/mux/notifyob/dllmain.cpp index d9785cd64..636f2c8ad 100644 --- a/network/ndis/mux/notifyob/dllmain.cpp +++ b/network/ndis/mux/notifyob/dllmain.cpp @@ -68,6 +68,7 @@ BOOL WINAPI DllMain (HINSTANCE hInstance, ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE +__control_entrypoint(DllExport) STDAPI DllCanUnloadNow(void) { HRESULT hr; @@ -85,6 +86,7 @@ STDAPI DllCanUnloadNow(void) ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type +_Check_return_ STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv) { TraceMsg( L"-->DllGetClassObject.\n"); diff --git a/network/ndis/mux/notifyob/notify.cpp b/network/ndis/mux/notifyob/notify.cpp index be239fcdd..3d0a55ff9 100644 --- a/network/ndis/mux/notifyob/notify.cpp +++ b/network/ndis/mux/notifyob/notify.cpp @@ -1041,11 +1041,8 @@ STDMETHODIMP CMuxNotify::ApplyProperties (VOID) INetLanConnectionUiInfo *pLanConnUiInfo; CMuxPhysicalAdapter *pAdapter; GUID guidAdapter; - INetCfgComponent *pncc; HRESULT hr = S_OK; - UNREFERENCED_PARAMETER(pncc); - TraceMsg(L"-->CMuxNotify INetCfgPropertyUi::ApplyProperties\n"); if ( m_pUnkContext ) { @@ -1232,9 +1229,14 @@ HRESULT CMuxNotify::HrLoadAdapterConfiguration (VOID) // Subkeys are actually a guid/bindname of the adapters. // szAdapterGuid[MAX_PATH]='\0'; - CLSIDFromString( szAdapterGuid, + HRESULT hrResult = CLSIDFromString( szAdapterGuid, &guidAdapter ); + if (hrResult != S_OK) { + + lResult = ERROR_INVALID_PARAMETER; + } + // // Create an instance representing the adapter. // diff --git a/network/ndis/mux/notifyob/virtual.cpp b/network/ndis/mux/notifyob/virtual.cpp index 5b6cde80d..fd3cce0e0 100644 --- a/network/ndis/mux/notifyob/virtual.cpp +++ b/network/ndis/mux/notifyob/virtual.cpp @@ -330,17 +330,22 @@ HRESULT CMuxVirtualMiniport::ApplyRegistryChanges(ConfigAction eApplyAction) WCHAR szMiniportGuid[MAX_PATH+1]; LPWSTR lpDevice; LONG lResult = 0; - + int numChars; TraceMsg( L"-->CMuxVirtualMiniport::ApplyRegistryChanges.\n" ); switch( eApplyAction ) { case eActAdd: // Virtual miniport added. - StringFromGUID2( m_guidAdapter, + numChars = StringFromGUID2( m_guidAdapter, szAdapterGuid, MAX_PATH+1 ); + if (numChars == 0) { + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + StringCchPrintfW ( szAdapterGuidKey, celems(szAdapterGuidKey), L"%s\\%s", @@ -361,10 +366,17 @@ HRESULT CMuxVirtualMiniport::ApplyRegistryChanges(ConfigAction eApplyAction) if ( lResult == ERROR_SUCCESS ) { - StringFromGUID2( m_guidMiniport, + numChars = StringFromGUID2( m_guidMiniport, szMiniportGuid, MAX_PATH+1 ); + if (numChars == 0) { + + RegCloseKey(hkeyAdapterGuid); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + lpDevice = AddDevicePrefix( szMiniportGuid ); if ( lpDevice ) { @@ -411,10 +423,15 @@ HRESULT CMuxVirtualMiniport::ApplyRegistryChanges(ConfigAction eApplyAction) case eActRemove: // Virtual miniport removed. - StringFromGUID2( m_guidAdapter, + numChars = StringFromGUID2( m_guidAdapter, szAdapterGuid, MAX_PATH+1 ); + if (numChars == 0) { + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + StringCchPrintfW( szAdapterGuidKey, celems(szAdapterGuidKey), L"%s\\%s", @@ -434,10 +451,17 @@ HRESULT CMuxVirtualMiniport::ApplyRegistryChanges(ConfigAction eApplyAction) if ( lResult == ERROR_SUCCESS ) { - StringFromGUID2( m_guidMiniport, + numChars = StringFromGUID2( m_guidMiniport, szMiniportGuid, MAX_PATH+1 ); + if (numChars == 0) { + + RegCloseKey(hkeyAdapterGuid); + + return HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); + } + lpDevice = AddDevicePrefix( szMiniportGuid ); TraceMsg( L" Deleting %s at %s.\n", lpDevice, diff --git a/network/ndis/ndisprot/6x/ndisprot60.sln b/network/ndis/ndisprot/6x/ndisprot60.sln index 474b2ff01..4c2e55edd 100644 --- a/network/ndis/ndisprot/6x/ndisprot60.sln +++ b/network/ndis/ndisprot/6x/ndisprot60.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33213.308 MinimumVisualStudioVersion = 12.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "60", "60", "{09F8A71E-BD45-42F5-8CB5-82F137773350}" EndProject @@ -20,33 +20,33 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Debug|Win32.ActiveCfg = Debug|Win32 {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Debug|Win32.Build.0 = Debug|Win32 - {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|Win32.ActiveCfg = Release|Win32 - {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|Win32.Build.0 = Release|Win32 {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Debug|x64.ActiveCfg = Debug|x64 {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Debug|x64.Build.0 = Debug|x64 + {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|Win32.ActiveCfg = Release|Win32 + {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|Win32.Build.0 = Release|Win32 {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|x64.ActiveCfg = Release|x64 {F27914B8-F3D9-4164-BF33-42BBFA19AED4}.Release|x64.Build.0 = Release|x64 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Debug|Win32.ActiveCfg = Debug|Win32 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Debug|Win32.Build.0 = Debug|Win32 - {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|Win32.ActiveCfg = Release|Win32 - {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|Win32.Build.0 = Release|Win32 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Debug|x64.ActiveCfg = Debug|x64 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Debug|x64.Build.0 = Debug|x64 + {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|Win32.ActiveCfg = Release|Win32 + {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|Win32.Build.0 = Release|Win32 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|x64.ActiveCfg = Release|x64 {C0748EAB-F425-488A-9F39-77D5DE2DD251}.Release|x64.Build.0 = Release|x64 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Debug|Win32.ActiveCfg = Debug|Win32 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Debug|Win32.Build.0 = Debug|Win32 - {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|Win32.ActiveCfg = Release|Win32 - {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|Win32.Build.0 = Release|Win32 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Debug|x64.ActiveCfg = Debug|x64 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Debug|x64.Build.0 = Debug|x64 + {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|Win32.ActiveCfg = Release|Win32 + {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|Win32.Build.0 = Release|Win32 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|x64.ActiveCfg = Release|x64 {34A953AA-28CB-472E-B438-1BE26FDF1D54}.Release|x64.Build.0 = Release|x64 EndGlobalSection @@ -54,10 +54,13 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution + {09F8A71E-BD45-42F5-8CB5-82F137773350} = {40B41B7C-63E0-4BEC-9BF6-2AE9002E0670} + {7B0AA49C-0A8C-4EED-8ACE-1A80EC2E5AEB} = {20D7328F-9929-4D3A-BC1D-08E2442A929D} {F27914B8-F3D9-4164-BF33-42BBFA19AED4} = {09F8A71E-BD45-42F5-8CB5-82F137773350} {C0748EAB-F425-488A-9F39-77D5DE2DD251} = {7B0AA49C-0A8C-4EED-8ACE-1A80EC2E5AEB} {34A953AA-28CB-472E-B438-1BE26FDF1D54} = {20D7328F-9929-4D3A-BC1D-08E2442A929D} - {09F8A71E-BD45-42F5-8CB5-82F137773350} = {40B41B7C-63E0-4BEC-9BF6-2AE9002E0670} - {7B0AA49C-0A8C-4EED-8ACE-1A80EC2E5AEB} = {40B41B7C-63E0-4BEC-9BF6-2AE9002E0670} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2A8BDEF4-DEBC-4BDD-A1E5-F767E2EC8D5B} EndGlobalSection EndGlobal diff --git a/network/ndis/ndisprot/6x/sys/60/ndisprot60.inf b/network/ndis/ndisprot/6x/sys/60/ndisprot60.inf index 92f300019..bae3936c6 100644 Binary files a/network/ndis/ndisprot/6x/sys/60/ndisprot60.inf and b/network/ndis/ndisprot/6x/sys/60/ndisprot60.inf differ diff --git a/network/ndis/ndisprot/6x/sys/60/ndisprot60.vcxproj b/network/ndis/ndisprot/6x/sys/60/ndisprot60.vcxproj index da4c5c58f..738100d55 100644 --- a/network/ndis/ndisprot/6x/sys/60/ndisprot60.vcxproj +++ b/network/ndis/ndisprot/6x/sys/60/ndisprot60.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -142,6 +142,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib + true %(AdditionalIncludeDirectories);.. diff --git a/network/ndis/ndisprot/6x/sys/630/ndisprot630.inf b/network/ndis/ndisprot/6x/sys/630/ndisprot630.inf index f992ad089..c5d7adb6b 100644 Binary files a/network/ndis/ndisprot/6x/sys/630/ndisprot630.inf and b/network/ndis/ndisprot/6x/sys/630/ndisprot630.inf differ diff --git a/network/ndis/ndisprot/6x/sys/630/ndisprot630.vcxproj b/network/ndis/ndisprot/6x/sys/630/ndisprot630.vcxproj index 08e82745a..67f574905 100644 --- a/network/ndis/ndisprot/6x/sys/630/ndisprot630.vcxproj +++ b/network/ndis/ndisprot/6x/sys/630/ndisprot630.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -153,6 +153,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib + true sha256 diff --git a/network/ndis/ndisprot/6x/test/prottest.vcxproj b/network/ndis/ndisprot/6x/test/prottest.vcxproj index 9ef15c25a..bbe324c41 100644 --- a/network/ndis/ndisprot/6x/test/prottest.vcxproj +++ b/network/ndis/ndisprot/6x/test/prottest.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/network/ndis/ndisprot_kmdf/60/ndisprot.inx b/network/ndis/ndisprot_kmdf/60/ndisprot.inx index a25033cf6..ecd932c17 100644 Binary files a/network/ndis/ndisprot_kmdf/60/ndisprot.inx and b/network/ndis/ndisprot_kmdf/60/ndisprot.inx differ diff --git a/network/ndis/ndisprot_kmdf/60/nprt6wdf.vcxproj b/network/ndis/ndisprot_kmdf/60/nprt6wdf.vcxproj index a04d1a1d8..81a2d78ed 100644 --- a/network/ndis/ndisprot_kmdf/60/nprt6wdf.vcxproj +++ b/network/ndis/ndisprot_kmdf/60/nprt6wdf.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -143,6 +143,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib + true diff --git a/network/ndis/ndisprot_kmdf/notifyob/dllmain.cpp b/network/ndis/ndisprot_kmdf/notifyob/dllmain.cpp index b3e3a66c5..2452d95c4 100644 --- a/network/ndis/ndisprot_kmdf/notifyob/dllmain.cpp +++ b/network/ndis/ndisprot_kmdf/notifyob/dllmain.cpp @@ -92,7 +92,7 @@ DllMain( return TRUE; } - +__control_entrypoint(DllExport) STDAPI DllCanUnloadNow( ) { diff --git a/network/ndis/netvmini/6x/60/netvmini60.inf b/network/ndis/netvmini/6x/60/netvmini60.inf index ed2c0b30f..63382e9be 100644 Binary files a/network/ndis/netvmini/6x/60/netvmini60.inf and b/network/ndis/netvmini/6x/60/netvmini60.inf differ diff --git a/network/ndis/netvmini/6x/60/netvmini60.vcxproj b/network/ndis/netvmini/6x/60/netvmini60.vcxproj index 6562995b6..5e5a4ed9f 100644 --- a/network/ndis/netvmini/6x/60/netvmini60.vcxproj +++ b/network/ndis/netvmini/6x/60/netvmini60.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -121,6 +121,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true sha256 diff --git a/network/ndis/netvmini/6x/620/netvmini620.inf b/network/ndis/netvmini/6x/620/netvmini620.inf index fbe4f8c4d..4dc1c9b64 100644 Binary files a/network/ndis/netvmini/6x/620/netvmini620.inf and b/network/ndis/netvmini/6x/620/netvmini620.inf differ diff --git a/network/ndis/netvmini/6x/620/netvmini620.vcxproj b/network/ndis/netvmini/6x/620/netvmini620.vcxproj index 531cd3723..90d220724 100644 --- a/network/ndis/netvmini/6x/620/netvmini620.vcxproj +++ b/network/ndis/netvmini/6x/620/netvmini620.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -121,6 +121,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true sha256 diff --git a/network/ndis/netvmini/6x/630/netvmini630.inf b/network/ndis/netvmini/6x/630/netvmini630.inf index 89bd114e2..eb7d61c85 100644 Binary files a/network/ndis/netvmini/6x/630/netvmini630.inf and b/network/ndis/netvmini/6x/630/netvmini630.inf differ diff --git a/network/ndis/netvmini/6x/630/netvmini630.vcxproj b/network/ndis/netvmini/6x/630/netvmini630.vcxproj index 19a25bfbc..65b5dd78e 100644 --- a/network/ndis/netvmini/6x/630/netvmini630.vcxproj +++ b/network/ndis/netvmini/6x/630/netvmini630.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -121,6 +121,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true sha256 diff --git a/network/ndis/netvmini/6x/680/netvmini680.inf b/network/ndis/netvmini/6x/680/netvmini680.inf index ac471b090..4160c5203 100644 Binary files a/network/ndis/netvmini/6x/680/netvmini680.inf and b/network/ndis/netvmini/6x/680/netvmini680.inf differ diff --git a/network/ndis/netvmini/6x/680/netvmini680.vcxproj b/network/ndis/netvmini/6x/680/netvmini680.vcxproj index 3d16c5e3b..01b8736e9 100644 --- a/network/ndis/netvmini/6x/680/netvmini680.vcxproj +++ b/network/ndis/netvmini/6x/680/netvmini680.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -121,6 +121,7 @@ %(AdditionalDependencies);$(DDK_LIB_PATH)\ndis.lib + true sha256 diff --git a/network/radio/HidSwitchDriverSample/RadioSwitchHidUsbFx2.vcxproj b/network/radio/HidSwitchDriverSample/RadioSwitchHidUsbFx2.vcxproj index 3b9df8db4..84bbb1eaf 100644 --- a/network/radio/HidSwitchDriverSample/RadioSwitchHidUsbFx2.vcxproj +++ b/network/radio/HidSwitchDriverSample/RadioSwitchHidUsbFx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/radio/RadioManagerSample/cpp/SampleRM.vcxproj b/network/radio/RadioManagerSample/cpp/SampleRM.vcxproj index 0e5f41be7..e6c3e2129 100644 --- a/network/radio/RadioManagerSample/cpp/SampleRM.vcxproj +++ b/network/radio/RadioManagerSample/cpp/SampleRM.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/network/trans/WFPSampler/lib/HelperFunctions_ThreadsAndEvents.cpp b/network/trans/WFPSampler/lib/HelperFunctions_ThreadsAndEvents.cpp index 89c7a5206..50b93eeaf 100644 --- a/network/trans/WFPSampler/lib/HelperFunctions_ThreadsAndEvents.cpp +++ b/network/trans/WFPSampler/lib/HelperFunctions_ThreadsAndEvents.cpp @@ -378,7 +378,8 @@ UINT32 HlprThreadWaitForEvent(_In_ HANDLE eventHandle, { status = WAIT_TIMEOUT; - HlprLogInfo(L"HlprThreadWaitForEvent() [status: %#x]"); + HlprLogInfo(L"HlprThreadWaitForEvent() [status: %#x]", + status); break; } diff --git a/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj b/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj index 00e24f272..94eb7ad74 100644 --- a/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj +++ b/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Universal WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Universal WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Universal WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Universal WindowsApplicationForDrivers10.0 Application diff --git a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX index b101c7722..fdd4f950b 100644 Binary files a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX and b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX differ diff --git a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj index 8e69a8a0f..672d5a8f0 100644 --- a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj +++ b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/trans/ddproxy/sys/ddproxy.inf b/network/trans/ddproxy/sys/ddproxy.inf index 3792b0038..44c5d13e2 100644 Binary files a/network/trans/ddproxy/sys/ddproxy.inf and b/network/trans/ddproxy/sys/ddproxy.inf differ diff --git a/network/trans/ddproxy/sys/ddproxy.vcxproj b/network/trans/ddproxy/sys/ddproxy.vcxproj index ae9cfacea..db8139813 100644 --- a/network/trans/ddproxy/sys/ddproxy.vcxproj +++ b/network/trans/ddproxy/sys/ddproxy.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/trans/inspect/sys/inspect.inf b/network/trans/inspect/sys/inspect.inf index 9fb9674e9..644c4eeef 100644 Binary files a/network/trans/inspect/sys/inspect.inf and b/network/trans/inspect/sys/inspect.inf differ diff --git a/network/trans/inspect/sys/inspect.vcxproj b/network/trans/inspect/sys/inspect.vcxproj index 3b874a1ff..bd73f3d7d 100644 --- a/network/trans/inspect/sys/inspect.vcxproj +++ b/network/trans/inspect/sys/inspect.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/trans/msnmntr/sys/msnmntr.inf b/network/trans/msnmntr/sys/msnmntr.inf index 17ebcb7c6..79fa3be0e 100644 Binary files a/network/trans/msnmntr/sys/msnmntr.inf and b/network/trans/msnmntr/sys/msnmntr.inf differ diff --git a/network/trans/msnmntr/sys/msnmntr.vcxproj b/network/trans/msnmntr/sys/msnmntr.vcxproj index 19091c054..8c4da9abd 100644 --- a/network/trans/msnmntr/sys/msnmntr.vcxproj +++ b/network/trans/msnmntr/sys/msnmntr.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/trans/stmedit/stmedit.sln b/network/trans/stmedit/stmedit.sln index 8ae2d8390..e6b3f49a9 100644 --- a/network/trans/stmedit/stmedit.sln +++ b/network/trans/stmedit/stmedit.sln @@ -15,9 +15,9 @@ Global GlobalSection(ProjectConfigurationPlatforms) = postSolution {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|Win32.ActiveCfg = Debug|Win32 {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|Win32.Build.0 = Debug|Win32 - {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.ActiveCfg = Release|Win32 - {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.Build.0 = Release|Win32 - {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.Deploy.0 = Release|Win32 + {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.ActiveCfg = Release|x64 + {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.Build.0 = Release|x64 + {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Debug|x64.Deploy.0 = Release|x64 {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Release|Win32.ActiveCfg = Release|Win32 {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Release|Win32.Build.0 = Release|Win32 {9CE912A5-6210-4EF8-B22D-611D13254D4C}.Release|x64.ActiveCfg = Release|x64 diff --git a/network/trans/stmedit/sys/stmedit.inf b/network/trans/stmedit/sys/stmedit.inf index 39cd21098..04734b1ad 100644 Binary files a/network/trans/stmedit/sys/stmedit.inf and b/network/trans/stmedit/sys/stmedit.inf differ diff --git a/network/trans/stmedit/sys/stmedit.vcxproj b/network/trans/stmedit/sys/stmedit.vcxproj index cdfcc9e77..2b81aee6f 100644 --- a/network/trans/stmedit/sys/stmedit.vcxproj +++ b/network/trans/stmedit/sys/stmedit.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/network/wlan/WDI/COMMON/common.vcxproj b/network/wlan/WDI/COMMON/common.vcxproj index 3de209fa5..7f1772411 100644 --- a/network/wlan/WDI/COMMON/common.vcxproj +++ b/network/wlan/WDI/COMMON/common.vcxproj @@ -1,26 +1,10 @@  - - Win10 Debug - Arm - - - Win10 Debug - Win32 - Win10 Debug x64 - - Win10 Release - Arm - - - Win10 Release - Win32 - Win10 Release x64 @@ -38,7 +22,6 @@ 1.0 $(Configuration.Replace(' ','')) $(BUILD_ALT_DIR)\$(Platform)\ - $(BUILD_ALT_DIR)\ $(SolutionDir)COMMON\$(Configuration)\$(Platform)\ @@ -47,33 +30,10 @@ {956B060D-1055-4584-9CF4-9FE14C428545} - - Windows10 - True - Windows Driver - - - - - Windows10 - False - Windows Driver - - - - - True - Windows Driver - Win8 True - - Windows10 - False - Windows Driver - Windows10 True @@ -88,41 +48,6 @@ DbgengKernelDebugger DbgengRemoteDebugger - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - - - $(VC_ReferencesPath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - *.cdf;*.cache;*.obj;*.ilk;*.ipdb;*.iobj;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_Arm); - $(VC_LibraryPath_Arm);$(WindowsSDK_LibraryPath_Arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_Arm); - $(VC_LibraryPath_Arm);$(WindowsSDK_LibraryPath_Arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - $(VC_IncludePath);$(WindowsSDK_IncludePath); $(VC_ReferencesPath_x64); @@ -139,207 +64,6 @@ $(VC_SourcePath); $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x64); - - - _X86_;DBG;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - Disabled - Default - false - Cdecl - Default - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\; - Neither - false - false - false - true - - - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - true - false - false - false - false - false - false - false - false - Prompt - true - - - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - - - - true - Disabled - Default - false - Neither - false - false - false - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\; - _X86_;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - true - None - - - $(OutDir)$(TargetName)$(TargetExt) - - - true - - - false - - - sha256 - - - - - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\; - None - true - Disabled - Default - false - Neither - false - false - false - _ARM_;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - - - - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\; - - - - - None - - - - - true - Disabled - Default - false - Neither - false - false - false - _ARM_;DBG;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\; diff --git a/network/wlan/WDI/LIB/Arm/hal.lib b/network/wlan/WDI/LIB/Arm/hal.lib deleted file mode 100644 index 794359a73..000000000 Binary files a/network/wlan/WDI/LIB/Arm/hal.lib and /dev/null differ diff --git a/network/wlan/WDI/LIB/Arm/rtklibcom.lib b/network/wlan/WDI/LIB/Arm/rtklibcom.lib deleted file mode 100644 index 356e38605..000000000 Binary files a/network/wlan/WDI/LIB/Arm/rtklibcom.lib and /dev/null differ diff --git a/network/wlan/WDI/LIB/x86/hal.lib b/network/wlan/WDI/LIB/x86/hal.lib deleted file mode 100644 index 41be4e253..000000000 Binary files a/network/wlan/WDI/LIB/x86/hal.lib and /dev/null differ diff --git a/network/wlan/WDI/LIB/x86/rtklibcom.lib b/network/wlan/WDI/LIB/x86/rtklibcom.lib deleted file mode 100644 index b18054afb..000000000 Binary files a/network/wlan/WDI/LIB/x86/rtklibcom.lib and /dev/null differ diff --git a/network/wlan/WDI/PLATFORM/NDIS6/SDIO/sdio.vcxproj b/network/wlan/WDI/PLATFORM/NDIS6/SDIO/sdio.vcxproj index 057df0902..5770eb62e 100644 --- a/network/wlan/WDI/PLATFORM/NDIS6/SDIO/sdio.vcxproj +++ b/network/wlan/WDI/PLATFORM/NDIS6/SDIO/sdio.vcxproj @@ -1,110 +1,14 @@  - - Win10 Debug - Arm - - - WinBlue Debug - Arm - - - Win8 Debug - Arm - - - Win10 Release - Arm - - - WinBlue Release - Arm - - - Win8 Release - Arm - - - Win10 Debug - Win32 - - - WinBlue Debug - Win32 - - - Win8 Debug - Win32 - - - Win7 Debug - Win32 - - - Vista Debug - Win32 - - - Win10 Release - Win32 - - - WinBlue Release - Win32 - - - Win8 Release - Win32 - - - Win7 Release - Win32 - - - Vista Release - Win32 - Win10 Debug x64 - - WinBlue Debug - x64 - - - Win8 Debug - x64 - - - Win7 Debug - x64 - - - Vista Debug - x64 - Win10 Release x64 - - WinBlue Release - x64 - - - Win8 Release - x64 - - - Win7 Release - x64 - - - Vista Release - x64 - WindowsKernelModeDriver10.0 @@ -118,8 +22,6 @@ 1.0 $(Configuration.Replace(' ','')) $(BUILD_ALT_DIR)\$(Platform)\ - - $(SolutionDir)\DrvBin\$(Configuration)\$(Platform) @@ -128,185 +30,22 @@ {105EA485-B9B6-48AE-B8B0-96BBEA575973} - - - - True - Windows Driver - true - - - WindowsV6.3 - True - - - Win8 - True - - - - - False - Windows Driver - - - - - WindowsV6.3 - False - - - Win8 - False - - - Windows10 - True - Windows Driver - - - - - WindowsV6.3 - True - - - Win8 - True - - - Win7 - True - - - Vista - True - - - Windows10 - False - Windows Driver - true - - - WindowsV6.3 - False - - - Win8 - False - - - Win7 - False - - - Vista - False - Windows10 True Windows Driver true - - WindowsV6.3 - True - - - Win8 - True - - - Win7 - True - - - Vista - True - Windows10 False Windows Driver true - - WindowsV6.3 - False - - - Win8 - False - - - Win7 - False - - - Vista - False - DbgengKernelDebugger DbgengRemoteDebugger - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - .sys - $(VC_ReferencesPath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - true - http://timestamp.verisign.com/scripts/timstamp.dll - true - true - false - 10_x86;$(Inf2CatWindowsVersionList) - true - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencesPath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - true - http://timestamp.verisign.com/scripts/timstamp.dll - .sys - 10_X86;$(Inf2CatWindowsVersionList) - true - - - .sys - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencesPath_arm); - $(VC_LibraryPath_arm);$(WindowsSDK_LibraryPath_arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - false - 6_3_ARM;$(Inf2CatWindowsVersionList) - true - http://timestamp.verisign.com/scripts/timstamp.dll - - - .sys - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencesPath_arm); - $(VC_LibraryPath_arm);$(WindowsSDK_LibraryPath_arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - false - 6_3_Arm;$(Inf2CatWindowsVersionList) - true - http://timestamp.verisign.com/scripts/timstamp.dll - http://timestamp.verisign.com/scripts/timstamp.dll true @@ -333,232 +72,6 @@ true http://timestamp.verisign.com/scripts/timstamp.dll - - - $(SolutionDir)COMMON\$(Configuration)\common.lib;$(SolutionDir)PLATFORM\NdisComm\$(Configuration)\NdisComm.lib;$(SolutionDir)\LIB\x86\hal.lib;$(SolutionDir)\LIB\x86\rtklibcom.lib;$(WindowsSDK_LibraryPath_x86)km\x86\ndis.lib;$(WindowsSDK_LibraryPath_x86)km\x86\ntoskrnl.lib;$(WindowsSDK_LibraryPath_x86)km\x86\sdbus.lib;$(WindowsSDK_LibraryPath_x86)km\x86\wlan\1.0\TlvGeneratorParser.lib; - - $(AdditionalOptions) /IGNORE:4099 - $(OutDir)$(TargetName)$(TargetExt) - - - _X86_;DBG;NDIS60_MINIPORT;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - Cdecl - Default - $(WindowsSdkDir)Include\km\;$(WindowsSdkDir)Include\shared\;$(WindowsSdkDir)Include\wdf\kmdf\1.15\;$(WindowsSdkDir)Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)COMMON\;$(SolutionDir)PLATFORM\NDIS6; - Disabled - Default - false - Neither - false - false - false - true - - - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - true - true - false - false - false - false - false - false - false - false - Prompt - true - true - - - true - false - - - sha256 - - - - - $(WindowsSdkDir)Include\km\;$(WindowsSdkDir)Include\shared\;$(WindowsSdkDir)Include\wdf\kmdf\1.15\;$(WindowsSdkDir)Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)COMMON\;$(SolutionDir)PLATFORM\NDIS6; - true - true - Disabled - Default - false - Neither - false - false - false - _X86_;NDIS60_MINIPORT;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - None - - - - $(AdditionalOptions) /IGNORE:4099 - $(OutDir)$(TargetName)$(TargetExt) - $(SolutionDir)COMMON\$(Configuration)\common.lib;$(SolutionDir)PLATFORM\NdisComm\$(Configuration)\NdisComm.lib;$(SolutionDir)\LIB\x86\hal.lib;$(SolutionDir)\LIB\x86\rtklibcom.lib;$(WindowsSDK_LibraryPath_x86)km\x86\ndis.lib;$(WindowsSDK_LibraryPath_x86)km\x86\ntoskrnl.lib;$(WindowsSDK_LibraryPath_x86)km\x86\sdbus.lib;$(WindowsSDK_LibraryPath_x86)km\x86\wlan\1.0\TlvGeneratorParser.lib; - - - - - - - - - true - - - false - - - sha256 - - - - - $(WindowsSdkDir)Include\km\;$(WindowsSdkDir)Include\shared\;$(WindowsSdkDir)Include\wdf\kmdf\1.15\;$(WindowsSdkDir)Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)COMMON\;$(SolutionDir)PLATFORM\NDIS6; - None - true - true - Disabled - Default - false - Neither - false - false - false - _ARM_;NDIS60_MINIPORT;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - $(SolutionDir)COMMON\$(Configuration)\$(Platform)\common.lib;$(SolutionDir)PLATFORM\NdisComm\$(Configuration)\$(Platform)\NdisComm.lib;$(SolutionDir)\LIB\Arm\hal.lib;$(SolutionDir)\LIB\Arm\rtklibcom.lib;$(WindowsSDK_LibraryPath_arm)km\arm\ndis.lib;$(WindowsSDK_LibraryPath_arm)km\arm\ntoskrnl.lib;$(WindowsSDK_LibraryPath_arm)km\arm\sdbus.lib;$(WindowsSDK_LibraryPath_arm)km\arm\wlan\1.0\TlvGeneratorParser.lib; - - - true - - - false - - - sha256 - - - - - $(WindowsSdkDir)Include\km\;$(WindowsSdkDir)Include\shared\;$(WindowsSdkDir)Include\wdf\kmdf\1.15\;$(WindowsSdkDir)Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)PLATFORM\NDIS6\SDIO;$(SolutionDir)COMMON\;$(SolutionDir)PLATFORM\NDIS6; - None - true - true - Disabled - Default - false - Neither - false - false - false - _ARM_;DBG;NDIS60_MINIPORT;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - $(SolutionDir)COMMON\$(Configuration)\common.lib;$(SolutionDir)PLATFORM\NdisComm\$(Configuration)\NdisComm.lib;$(SolutionDir)\LIB\Arm\hal.lib;$(SolutionDir)\LIB\Arm\rtklibcom.lib;$(WindowsSDK_LibraryPath_arm)km\arm\ndis.lib;$(WindowsSDK_LibraryPath_arm)km\arm\ntoskrnl.lib;$(WindowsSDK_LibraryPath_arm)km\arm\sdbus.lib;$(WindowsSDK_LibraryPath_arm)km\arm\wlan\1.0\TlvGeneratorParser.lib; - - - true - - - false - - - sha256 - - - sha256 - - - sha256 - - - sha256 - - - sha256 - - true @@ -665,106 +178,6 @@ sha256 - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - @@ -779,20 +192,6 @@ - - - - - - - - - - - - - - @@ -801,26 +200,6 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/network/wlan/WDI/PLATFORM/NdisComm/NdisComm.vcxproj b/network/wlan/WDI/PLATFORM/NdisComm/NdisComm.vcxproj index ec170811f..eecb8f972 100644 --- a/network/wlan/WDI/PLATFORM/NdisComm/NdisComm.vcxproj +++ b/network/wlan/WDI/PLATFORM/NdisComm/NdisComm.vcxproj @@ -1,110 +1,14 @@  - - Win10 Debug - Arm - - - Win10 Debug - Win32 - Win10 Debug x64 - - Win10 Release - Arm - - - Win10 Release - Win32 - Win10 Release x64 - - WinBlue Debug - Arm - - - Win8 Debug - Arm - - - WinBlue Release - Arm - - - Win8 Release - Arm - - - WinBlue Debug - Win32 - - - Win8 Debug - Win32 - - - Win7 Debug - Win32 - - - Vista Debug - Win32 - - - WinBlue Release - Win32 - - - Win8 Release - Win32 - - - Win7 Release - Win32 - - - Vista Release - Win32 - - - WinBlue Debug - x64 - - - Win8 Debug - x64 - - - Win7 Debug - x64 - - - Vista Debug - x64 - - - WinBlue Release - x64 - - - Win8 Release - x64 - - - Win7 Release - x64 - - - Vista Release - x64 - WindowsKernelModeDriver10.0 @@ -119,7 +23,6 @@ 1.0 $(Configuration.Replace(' ','')) $(BUILD_ALT_DIR)\$(Platform)\ - $(BUILD_ALT_DIR)\ $(SolutionDir)PLATFORM\NdisComm\$(Configuration)\$(Platform)\ @@ -128,152 +31,20 @@ {C0A51792-1338-4294-ADAA-EDC4EE30CF05} - - WindowsV6.3 - True - - - Windows10 - True - Windows Driver - - - Win8 - True - - - WindowsV6.3 - False - - - Windows10 - False - Windows Driver - - - Win8 - False - - - WindowsV6.3 - True - - - Windows10 - True - Windows Driver - - - Win8 - True - - - Win7 - True - - - Vista - True - - - WindowsV6.3 - False - - - Windows10 - False - Windows Driver - - - Win8 - False - - - Win7 - False - - - Vista - False - - - WindowsV6.3 - True - Windows10 True Windows Driver - - Win8 - True - - - Win7 - True - - - Vista - True - - - WindowsV6.3 - False - Windows10 False Windows Driver - - Win8 - False - - - Win7 - False - - - Vista - False - DbgengKernelDebugger DbgengRemoteDebugger - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencesPath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_x86); - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_arm); - $(VC_LibraryPath_arm);$(WindowsSDK_LibraryPath_arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - - - $(VC_IncludePath);$(WindowsSDK_IncludePath); - $(VC_ReferencePath_arm); - $(VC_LibraryPath_arm);$(WindowsSDK_LibraryPath_arm);$(NETFXKitsDir)Lib\um\arm - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_arm); - $(VC_IncludePath);$(WindowsSDK_IncludePath); $(VC_ReferencesPath_x64); @@ -290,219 +61,6 @@ $(VC_SourcePath); $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x64); - - - _X86_;DBG;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - Cdecl - Default - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)COMMON\; - Disabled - Default - false - Neither - false - false - false - true - - - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - false - None - true - true - false - false - false - false - false - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - - - - $(OutDir)$(TargetName)$(TargetExt) - - - - - true - - - - - false - - - true - Disabled - Default - false - Neither - false - false - false - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)COMMON\; - None - true - _X86_;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - true - - - sha256 - - - - - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)COMMON\; - None - true - true - Disabled - Default - false - Neither - false - false - false - _ARM_;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - true - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - - - - true - $(WindowsSdkDir)\Include\km\;$(WindowsSdkDir)\Include\shared\;$(WindowsSdkDir)\Include\wdf\kmdf\1.15\;$(WindowsSdkDir)\Include\km\crt\;$(SolutionDir)HEADER;$(SolutionDir)PLATFORM\NDIS6\;$(SolutionDir)PLATFORM\NdisComm\;$(SolutionDir)PLATFORM\NDIS6\SDIO\;$(SolutionDir)HAL\;$(SolutionDir)HAL\phydm\;$(SolutionDir)HAL\rtl8723B\;$(SolutionDir)HAL\rtl8723B\rtl8723bs\;$(SolutionDir)HAL\phydm\rtl8723b\;$(SolutionDir)COMMON\; - None - true - true - Disabled - Default - false - Neither - false - false - false - _ARM_;DBG;USE_KLOCKS=1;BINARY_COMPATIBLE=0;NDIS650_MINIPORT=1;NDIS640_MINIPORT=1;NDIS630_MINIPORT=1;NDIS620_MINIPORT=1;NDIS61_MINIPORT=1;NDIS_MINIPORT_DRIVER;%(PreprocessorDefinitions) - false - false - false - false - false - true - false - EnableFastChecks - MultiThreadedDebugDLL - Default - false - true - true - true - NotUsing - Cdecl - Default - false - false - false - Prompt - - - $(OutDir)$(TargetName)$(TargetExt) - true - - - false - - - sha256 - - - sha256 - - - sha256 - - - sha256 - - - sha256 - - true @@ -603,106 +161,6 @@ sha256 - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - - - - sha256 - - diff --git a/network/wlan/WDI/PLATFORM/WinInf/SDIO/arm/netrtwlans.inf b/network/wlan/WDI/PLATFORM/WinInf/SDIO/arm/netrtwlans.inf deleted file mode 100644 index e18bf5105..000000000 --- a/network/wlan/WDI/PLATFORM/WinInf/SDIO/arm/netrtwlans.inf +++ /dev/null @@ -1,1259 +0,0 @@ -;; netrtwlans.inf -;; -;; Realtek Wireless 802.11b/g/n SDIO Network Adapter -;; -;; Copyright (C) 2012 Realtek Semiconductor Corp. -;; -;; This release is primarily for WHQL test. -;; - -;; FOR XP/Vista/Win7/Win8 - -[Version] -Signature = "$Windows NT$" -Class = Net -ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} -Provider = %Realtek% -CatalogFile.NT = netrtwlans.cat ;; for WHQL certified -DriverVer = 11/23/2015,3008.22.1030.2015 - -[Manufacturer] -%Realtek% = Realtek,NTArm.10.0 - -[ControlFlags] -ExcludeFromSelect = * - -[Realtek.NTArm.10.0] -;; For 8723 RTK common ================================================================ - -;; For 8723 RTK common ================================================================ -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_8753 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_B723 -;; Acer -%RTL8723bs.DeviceDesc% = ACER8723bs.ndi, SD\VID_024C&PID_0623 -;; HP -%RTL8723bs.DeviceDesc% = HP8723bs.ndi, SD\VID_024C&PID_0523 -;; ECS -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0524 -;; bestbuy -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0240 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0241 -;; For Braswell platform -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0626 -;; Reserved -%RTL8723bs.DeviceDesc% = RSVD8723bs.ndi, SD\VID_024C&PID_0624 - -;; For 8188E RTK common ================================================================ -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8188 -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8179 - -;; For 8812A RTK common ================================================================ - -;; For 8814A RTK common ================================================================ -%RTL8814as.DeviceDesc% = RTL8814as.ndi, SD\VID_024C&PID_8813 - -;; For 8821A RTK common ================================================================ -%RTL8821as.DeviceDesc% = RTL8821as.ndi, SD\VID_024C&PID_8821 - -;; For 8192ES RTK common ================================================================ -%RTL8192es.DeviceDesc% = RTL8192es.ndi, SD\VID_024C&PID_818B - - -;; For 8703 RTK common ================================================================ -%RTL8703bs.DeviceDesc% = RTL8703bs.ndi, SD\VID_024C&PID_B703 - -;; For 8188 RTK common ================================================================ -%RTL8188fs.DeviceDesc% = RTL8188fs.ndi, SD\VID_024C&PID_F179 - -;; For 8822B RTK common ================================================================ -%RTL8822bs.DeviceDesc% = RTL8822bs.ndi, SD\VID_024C&PID_B822 - -;; For 8723D RTK common ================================================================ -%RTL8723ds.DeviceDesc% = RTL8723ds.ndi, SD\VID_024C&PID_D723 - -;;---------------------------------------------------------------------------- -;; Realtek 8723as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723as.ndi.NT] -AddReg = NDIS_64.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8723bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;;---------------------------------------------------------------------------- -;; Acer 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[ACER8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, RSSI2GridMode_2.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;;---------------------------------------------------------------------------- -;; HP 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[HP8723bs.ndi.NT] -AddReg = NDIS_64.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; RSVD 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[RSVD8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanDisable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8188eu default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8188es.ndi.NT] -AddReg = NDIS_64.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8821as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8821as.ndi.NT] -AddReg = NDIS_64.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8814as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8814as.ndi.NT] -AddReg = NDIS_64.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8192es default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8192es.ndi.NT] -AddReg = NDIS_64.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8703bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8703bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8188fs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8188fs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - -;;---------------------------------------------------------------------------- -;; Realtek 8822bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8822bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8723ds default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723ds.ndi.NT] -AddReg = NDIS_64.reg, RTL8723ds.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - -;;---------------------------------------------------------------------------- -;; OS relative registry. -;;---------------------------------------------------------------------------- -[NDIS_64.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -HKR, Ndi, Service, 0, "RtlWlans" -;; -;; OS relative service. -;; -[RtlWlans.Service] -DisplayName = %RtlWlans.DeviceDesc.DispName% -ServiceType = 1 ; %SERVICE_KERNEL_DRIVER% -StartType = 3 ; %SERRVICE_DEMAND_START% -ErrorControl = 1 ; %SERRVICE_ERROR_NORMAL% -ServiceBinary = %12%\rtwlans.sys -LoadOrderGroup = NDIS - -;; -;; OS relative event log. -;; -[RtlWlans.EventLog] -AddReg = RtlWlans.AddEventLog.reg - -[RtlWlans.AddEventLog.reg] -HKR, , EventMessageFile, 0x00020000, "%%SystemRoot%%\System32\netevent.dll" -HKR, , TypesSupported , 0x00010001, 7 - -[CIHVS.reg] -HKR, Ndi\IHVExtensions, ExtensibilityDLL, 0, "%SystemRoot%\system32\Rtlihvs.dll" -HKR, Ndi\IHVExtensions, UIExtensibilityCLSID, 0, "{6C2A8CCA-B2A2-4d81-A3B2-4E15F445C312}" -HKR, Ndi\IHVExtensions, GroupName, 0, "Realtek CCX SDK IHV Service" -HKR, Ndi\IHVExtensions, AdapterOUI, 0x00010001, 0x00e04c - -;******************************************************************************* -; WAPI section -;******************************************************************************* -[wapi.reg] -HKR,defaults,WapiSupport,0,"1" -HKR,,WapiSupport,0,"1" - -;******************************************************************************* -; RTL8723as common paramters -;******************************************************************************* -[RTL8723as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - - -;******************************************************************************* -; RTL8723bs common paramters -;******************************************************************************* -[RTL8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -;;HKR,defaults,EnableAdaptivity,0,"0" -;;HKR,,EnableAdaptivity,0,"0" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of RTL8723bs.common.reg - -[HP8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -; Enable Adaptivity -;;HKR,defaults,EnableAdaptivity,0,"1" -;;HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; Enable Customeized PowerLimit Table -HKR,,EnableTxPowerLimit,0,"1" -HKR,,DecryptCustomFile,,"1" -HKR,,PwrLimitFile,0,"TXPWR_LMT_IEC0921_Enc.txt" - -; Regulation WorldWide -HKR,defaults,PwrTblSel,0,"4" -HKR,,PwrTblSel,0,"4" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of HP8723bs.common.reg - -;******************************************************************************* -; RTL8703bs common paramters -;******************************************************************************* -[RTL8703bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - - -;******************************************************************************* -; RTL8188Fs common paramters -;******************************************************************************* -[RTL8188fs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"0" -HKR,,RomDLFwEnable,0,"0" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - - -;******************************************************************************* -; RTL8821as common paramters -;******************************************************************************* -[RTL8821as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - - -;******************************************************************************* -; RTL8814as common paramters -;******************************************************************************* -[RTL8814as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -;; Add for 8814AS, based on 8821AS's modification -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - - -;******************************************************************************* -; RTL8192es common paramters -;******************************************************************************* -[RTL8192es.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -;******************************************************************************* -; RTL8822bs common paramters -;******************************************************************************* -[RTL8822bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" -HKR,,ValidRFPath,0,"51" -HKR,,PreInitMem,0,"1" - - -;******************************************************************************* -; RTL8723ds common paramters -;******************************************************************************* -[RTL8723ds.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,defaults,LdpcCap,0,"0" - - -;;---------------------------------------------------------------------------- -;; Realtek WLAN NIC parameters -;;---------------------------------------------------------------------------- -[RTLWLAN.reg] - -; Enable Adaptivity -HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,Channel,0,"1" -HKR,,Channel,0,"1" - -;; Antenna Diversity Type -HKR,defaults,AntennaDivType,0,"0" -HKR,,AntennaDivType,0,"0" - -HKR,defaults,NetworkType,0,"1" -HKR,,NetworkType,0,"1" - -HKR,defaults,StaUapsd,0,"0" -HKR,,StaUapsd,0,"0" - -; For B/G mode and B/G/N mode switch, we will use different wireless mode registry in later section -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - - -;; For WiFi test, 1: WiFi Config and 0: Performance Config -HKR,defaults,WiFiConfg,0,"0" -HKR,,WiFiConfg,0,"0" - -HKR,defaults,RxReorder,0,"1" -HKR,,RxReorder,0,"1" - -HKR,,DefaultKeyID,,"0" -HKR,,DefaultKey0,,"" -HKR,,DefaultKey1,,"" -HKR,,DefaultKey2,,"" -HKR,,DefaultKey3,,"" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - -;Leisure Power Save -HKR,defaults,bLeisurePs,0,"2" -HKR,,bLeisurePs,0,"2" - -;Fw Control LPS -HKR,defaults,bFwCtrlLPS,0,"1" -HKR,,bFwCtrlLPS,0,"1" - -;; LPS Interval -;HKR,defaults,LPSIntvl,0,"3" -HKR,,LPSIntvl,0,"3" - -HKR,,WEPinNmode,0,"0" - -HKR,defaults,RxSC,0,"0" -HKR,,RxSC,0,"0" - -HKR,defaults,TxSC,0,"0" -HKR,,TxSC,0,"0" - -HKR,defaults,NblRacingWA,0,"1" -HKR,,NblRacingWA,0,"1" - -HKR,defaults,SuspendTimerInLowPwr,0,"1" -HKR,,SuspendTimerInLowPwr,0,"1" - -;; Rx reorder pending time -HKR,,RxReorder_PendTime,0,"100" - -;Antenna Diversity -HKR,Ndi\params\AntDiv, ParamDesc, 0, "Antenna Diversity" -HKR,Ndi\params\AntDiv, default, 0, "0" -HKR,Ndi\params\AntDiv, type, 0, "enum" -HKR,Ndi\params\AntDiv\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\AntDiv\enum, "1", 0, %ENABLED_STR% - -HKLM, SYSTEM\CurrentControlSet\Services\RtlWlans\Parameters, "BtAntennaInHw", 0x00010001,2 - -[Ndis5Set.reg] -HKR,Ndi\params\PSPXlinkMode, ParamDesc, 0, %PSP_XLINK_STR% -HKR,Ndi\params\PSPXlinkMode, type, 0, "enum" -HKR,Ndi\params\PSPXlinkMode, default, 0, "0" -HKR,Ndi\params\PSPXlinkMode\enum, "0", 0, %DISABLE_STR% -HKR,Ndi\params\PSPXlinkMode\enum, "1", 0, %ENABLE_STR% -HKR,defaults,PSPXlinkMode,0,"0" -HKR,,PSPXlinkMode,0,"0" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - - -[Ndis6Set.reg] -;Inactive Power Save -HKR,defaults,InactivePs,0,"2" -HKR,,InactivePs,0,"2" - - -;;---------------------------------------------------------------------------- -;; Wireless mode option parameters -;;---------------------------------------------------------------------------- -[11nWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -;; 40MHz Support in 11n -HKR,Ndi\params\BWSetting, ParamDesc, 0, "Bandwidth" -HKR,Ndi\params\BWSetting, type, 0, "enum" -HKR,Ndi\params\BWSetting, default, 0, "1" -HKR,Ndi\params\BWSetting\enum, "0", 0, "20MHz Only" -HKR,Ndi\params\BWSetting\enum, "1", 0, "20_40MHz" -HKR,defaults,BWSetting,0,"1" -HKR,,BWSetting,0,"1" -HKR,,BWSetting,,"1" - -HKR,,Channel,0,"10" - -[11gWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,defaults,WirelessMode, 0, "4" -HKR,,WirelessMode, 0, "4" - -HKR,,BWSetting,0,"0" - -HKR,,Channel,0,"10" - -[11acWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "8", 0, %AUTO_STR% -HKR,Ndi\params\WirelessMode\enum, "1", 0, %IEEE_802_11A_STR% -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "16", 0, %IEEE_802_11BGN_STR% -HKR,Ndi\params\WirelessMode\enum, "32", 0, %IEEE_802_11AN_STR% -HKR,Ndi\params\WirelessMode\enum, "64", 0, %IEEE_802_11ANAC_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -HKR,,Channel,0,"36" - -;; RF Type -HKR,,RFType,0,"15" - - -HKR,defaults,BWSetting,0,"2" -HKR,,BWSetting,0,"2" - -;;---------------------------------------------------------------------------- -;; LPS 32k Control Parameters -;;---------------------------------------------------------------------------- -[32kEnable.reg] -HKR,,bLowPowerEnable,0,"1" -[32kDisable.reg] -HKR,,bLowPowerEnable,0,"0" - -;------------------------------------------------------------------------------- -; PnP pre-transition handling -;------------------------------------------------------------------------------- -[PnpPreTransOn.reg] -HKR,,PreTransPnP,0,"1" -[PnpPreTransOff.reg] -HKR,,PreTransPnP,0,"0" - -;;---------------------------------------------------------------------------- -;; WOWLAN Control Parameters -;;---------------------------------------------------------------------------- -[WowlanAllEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanDisable.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"0" -HKR,,GTKOffloadEnable,0,"0" - -[WowlanAllEnableNoLPS.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanEnableNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[WowlanEnableNoLPSNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[ConnectedStandbyEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" -HKR,,D2ListenIntvl,0,"4" -HKR,,NSOffloadEnable,0,"1" -HKR,,NLOEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "0" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"0" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -;; Packet coalescing should be enabled in WHCK test -HKR,defaults,*PacketCoalescing,0,"0" -HKR,,*PacketCoalescing,0,"0" - -;------------------------------------------------------------------------------- -; Auto Channel Selection -;------------------------------------------------------------------------------- -[AutoChnlSelon.reg] -HKR,,AutoChnlSel,0,"1" -[AutoChnlSeloff.reg] -HKR,,AutoChnlSel,0,"0" - -;;---------------------------------------------------------------------------- -;; RSSI to Grid Mode Parameters -;;---------------------------------------------------------------------------- -[RSSI2GridRealMode.reg] -HKR,,RSSI2GridMode,0,"1" -[RSSI2GridMode_2.reg] -HKR,,RSSI2GridMode,0,"2" -[RSSI2GridMode_4.reg] -HKR,,RSSI2GridMode,0,"4" - -;;---------------------------------------------------------------------------- -;; KFREE parameters -;;---------------------------------------------------------------------------- -[KFREE_COMMON.reg] -HKR,,RfKFreeEnable,0,"0" - -;******************************************************************************* -; Customer reg section -;******************************************************************************* -[ScanType.reg] -HKR,defaults,PassiveScan, 0, "0" -HKR,,PassiveScan, 0, "0" - -;******************************************************************************* -; Multi-Channel Concurrent section -;******************************************************************************* -[MCC.reg] -HKR,Ndi\params\MultiChannelFcsMode, ParamDesc, 0, %MCC_STR% -HKR,Ndi\params\MultiChannelFcsMode, type, 0, "enum" -HKR,Ndi\params\MultiChannelFcsMode, default, 0, "0" -HKR,Ndi\params\MultiChannelFcsMode\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\MultiChannelFcsMode\enum, "4", 0, %ENABLED_STR% -HKR,defaults,MultiChannelFcsMode, 0, "0" -HKR,,MultiChannelFcsMode, 0, "0" - -;******************************************************************************* -; Destination Directory -;******************************************************************************* -[RTWlanS.CopyFiles] -rtwlans.sys,,,2 - -[DestinationDirs] -DefaultDestDir = 11 -RTWlanS.CopyFiles = 12 -CIHVS.CopyFiles = 11 -RtlUI2.CopyFiles = 10 - -;;**************************************************************************** -;; Source Files -;;**************************************************************************** -[CIHVS.CopyFiles] -Rtlihvs.dll,,,2 - -[RegisterUIExt] -11,,RtlExtUI.dll,1 - -[RtlUI2.CopyFiles] -RtlUI2.exe,,,2 - -[SourceDisksFiles] -rtwlans.sys = 1 -Rtlihvs.dll = 1 - -[SourceDisksNames] -1=%DISKNAME%,,, - - -;******************************************************************************* -; Strings -;******************************************************************************* -[Strings] -SSID_STR = "SSID" -CHANNEL_STR = "Channel" -NETWORK_TYPE_STR = "Network Type" -LED_CONTROL_STR = "LED Control" -POWER_SAVE_STR = "Power Save Mode" -WIFI_IBSS_STR = "IBSS Default 11b Mode" -RATE_ADAPTIVE_STR = "Rate Adaptive" -QOS_STR = "QoS" -WiFiConfg_STR = "WiFiConfg" -WMM_APSD = "WMM APSD" -CCX_RM_STR = "CCX Radio Measurement" -CCX_OFF_LINE_DUR_UP_LIMIT_STR = "CCX Max Off-Line Measurement (0: unlimited)" -FORCE_PRIORITY_STR = "Forced Priority" -HW_PARA_STR = "Init from HwParaFile" -THREE_WIRE_MODE_STR = "Three Wire Programming Mode" -BOARD_TYPE_STR = "Board Type" -PROTECTION_MODE_STR = "Protection Mode" -TPC_STR = "Transmit Power Control" -TPC_POLARITY_STR = "TPC Polarity Select" -HIGH_POWER_STR = "High Power Mechanism" -INIT_GAIN_STR = "Initial Gain State" -CW_MAX_MIN_STR = "Contention Window" -PSP_XLINK_STR = "PSP XLink Mode" -DISABLE_STR = "Disable" -ENABLE_STR = "Enable" -DISABLED_STR = "Disabled" -ENABLED_STR = "Enabled" -AUTO_STR = "Auto" -AD_HOC_STR = "Ad Hoc" -INFRASTRUCTURE_STR = "Infrastructure" -AUTO_SELECT = "Auto select" -WL_MODE_STR = "Wireless Mode" -RX_REORDER_STR = "Rx Reorder" -CAM_STR = "CAM" -MAX_PSP_STR = "MAX_PSP" -Fast_PSP_STR = "Fast_PSP" -NO_AC_STR = "No AC (Disable)" -ALL_AC_STR = "ALL AC" -IEEE_802_11A_STR = "IEEE 802.11a" -IEEE_802_11B_STR = "IEEE 802.11b" -IEEE_802_11BG_STR = "IEEE 802.11b/g" -IEEE_802_11BGN_STR = "IEEE 802.11b/g/n" -IEEE_802_11AN_STR = "IEEE 802.11a/n" -IEEE_802_11ANAC_STR = "IEEE 802.11a/n/ac" -IEEE_802_11AC_STR = "IEEE 802.11 ac" -WakeOnMagicPacket = "Wake on Magic Packet" -WakeOnPattern = "Wake on Pattern Match" -MCC_STR = "Multi-Channel Concurrent" - -;******************************************************************************* -; manufacture description -;******************************************************************************* -Realtek = "Realtek Semiconductor Corp." - - -;******************************************************************************* -; Source disk name -;******************************************************************************* -DISKNAME = "Realtek Wireless LAN 802.11n SDIO Network Adapter Driver Disk" -RtlWlans.DeviceDesc = "Realtek Wireless LAN 802.11n SDIO Network Adapter" -RtlWlans.DeviceDesc.DispName = "Realtek Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8723as Device description -;******************************************************************************* -RTL8723as.DeviceDesc = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723as.DeviceDesc.DispName = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" - - - -;******************************************************************************* -; RTL8723bs Device description -;******************************************************************************* -RTL8723bs.DeviceDesc = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723bs.DeviceDesc.DispName = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8814as Device description -;******************************************************************************* -RTL8814as.DeviceDesc = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" -RTL8814as.DeviceDesc.DispName = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" - -;******************************************************************************* -; RTL8188ES Device description -;******************************************************************************* -RTL8188es.DeviceDesc = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8188es.DeviceDesc.DispName = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -;******************************************************************************* -; RTL8821as Device description -;******************************************************************************* -RTL8821as.DeviceDesc = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8821as.DeviceDesc.DispName = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -;******************************************************************************* -; RTL8192E Device description -;******************************************************************************* -RTL8192es.DeviceDesc = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8192es.DeviceDesc.DispName = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" - -;******************************************************************************* -; RTL8703bs Device description -;******************************************************************************* -RTL8703bs.DeviceDesc = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8703bs.DeviceDesc.DispName = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8188Fs Device description -;******************************************************************************* -RTL8188fs.DeviceDesc = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -RTL8188fs.DeviceDesc.DispName = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -;******************************************************************************* -; RTL8822bs Device description -;******************************************************************************* -RTL8822bs.DeviceDesc = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8822bs.DeviceDesc.DispName = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" - -;******************************************************************************* -; RTL8723ds Device description -;******************************************************************************* -RTL8723ds.DeviceDesc = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723ds.DeviceDesc.DispName = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" diff --git a/network/wlan/WDI/PLATFORM/WinInf/SDIO/netrtwlans.inf b/network/wlan/WDI/PLATFORM/WinInf/SDIO/netrtwlans.inf deleted file mode 100644 index 59166e9e3..000000000 --- a/network/wlan/WDI/PLATFORM/WinInf/SDIO/netrtwlans.inf +++ /dev/null @@ -1,2711 +0,0 @@ -;; netrtwlans.inf -;; -;; Realtek Wireless 802.11b/g/n SDIO Network Adapter -;; -;; Copyright (C) 2012 Realtek Semiconductor Corp. -;; -;; This release is primarily for WHQL test. -;; - -;; FOR XP/Vista/Win7/Win8 - -[Version] -Signature = "$Windows NT$" -Class = Net -ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} -Provider = %Realtek% -CatalogFile.NT = netrtwlans.cat ;; for WHQL certified -DriverVer = 10/30/2015,3008.22.1030.2015 - -[Manufacturer] -%Realtek% = Realtek, NTx86, NTamd64, NTx86.6.0, NTamd64.6.0, NTx86.6.1, NTamd64.6.1, NTx86.6.2, NTamd64.6.2, NTx86.6.3, NTamd64.6.3, NTx86.10.0, NTamd64.10.0, NTArm.10.0 - -[ControlFlags] -ExcludeFromSelect = * - -;; ## Manufacturer [Realtek] -;; $$ ICtype 8723A Start -;; For 8723 RTK common ================================================================ -;; $$ ICtype 8723A End - -;; $$ ICtype 8723B Start -;; For 8723 RTK common ================================================================ -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_8753 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_B723 -;; Acer -%RTL8723bs.DeviceDesc% = ACER8723bs.ndi, SD\VID_024C&PID_0623 -;; HP -%RTL8723bs.DeviceDesc% = HP8723bs.ndi, SD\VID_024C&PID_0523 -;; ECS -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0524 -;; bestbuy -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0240 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0241 -;; For Braswell platform -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0626 -;; Reserved -%RTL8723bs.DeviceDesc% = RSVD8723bs.ndi, SD\VID_024C&PID_0624 -;; $$ ICtype 8723B End - -;; $$ ICtype 8188E Start -;; For 8188E RTK common ================================================================ -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8188 -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8179 -;; $$ ICtype 8188E End - -;; $$ ICtype 8812A Start -;; For 8812A RTK common ================================================================ -;; $$ ICtype 8812A End - -;; $$ ICtype 8814A Start -;; For 8814A RTK common ================================================================ -%RTL8814as.DeviceDesc% = RTL8814as.ndi, SD\VID_024C&PID_8813 -;; $$ ICtype 8814A End - -;; $$ ICtype 8821A Start -;; For 8821A RTK common ================================================================ -%RTL8821as.DeviceDesc% = RTL8821as.ndi, SD\VID_024C&PID_8821 -;; $$ ICtype 8821A End - -;; $$ ICtype 8192E Start -;; For 8192ES RTK common ================================================================ -%RTL8192es.DeviceDesc% = RTL8192es.ndi, SD\VID_024C&PID_818B -;; $$ ICtype 8192E End - - -;; $$ ICtype 8703B Start -;; For 8703 RTK common ================================================================ -%RTL8703bs.DeviceDesc% = RTL8703bs.ndi, SD\VID_024C&PID_B703 -;; $$ ICtype 8703B End - -;; $$ ICtype 8188F Start -;; For 8188 RTK common ================================================================ -%RTL8188fs.DeviceDesc% = RTL8188fs.ndi, SD\VID_024C&PID_F179 -;; $$ ICtype 8188F End - -;; $$ ICtype 8822B Start -;; For 8822B RTK common ================================================================ -%RTL8822bs.DeviceDesc% = RTL8822bs.ndi, SD\VID_024C&PID_B822 -;; $$ ICtype 8822B End - -;; $$ ICtype 8723D Start -;; For 8723D RTK common ================================================================ -%RTL8723ds.DeviceDesc% = RTL8723ds.ndi, SD\VID_024C&PID_D723 -;; $$ ICtype 8723D End - -;; $$ ICtype 8723A Start -;;---------------------------------------------------------------------------- -;; Realtek 8723as default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8723as_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8723as_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8723as_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8723as_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8723as_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8723as_os63.ndi.NT] -AddReg = NDIS_63.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as_os63.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8723as_os64.ndi.NT] -AddReg = NDIS_64.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as_os64.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8723A End - -;; $$ ICtype 8723B Start -;;---------------------------------------------------------------------------- -;; Realtek 8723bs default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_51.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_60.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -;; $$ FeatureType WAPI Start -AddReg = wapi.reg -RegisterDlls = RegisterUIExt -CopyFiles = CIHVS.CopyFiles -;; $$ FeatureType WAPI End -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_61.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -;; $$ FeatureType WAPI Start -AddReg = wapi.reg -RegisterDlls = RegisterUIExt -CopyFiles = CIHVS.CopyFiles -;; $$ FeatureType WAPI End -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_62.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, MCC.reg -;; $$ FeatureType WAPI Start -AddReg = wapi.reg -RegisterDlls = RegisterUIExt -CopyFiles = CIHVS.CopyFiles -;; $$ FeatureType WAPI End -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_63.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, MCC.reg -;; $$ FeatureType WAPI Start -AddReg = wapi.reg -RegisterDlls = RegisterUIExt -CopyFiles = CIHVS.CopyFiles -;; $$ FeatureType WAPI End -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, MCC.reg -;; $$ FeatureType WAPI Start -AddReg = wapi.reg -RegisterDlls = RegisterUIExt -CopyFiles = CIHVS.CopyFiles -;; $$ FeatureType WAPI End -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End -;;---------------------------------------------------------------------------- -;; Acer 8723bs installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_51.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_60.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_61.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg, RSSI2GridMode_2.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_62.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, RSSI2GridMode_2.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_63.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, RSSI2GridMode_2.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[ACER8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, RSSI2GridMode_2.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End -;;---------------------------------------------------------------------------- -;; HP 8723bs installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_51.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_60.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_61.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_62.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_63.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[HP8723bs.ndi.NT] -AddReg = NDIS_64.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8723B End - -;;---------------------------------------------------------------------------- -;; RSVD 8723bs installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_51.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_60.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_61.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_62.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanDisable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_63.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanDisable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RSVD8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanDisable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8723B End - -;; $$ ICtype 8188E Start -;;---------------------------------------------------------------------------- -;; Realtek 8188eu default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8188es_os51.ndi.NT] -AddReg = NDIS_51.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8188es_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8188es_os60.ndi.NT] -AddReg = NDIS_60.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg, ConnectedStandbyEnable.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8188es_os61.ndi.NT] -AddReg = NDIS_61.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg, ConnectedStandbyEnable.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8188es_os62.ndi.NT] -AddReg = NDIS_62.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg, ConnectedStandbyEnable.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8188es_os63.ndi.NT] -AddReg = NDIS_63.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es_os63.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8188es_os64.ndi.NT] -AddReg = NDIS_64.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es_os64.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8188E End - -;; $$ ICtype 8821A Start -;;---------------------------------------------------------------------------- -;; Realtek 8821as default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8821as_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8821as_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8821as_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8821as_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8821as_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8821as_os63.ndi.NT] -AddReg = NDIS_63.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as_os63.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8821as_os64.ndi.NT] -AddReg = NDIS_64.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as_os64.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8821A End - -;; $$ ICtype 8814A Start -;;---------------------------------------------------------------------------- -;; Realtek 8814as default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8814as_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8814as_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8814as_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8814as_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8814as_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8814as_os63.ndi.NT] -AddReg = NDIS_63.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as_os63.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8814as_os64.ndi.NT] -AddReg = NDIS_64.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as_os64.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8814A End - -;; $$ ICtype 8192E Start -;;---------------------------------------------------------------------------- -;; Realtek 8192es default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8192es_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8192es_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8192es_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8192es_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8192es_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8192es_os63.ndi.NT] -AddReg = NDIS_63.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es_os63.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8192es_os64.ndi.NT] -AddReg = NDIS_64.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es_os64.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8192E End - -;; $$ ICtype 8703B Start -;;---------------------------------------------------------------------------- -;; Realtek 8703bs default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_51.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg, WowlanAllEnable.reg, KFREE_COMMON.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_60.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanAllEnable.reg, KFREE_COMMON.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_61.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanAllEnable.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_62.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_63.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8703bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8703B End - -;; $$ ICtype 8188F Start -;;---------------------------------------------------------------------------- -;; Realtek 8188fs default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_51.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis5Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_60.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_61.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_62.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_63.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8188fs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8188F End -;; $$ ICtype 8822B Start -;;---------------------------------------------------------------------------- -;; Realtek 8822bs default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8822bs_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8822bs_os51.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8822bs_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs_os60.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8822bs_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs_os61.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8822bs_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs_os62.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8822bs_os63.ndi.NT] -AddReg = NDIS_63.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs_os63.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs_os63.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8822bs_os64.ndi.NT] -AddReg = NDIS_64.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs_os64.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs_os64.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8822B End - -;; $$ ICtype 8723D Start -;;---------------------------------------------------------------------------- -;; Realtek 8723ds default installation -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[RTL8723ds_os51.ndi.NT] -AddReg = NDIS_51.reg, RTL8723ds.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis5Set.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles - -[RTL8723ds_os51.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os51 End - -;; ** Section for os60 Start -[RTL8723ds_os60.ndi.NT] -AddReg = NDIS_60.reg, RTL8723ds.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds_os60.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -;; ** Section for os60 End - -;; ** Section for os61 Start -[RTL8723ds_os61.ndi.NT] -AddReg = NDIS_61.reg, RTL8723ds.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds_os61.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds_os61.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os61 End - -;; ** Section for os62 Start -[RTL8723ds_os62.ndi.NT] -AddReg = NDIS_62.reg, RTL8723ds.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds_os62.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds_os62.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os62 End - -;; ** Section for os63 Start -[RTL8723ds.ndi.NT] -AddReg = NDIS_63.reg, RTL8723ds.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os63 End - -;; ** Section for os64 Start -[RTL8723ds.ndi.NT] -AddReg = NDIS_64.reg, RTL8723ds.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds.ndi.NT.Services] -;; $$ AddServiceName Start -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -;; $$ AddServiceName End -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;; ** Section for os64 End - -;; $$ ICtype 8723D End -;;---------------------------------------------------------------------------- -;; OS relative registry. -;;---------------------------------------------------------------------------- -;; ** Section for os51 Start -[NDIS_51.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5" -HKR, Ndi\Interfaces, LowerRange, 0, "ethernet" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os51 End -;; ** Section for os60 Start -[NDIS_60.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os60 End -;; ** Section for os61 Start -[NDIS_61.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os61 End -;; ** Section for os62 Start -[NDIS_62.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os62 End -;; ** Section for os63 Start -[NDIS_63.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os63 End -;; ** Section for os64 Start -[NDIS_64.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -;; $$ ServiceName Start -HKR, Ndi, Service, 0, "RtlWlans" -;; $$ ServiceName End -;; ** Section for os64 End -;; -;; OS relative service. -;; -[RtlWlans.Service] -DisplayName = %RtlWlans.DeviceDesc.DispName% -ServiceType = 1 ; %SERVICE_KERNEL_DRIVER% -StartType = 3 ; %SERRVICE_DEMAND_START% -ErrorControl = 1 ; %SERRVICE_ERROR_NORMAL% -;; $$ DriverName Start -ServiceBinary = %12%\rtwlans.sys -;; $$ DriverName End -LoadOrderGroup = NDIS - -;; -;; OS relative event log. -;; -[RtlWlans.EventLog] -AddReg = RtlWlans.AddEventLog.reg - -[RtlWlans.AddEventLog.reg] -HKR, , EventMessageFile, 0x00020000, "%%SystemRoot%%\System32\netevent.dll" -HKR, , TypesSupported , 0x00010001, 7 - -[CIHVS.reg] -HKR, Ndi\IHVExtensions, ExtensibilityDLL, 0, "%SystemRoot%\system32\Rtlihvs.dll" -HKR, Ndi\IHVExtensions, UIExtensibilityCLSID, 0, "{6C2A8CCA-B2A2-4d81-A3B2-4E15F445C312}" -HKR, Ndi\IHVExtensions, GroupName, 0, "Realtek CCX SDK IHV Service" -HKR, Ndi\IHVExtensions, AdapterOUI, 0x00010001, 0x00e04c - -;******************************************************************************* -; WAPI section -;******************************************************************************* -[wapi.reg] -HKR,defaults,WapiSupport,0,"1" -HKR,,WapiSupport,0,"1" - -;; $$ ICtype 8723A Start -;******************************************************************************* -; RTL8723as common paramters -;******************************************************************************* -[RTL8723as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -;; $$ ICtype 8723A End - -;; $$ ICtype 8723B Start -;******************************************************************************* -; RTL8723bs common paramters -;******************************************************************************* -[RTL8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -;;HKR,defaults,EnableAdaptivity,0,"0" -;;HKR,,EnableAdaptivity,0,"0" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of RTL8723bs.common.reg - -[HP8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -; Enable Adaptivity -;;HKR,defaults,EnableAdaptivity,0,"1" -;;HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; Enable Customeized PowerLimit Table -HKR,,EnableTxPowerLimit,0,"1" -HKR,,DecryptCustomFile,,"1" -HKR,,PwrLimitFile,0,"TXPWR_LMT_IEC0921_Enc.txt" - -; Regulation WorldWide -HKR,defaults,PwrTblSel,0,"4" -HKR,,PwrTblSel,0,"4" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of HP8723bs.common.reg -;; $$ ICtype 8723B End - -;; $$ ICtype 8703B Start -;******************************************************************************* -; RTL8703bs common paramters -;******************************************************************************* -[RTL8703bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -;; $$ ICtype 8703B End - -;; $$ ICtype 8188F Start -;******************************************************************************* -; RTL8188Fs common paramters -;******************************************************************************* -[RTL8188fs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"0" -HKR,,RomDLFwEnable,0,"0" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -;; $$ ICtype 8703B End - -;; $$ ICtype 8821A Start -;******************************************************************************* -; RTL8821as common paramters -;******************************************************************************* -[RTL8821as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - -;; $$ ICtype 8821A End - -;; $$ ICtype 8814A Start -;******************************************************************************* -; RTL8814as common paramters -;******************************************************************************* -[RTL8814as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -;; Add for 8814AS, based on 8821AS's modification -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - -;; $$ ICtype 8814A End - -;; $$ ICtype 8192E Start -;******************************************************************************* -; RTL8192es common paramters -;******************************************************************************* -[RTL8192es.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" -;; $$ ICtype 8192E End - -;; $$ ICtype 8822B Start -;******************************************************************************* -; RTL8822bs common paramters -;******************************************************************************* -[RTL8822bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" -HKR,,ValidRFPath,0,"51" -HKR,,PreInitMem,0,"1" - -;; $$ ICtype 8822B End - -;; $$ ICtype 8723D Start -;******************************************************************************* -; RTL8723ds common paramters -;******************************************************************************* -[RTL8723ds.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,defaults,LdpcCap,0,"0" - -;; $$ ICtype 8723D End - -;;---------------------------------------------------------------------------- -;; Realtek WLAN NIC parameters -;;---------------------------------------------------------------------------- -[RTLWLAN.reg] - -; Enable Adaptivity -HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,Channel,0,"1" -HKR,,Channel,0,"1" - -;; Antenna Diversity Type -HKR,defaults,AntennaDivType,0,"0" -HKR,,AntennaDivType,0,"0" - -HKR,defaults,NetworkType,0,"1" -HKR,,NetworkType,0,"1" - -HKR,defaults,StaUapsd,0,"0" -HKR,,StaUapsd,0,"0" - -; For B/G mode and B/G/N mode switch, we will use different wireless mode registry in later section -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - - -;; For WiFi test, 1: WiFi Config and 0: Performance Config -HKR,defaults,WiFiConfg,0,"0" -HKR,,WiFiConfg,0,"0" - -HKR,defaults,RxReorder,0,"1" -HKR,,RxReorder,0,"1" - -HKR,,DefaultKeyID,,"0" -HKR,,DefaultKey0,,"" -HKR,,DefaultKey1,,"" -HKR,,DefaultKey2,,"" -HKR,,DefaultKey3,,"" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - -;Leisure Power Save -HKR,defaults,bLeisurePs,0,"2" -HKR,,bLeisurePs,0,"2" - -;Fw Control LPS -HKR,defaults,bFwCtrlLPS,0,"1" -HKR,,bFwCtrlLPS,0,"1" - -;; LPS Interval -;HKR,defaults,LPSIntvl,0,"3" -HKR,,LPSIntvl,0,"3" - -HKR,,WEPinNmode,0,"0" - -HKR,defaults,RxSC,0,"0" -HKR,,RxSC,0,"0" - -HKR,defaults,TxSC,0,"0" -HKR,,TxSC,0,"0" - -HKR,defaults,NblRacingWA,0,"1" -HKR,,NblRacingWA,0,"1" - -HKR,defaults,SuspendTimerInLowPwr,0,"1" -HKR,,SuspendTimerInLowPwr,0,"1" - -;; Rx reorder pending time -HKR,,RxReorder_PendTime,0,"100" - -;Antenna Diversity -HKR,Ndi\params\AntDiv, ParamDesc, 0, "Antenna Diversity" -HKR,Ndi\params\AntDiv, default, 0, "0" -HKR,Ndi\params\AntDiv, type, 0, "enum" -HKR,Ndi\params\AntDiv\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\AntDiv\enum, "1", 0, %ENABLED_STR% - -HKLM, SYSTEM\CurrentControlSet\Services\RtlWlans\Parameters, "BtAntennaInHw", 0x00010001,2 - -[Ndis5Set.reg] -HKR,Ndi\params\PSPXlinkMode, ParamDesc, 0, %PSP_XLINK_STR% -HKR,Ndi\params\PSPXlinkMode, type, 0, "enum" -HKR,Ndi\params\PSPXlinkMode, default, 0, "0" -HKR,Ndi\params\PSPXlinkMode\enum, "0", 0, %DISABLE_STR% -HKR,Ndi\params\PSPXlinkMode\enum, "1", 0, %ENABLE_STR% -HKR,defaults,PSPXlinkMode,0,"0" -HKR,,PSPXlinkMode,0,"0" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - - -[Ndis6Set.reg] -;Inactive Power Save -HKR,defaults,InactivePs,0,"2" -HKR,,InactivePs,0,"2" - - -;;---------------------------------------------------------------------------- -;; Wireless mode option parameters -;;---------------------------------------------------------------------------- -[11nWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -;; 40MHz Support in 11n -HKR,Ndi\params\BWSetting, ParamDesc, 0, "Bandwidth" -HKR,Ndi\params\BWSetting, type, 0, "enum" -HKR,Ndi\params\BWSetting, default, 0, "1" -HKR,Ndi\params\BWSetting\enum, "0", 0, "20MHz Only" -HKR,Ndi\params\BWSetting\enum, "1", 0, "20_40MHz" -HKR,defaults,BWSetting,0,"1" -HKR,,BWSetting,0,"1" -HKR,,BWSetting,,"1" - -HKR,,Channel,0,"10" - -[11gWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,defaults,WirelessMode, 0, "4" -HKR,,WirelessMode, 0, "4" - -HKR,,BWSetting,0,"0" - -HKR,,Channel,0,"10" - -[11acWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "8", 0, %AUTO_STR% -HKR,Ndi\params\WirelessMode\enum, "1", 0, %IEEE_802_11A_STR% -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "16", 0, %IEEE_802_11BGN_STR% -HKR,Ndi\params\WirelessMode\enum, "32", 0, %IEEE_802_11AN_STR% -HKR,Ndi\params\WirelessMode\enum, "64", 0, %IEEE_802_11ANAC_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -HKR,,Channel,0,"36" - -;; RF Type -HKR,,RFType,0,"15" - - -HKR,defaults,BWSetting,0,"2" -HKR,,BWSetting,0,"2" - -;;---------------------------------------------------------------------------- -;; LPS 32k Control Parameters -;;---------------------------------------------------------------------------- -[32kEnable.reg] -HKR,,bLowPowerEnable,0,"1" -[32kDisable.reg] -HKR,,bLowPowerEnable,0,"0" - -;------------------------------------------------------------------------------- -; PnP pre-transition handling -;------------------------------------------------------------------------------- -[PnpPreTransOn.reg] -HKR,,PreTransPnP,0,"1" -[PnpPreTransOff.reg] -HKR,,PreTransPnP,0,"0" - -;;---------------------------------------------------------------------------- -;; WOWLAN Control Parameters -;;---------------------------------------------------------------------------- -[WowlanAllEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanDisable.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"0" -HKR,,GTKOffloadEnable,0,"0" - -[WowlanAllEnableNoLPS.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanEnableNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[WowlanEnableNoLPSNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[ConnectedStandbyEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" -HKR,,D2ListenIntvl,0,"4" -HKR,,NSOffloadEnable,0,"1" -HKR,,NLOEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "0" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"0" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -;; Packet coalescing should be enabled in WHCK test -HKR,defaults,*PacketCoalescing,0,"0" -HKR,,*PacketCoalescing,0,"0" - -;------------------------------------------------------------------------------- -; Auto Channel Selection -;------------------------------------------------------------------------------- -[AutoChnlSelon.reg] -HKR,,AutoChnlSel,0,"1" -[AutoChnlSeloff.reg] -HKR,,AutoChnlSel,0,"0" - -;;---------------------------------------------------------------------------- -;; RSSI to Grid Mode Parameters -;;---------------------------------------------------------------------------- -[RSSI2GridRealMode.reg] -HKR,,RSSI2GridMode,0,"1" -[RSSI2GridMode_2.reg] -HKR,,RSSI2GridMode,0,"2" -[RSSI2GridMode_4.reg] -HKR,,RSSI2GridMode,0,"4" - -;;---------------------------------------------------------------------------- -;; KFREE parameters -;;---------------------------------------------------------------------------- -[KFREE_COMMON.reg] -HKR,,RfKFreeEnable,0,"0" - -;******************************************************************************* -; Customer reg section -;******************************************************************************* -[ScanType.reg] -HKR,defaults,PassiveScan, 0, "0" -HKR,,PassiveScan, 0, "0" - -;******************************************************************************* -; Multi-Channel Concurrent section -;******************************************************************************* -[MCC.reg] -HKR,Ndi\params\MultiChannelFcsMode, ParamDesc, 0, %MCC_STR% -HKR,Ndi\params\MultiChannelFcsMode, type, 0, "enum" -HKR,Ndi\params\MultiChannelFcsMode, default, 0, "0" -HKR,Ndi\params\MultiChannelFcsMode\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\MultiChannelFcsMode\enum, "4", 0, %ENABLED_STR% -HKR,defaults,MultiChannelFcsMode, 0, "0" -HKR,,MultiChannelFcsMode, 0, "0" - -;******************************************************************************* -; Destination Directory -;******************************************************************************* -[RTWlanS.CopyFiles] -;; $$ DriverName Start -rtwlans.sys,,,2 -;; $$ DriverName End - -[DestinationDirs] -DefaultDestDir = 11 -RTWlanS.CopyFiles = 12 -CIHVS.CopyFiles = 11 -RtlUI2.CopyFiles = 10 - -;;**************************************************************************** -;; Source Files -;;**************************************************************************** -[CIHVS.CopyFiles] -Rtlihvs.dll,,,2 -;; $$ FeatureType WAPI Start -RtlExtUI.dll,,,2 -;; $$ FeatureType WAPI End - -[RegisterUIExt] -11,,RtlExtUI.dll,1 - -[RtlUI2.CopyFiles] -RtlUI2.exe,,,2 - -[SourceDisksFiles] -;; $$ DriverName Start -rtwlans.sys = 1 -Rtlihvs.dll = 1 -;; $$ DriverName End -;; $$ FeatureType WAPI Start -RtlExtUI.dll = 1 -;; $$ FeatureType WAPI End - -[SourceDisksNames] -1=%DISKNAME%,,, - - -;******************************************************************************* -; Strings -;******************************************************************************* -[Strings] -SSID_STR = "SSID" -CHANNEL_STR = "Channel" -NETWORK_TYPE_STR = "Network Type" -LED_CONTROL_STR = "LED Control" -POWER_SAVE_STR = "Power Save Mode" -WIFI_IBSS_STR = "IBSS Default 11b Mode" -RATE_ADAPTIVE_STR = "Rate Adaptive" -QOS_STR = "QoS" -WiFiConfg_STR = "WiFiConfg" -WMM_APSD = "WMM APSD" -CCX_RM_STR = "CCX Radio Measurement" -CCX_OFF_LINE_DUR_UP_LIMIT_STR = "CCX Max Off-Line Measurement (0: unlimited)" -FORCE_PRIORITY_STR = "Forced Priority" -HW_PARA_STR = "Init from HwParaFile" -THREE_WIRE_MODE_STR = "Three Wire Programming Mode" -BOARD_TYPE_STR = "Board Type" -PROTECTION_MODE_STR = "Protection Mode" -TPC_STR = "Transmit Power Control" -TPC_POLARITY_STR = "TPC Polarity Select" -HIGH_POWER_STR = "High Power Mechanism" -INIT_GAIN_STR = "Initial Gain State" -CW_MAX_MIN_STR = "Contention Window" -PSP_XLINK_STR = "PSP XLink Mode" -DISABLE_STR = "Disable" -ENABLE_STR = "Enable" -DISABLED_STR = "Disabled" -ENABLED_STR = "Enabled" -AUTO_STR = "Auto" -AD_HOC_STR = "Ad Hoc" -INFRASTRUCTURE_STR = "Infrastructure" -AUTO_SELECT = "Auto select" -WL_MODE_STR = "Wireless Mode" -RX_REORDER_STR = "Rx Reorder" -CAM_STR = "CAM" -MAX_PSP_STR = "MAX_PSP" -Fast_PSP_STR = "Fast_PSP" -NO_AC_STR = "No AC (Disable)" -ALL_AC_STR = "ALL AC" -IEEE_802_11A_STR = "IEEE 802.11a" -IEEE_802_11B_STR = "IEEE 802.11b" -IEEE_802_11BG_STR = "IEEE 802.11b/g" -IEEE_802_11BGN_STR = "IEEE 802.11b/g/n" -IEEE_802_11AN_STR = "IEEE 802.11a/n" -IEEE_802_11ANAC_STR = "IEEE 802.11a/n/ac" -IEEE_802_11AC_STR = "IEEE 802.11 ac" -WakeOnMagicPacket = "Wake on Magic Packet" -WakeOnPattern = "Wake on Pattern Match" -MCC_STR = "Multi-Channel Concurrent" - -;******************************************************************************* -; manufacture description -;******************************************************************************* -Realtek = "Realtek Semiconductor Corp." - - -;******************************************************************************* -; Source disk name -;******************************************************************************* -;; $$ CDISKNAME Start -DISKNAME = "Realtek Wireless LAN 802.11n SDIO Network Adapter Driver Disk" -RtlWlans.DeviceDesc = "Realtek Wireless LAN 802.11n SDIO Network Adapter" -RtlWlans.DeviceDesc.DispName = "Realtek Wireless LAN 802.11n SDIO Network Adapter" -;; $$ CDISKNAME End - -;; $$ ICtype 8723A Start -;******************************************************************************* -; RTL8723as Device description -;******************************************************************************* -RTL8723as.DeviceDesc = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723as.DeviceDesc.DispName = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" -;; $$ ICtype 8723A End - - - -;; $$ ICtype 8723B Start -;******************************************************************************* -; RTL8723bs Device description -;******************************************************************************* -RTL8723bs.DeviceDesc = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723bs.DeviceDesc.DispName = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" -;; $$ ICtype 8723B End - -;; $$ ICtype 8814A Start -;******************************************************************************* -; RTL8814as Device description -;******************************************************************************* -RTL8814as.DeviceDesc = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" -RTL8814as.DeviceDesc.DispName = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" -;; $$ ICtype 8814A End - -;; $$ ICtype 8188E Start -;******************************************************************************* -; RTL8188ES Device description -;******************************************************************************* -RTL8188es.DeviceDesc = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8188es.DeviceDesc.DispName = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -;; $$ ICtype 8188E End -;; $$ ICtype 8821A Start -;******************************************************************************* -; RTL8821as Device description -;******************************************************************************* -RTL8821as.DeviceDesc = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8821as.DeviceDesc.DispName = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -;; $$ ICtype 8821A End -;; $$ ICtype 8192E Start -;******************************************************************************* -; RTL8192E Device description -;******************************************************************************* -RTL8192es.DeviceDesc = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8192es.DeviceDesc.DispName = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" -;; $$ ICtype 8192E End - -;; $$ ICtype 8703B Start -;******************************************************************************* -; RTL8703bs Device description -;******************************************************************************* -RTL8703bs.DeviceDesc = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8703bs.DeviceDesc.DispName = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" -;; $$ ICtype 8703B End - -;; $$ ICtype 8188F Start -;******************************************************************************* -; RTL8188Fs Device description -;******************************************************************************* -RTL8188fs.DeviceDesc = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -RTL8188fs.DeviceDesc.DispName = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -;; $$ ICtype 8188F End -;; $$ ICtype 8822B Start -;******************************************************************************* -; RTL8822bs Device description -;******************************************************************************* -RTL8822bs.DeviceDesc = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8822bs.DeviceDesc.DispName = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -;; $$ ICtype 8822B End - -;; $$ ICtype 8723D Start -;******************************************************************************* -; RTL8723ds Device description -;******************************************************************************* -RTL8723ds.DeviceDesc = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723ds.DeviceDesc.DispName = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" -;; $$ ICtype 8723D End \ No newline at end of file diff --git a/network/wlan/WDI/PLATFORM/WinInf/SDIO/x64/netrtwlans.inf b/network/wlan/WDI/PLATFORM/WinInf/SDIO/x64/netrtwlans.inf index 181700f1a..e7753ef3c 100644 Binary files a/network/wlan/WDI/PLATFORM/WinInf/SDIO/x64/netrtwlans.inf and b/network/wlan/WDI/PLATFORM/WinInf/SDIO/x64/netrtwlans.inf differ diff --git a/network/wlan/WDI/PLATFORM/WinInf/SDIO/x86/netrtwlans.inf b/network/wlan/WDI/PLATFORM/WinInf/SDIO/x86/netrtwlans.inf deleted file mode 100644 index 5e6b284bc..000000000 --- a/network/wlan/WDI/PLATFORM/WinInf/SDIO/x86/netrtwlans.inf +++ /dev/null @@ -1,1259 +0,0 @@ -;; netrtwlans.inf -;; -;; Realtek Wireless 802.11b/g/n SDIO Network Adapter -;; -;; Copyright (C) 2012 Realtek Semiconductor Corp. -;; -;; This release is primarily for WHQL test. -;; - -;; FOR XP/Vista/Win7/Win8 - -[Version] -Signature = "$Windows NT$" -Class = Net -ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} -Provider = %Realtek% -CatalogFile.NT = netrtwlans.cat ;; for WHQL certified -DriverVer = 11/23/2015,3008.22.1030.2015 - -[Manufacturer] -%Realtek% = Realtek,NTx86.10.0 - -[ControlFlags] -ExcludeFromSelect = * - -[Realtek.NTx86.10.0] -;; For 8723 RTK common ================================================================ - -;; For 8723 RTK common ================================================================ -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_8753 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_B723 -;; Acer -%RTL8723bs.DeviceDesc% = ACER8723bs.ndi, SD\VID_024C&PID_0623 -;; HP -%RTL8723bs.DeviceDesc% = HP8723bs.ndi, SD\VID_024C&PID_0523 -;; ECS -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0524 -;; bestbuy -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0240 -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0241 -;; For Braswell platform -%RTL8723bs.DeviceDesc% = RTL8723bs.ndi, SD\VID_024C&PID_0626 -;; Reserved -%RTL8723bs.DeviceDesc% = RSVD8723bs.ndi, SD\VID_024C&PID_0624 - -;; For 8188E RTK common ================================================================ -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8188 -%RTL8188es.DeviceDesc% = RTL8188es.ndi, SD\VID_024C&PID_8179 - -;; For 8812A RTK common ================================================================ - -;; For 8814A RTK common ================================================================ -%RTL8814as.DeviceDesc% = RTL8814as.ndi, SD\VID_024C&PID_8813 - -;; For 8821A RTK common ================================================================ -%RTL8821as.DeviceDesc% = RTL8821as.ndi, SD\VID_024C&PID_8821 - -;; For 8192ES RTK common ================================================================ -%RTL8192es.DeviceDesc% = RTL8192es.ndi, SD\VID_024C&PID_818B - - -;; For 8703 RTK common ================================================================ -%RTL8703bs.DeviceDesc% = RTL8703bs.ndi, SD\VID_024C&PID_B703 - -;; For 8188 RTK common ================================================================ -%RTL8188fs.DeviceDesc% = RTL8188fs.ndi, SD\VID_024C&PID_F179 - -;; For 8822B RTK common ================================================================ -%RTL8822bs.DeviceDesc% = RTL8822bs.ndi, SD\VID_024C&PID_B822 - -;; For 8723D RTK common ================================================================ -%RTL8723ds.DeviceDesc% = RTL8723ds.ndi, SD\VID_024C&PID_D723 - -;;---------------------------------------------------------------------------- -;; Realtek 8723as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723as.ndi.NT] -AddReg = NDIS_64.reg, RTL8723as.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8723bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;;---------------------------------------------------------------------------- -;; Acer 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[ACER8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, RSSI2GridMode_2.reg, MCC.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[ACER8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[ACER8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration -;;---------------------------------------------------------------------------- -;; HP 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[HP8723bs.ndi.NT] -AddReg = NDIS_64.reg, HP8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[HP8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[HP8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; RSVD 8723bs installation -;;---------------------------------------------------------------------------- - - - - - -[RSVD8723bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8723bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, WowlanDisable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RSVD8723bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RSVD8723bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8188eu default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8188es.ndi.NT] -AddReg = NDIS_64.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188es.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188es.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8821as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8821as.ndi.NT] -AddReg = NDIS_64.reg, RTL8821as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8821as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8821as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8814as default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8814as.ndi.NT] -AddReg = NDIS_64.reg, RTL8814as.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8814as.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8814as.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8192es default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8192es.ndi.NT] -AddReg = NDIS_64.reg, RTL8192es.common.reg, RTLWLAN.reg, 11nWirelessMode.reg, Ndis6Set.reg, CIHVS.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8192es.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8192es.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8703bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8703bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, AutoChnlSelon.reg, CIHVS.reg, KFREE_COMMON.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8703bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8703bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8188fs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8188fs.ndi.NT] -AddReg = NDIS_64.reg, RTL8703bs.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8188fs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8188fs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - -;;---------------------------------------------------------------------------- -;; Realtek 8822bs default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8822bs.ndi.NT] -AddReg = NDIS_64.reg, RTL8822bs.common.reg, RTLWLAN.reg, 11acWirelessMode.reg, Ndis6Set.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8822bs.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8822bs.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - - -;;---------------------------------------------------------------------------- -;; Realtek 8723ds default installation -;;---------------------------------------------------------------------------- - - - - - -[RTL8723ds.ndi.NT] -AddReg = NDIS_64.reg, RTL8723ds.common.reg, RTLWLAN.reg, Ndis6Set.reg, 11nWirelessMode.reg, ConnectedStandbyEnable.reg, 32kEnable.reg, CIHVS.reg, PnpPreTransOn.reg, AutoChnlSelon.reg -Include = netvwifibus.inf -Needs = VWiFiBus.CopyFiles -Characteristics = 0x84 -BusType = 15 -CopyFiles = RTWlanS.CopyFiles -*IfType = 71 ; IF_TYPE_IEEE80211 -*MediaType = 16 ; NdisMediumNative802_11 -*PhysicalMediaType = 9 ; NdisPhysicalMediumNative802_11 - -[RTL8723ds.ndi.NT.Services] -AddService = RtlWlans, 2, RtlWlans.Service, RtlWlans.EventLog -Include = netvwifibus.inf -Needs = VWiFiBus.Services - -[RTL8723ds.ndi.NT.HW] -Include = netvwifibus.inf -Needs = VWiFiBus.PnPFilterRegistration - -;;---------------------------------------------------------------------------- -;; OS relative registry. -;;---------------------------------------------------------------------------- -[NDIS_64.reg] -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5,mdcwifi" -HKR, Ndi\Interfaces, LowerRange, 0, "wlan,ethernet,vwifi" -HKR, Ndi, Service, 0, "RtlWlans" -;; -;; OS relative service. -;; -[RtlWlans.Service] -DisplayName = %RtlWlans.DeviceDesc.DispName% -ServiceType = 1 ; %SERVICE_KERNEL_DRIVER% -StartType = 3 ; %SERRVICE_DEMAND_START% -ErrorControl = 1 ; %SERRVICE_ERROR_NORMAL% -ServiceBinary = %12%\rtwlans.sys -LoadOrderGroup = NDIS - -;; -;; OS relative event log. -;; -[RtlWlans.EventLog] -AddReg = RtlWlans.AddEventLog.reg - -[RtlWlans.AddEventLog.reg] -HKR, , EventMessageFile, 0x00020000, "%%SystemRoot%%\System32\netevent.dll" -HKR, , TypesSupported , 0x00010001, 7 - -[CIHVS.reg] -HKR, Ndi\IHVExtensions, ExtensibilityDLL, 0, "%SystemRoot%\system32\Rtlihvs.dll" -HKR, Ndi\IHVExtensions, UIExtensibilityCLSID, 0, "{6C2A8CCA-B2A2-4d81-A3B2-4E15F445C312}" -HKR, Ndi\IHVExtensions, GroupName, 0, "Realtek CCX SDK IHV Service" -HKR, Ndi\IHVExtensions, AdapterOUI, 0x00010001, 0x00e04c - -;******************************************************************************* -; WAPI section -;******************************************************************************* -[wapi.reg] -HKR,defaults,WapiSupport,0,"1" -HKR,,WapiSupport,0,"1" - -;******************************************************************************* -; RTL8723as common paramters -;******************************************************************************* -[RTL8723as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - - -;******************************************************************************* -; RTL8723bs common paramters -;******************************************************************************* -[RTL8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -;;HKR,defaults,EnableAdaptivity,0,"0" -;;HKR,,EnableAdaptivity,0,"0" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of RTL8723bs.common.reg - -[HP8723bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - -; Enable Adaptivity -;;HKR,defaults,EnableAdaptivity,0,"1" -;;HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,EnableCarrierSense,0,"0" -HKR,,EnableCarrierSense,0,"0" - -; Enable Customeized PowerLimit Table -HKR,,EnableTxPowerLimit,0,"1" -HKR,,DecryptCustomFile,,"1" -HKR,,PwrLimitFile,0,"TXPWR_LMT_IEC0921_Enc.txt" - -; Regulation WorldWide -HKR,defaults,PwrTblSel,0,"4" -HKR,,PwrTblSel,0,"4" - -; AOAC reconnect -HKR,defaults,PnpKeepLink,0,"1" -HKR,,PnpKeepLink,0,"1" - -;; $$ End of HP8723bs.common.reg - -;******************************************************************************* -; RTL8703bs common paramters -;******************************************************************************* -[RTL8703bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"1" -HKR,,RomDLFwEnable,0,"1" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - - -;******************************************************************************* -; RTL8188Fs common paramters -;******************************************************************************* -[RTL8188fs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,RomDLFwEnable,0,"0" -HKR,,RomDLFwEnable,0,"0" - -HKR,defaults,bFwCtrlPwrOff,0,"1" -HKR,,bFwCtrlPwrOff,0,"1" - - -;******************************************************************************* -; RTL8821as common paramters -;******************************************************************************* -[RTL8821as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - - -;******************************************************************************* -; RTL8814as common paramters -;******************************************************************************* -[RTL8814as.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -;; Add for 8814AS, based on 8821AS's modification -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" - - -;******************************************************************************* -; RTL8192es common paramters -;******************************************************************************* -[RTL8192es.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -;******************************************************************************* -; RTL8822bs common paramters -;******************************************************************************* -[RTL8822bs.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,,StbcCap,0,"17" -HKR,,LdpcCap,0,"34" -HKR,,BeamformCap,0,"34" -HKR,,ValidRFPath,0,"51" -HKR,,PreInitMem,0,"1" - - -;******************************************************************************* -; RTL8723ds common paramters -;******************************************************************************* -[RTL8723ds.common.reg] -HKR,defaults,LedCtrl,0,"1" -HKR,,LedCtrl,0,"1" - -HKR,defaults,QoS,0,"1" -HKR,,QoS,0,"1" - -HKR,defaults,CcxRm,0,"1" -HKR,,CcxRm,0,"1" - -HKR,defaults,CcxOffLineDurUpLimit,0,"0" -HKR,,CcxOffLineDurUpLimit,0,"0" - -HKR,defaults,UsbRxAggMode,0,"1" -HKR,,UsbRxAggMode,0,"1" - -HKR,defaults,bEarlymodeEnable,0,"0" -HKR,,bEarlymodeEnable,0,"0" - -HKR,defaults,LdpcCap,0,"0" - - -;;---------------------------------------------------------------------------- -;; Realtek WLAN NIC parameters -;;---------------------------------------------------------------------------- -[RTLWLAN.reg] - -; Enable Adaptivity -HKR,,EnableAdaptivity,0,"1" - -HKR,defaults,Channel,0,"1" -HKR,,Channel,0,"1" - -;; Antenna Diversity Type -HKR,defaults,AntennaDivType,0,"0" -HKR,,AntennaDivType,0,"0" - -HKR,defaults,NetworkType,0,"1" -HKR,,NetworkType,0,"1" - -HKR,defaults,StaUapsd,0,"0" -HKR,,StaUapsd,0,"0" - -; For B/G mode and B/G/N mode switch, we will use different wireless mode registry in later section -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - - -;; For WiFi test, 1: WiFi Config and 0: Performance Config -HKR,defaults,WiFiConfg,0,"0" -HKR,,WiFiConfg,0,"0" - -HKR,defaults,RxReorder,0,"1" -HKR,,RxReorder,0,"1" - -HKR,,DefaultKeyID,,"0" -HKR,,DefaultKey0,,"" -HKR,,DefaultKey1,,"" -HKR,,DefaultKey2,,"" -HKR,,DefaultKey3,,"" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - -;Leisure Power Save -HKR,defaults,bLeisurePs,0,"2" -HKR,,bLeisurePs,0,"2" - -;Fw Control LPS -HKR,defaults,bFwCtrlLPS,0,"1" -HKR,,bFwCtrlLPS,0,"1" - -;; LPS Interval -;HKR,defaults,LPSIntvl,0,"3" -HKR,,LPSIntvl,0,"3" - -HKR,,WEPinNmode,0,"0" - -HKR,defaults,RxSC,0,"0" -HKR,,RxSC,0,"0" - -HKR,defaults,TxSC,0,"0" -HKR,,TxSC,0,"0" - -HKR,defaults,NblRacingWA,0,"1" -HKR,,NblRacingWA,0,"1" - -HKR,defaults,SuspendTimerInLowPwr,0,"1" -HKR,,SuspendTimerInLowPwr,0,"1" - -;; Rx reorder pending time -HKR,,RxReorder_PendTime,0,"100" - -;Antenna Diversity -HKR,Ndi\params\AntDiv, ParamDesc, 0, "Antenna Diversity" -HKR,Ndi\params\AntDiv, default, 0, "0" -HKR,Ndi\params\AntDiv, type, 0, "enum" -HKR,Ndi\params\AntDiv\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\AntDiv\enum, "1", 0, %ENABLED_STR% - -HKLM, SYSTEM\CurrentControlSet\Services\RtlWlans\Parameters, "BtAntennaInHw", 0x00010001,2 - -[Ndis5Set.reg] -HKR,Ndi\params\PSPXlinkMode, ParamDesc, 0, %PSP_XLINK_STR% -HKR,Ndi\params\PSPXlinkMode, type, 0, "enum" -HKR,Ndi\params\PSPXlinkMode, default, 0, "0" -HKR,Ndi\params\PSPXlinkMode\enum, "0", 0, %DISABLE_STR% -HKR,Ndi\params\PSPXlinkMode\enum, "1", 0, %ENABLE_STR% -HKR,defaults,PSPXlinkMode,0,"0" -HKR,,PSPXlinkMode,0,"0" - -;Inactive Power Save -HKR,defaults,InactivePs,0,"0" -HKR,,InactivePs,0,"0" - - -[Ndis6Set.reg] -;Inactive Power Save -HKR,defaults,InactivePs,0,"2" -HKR,,InactivePs,0,"2" - - -;;---------------------------------------------------------------------------- -;; Wireless mode option parameters -;;---------------------------------------------------------------------------- -[11nWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "8", 0, %IEEE_802_11BGN_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -;; 40MHz Support in 11n -HKR,Ndi\params\BWSetting, ParamDesc, 0, "Bandwidth" -HKR,Ndi\params\BWSetting, type, 0, "enum" -HKR,Ndi\params\BWSetting, default, 0, "1" -HKR,Ndi\params\BWSetting\enum, "0", 0, "20MHz Only" -HKR,Ndi\params\BWSetting\enum, "1", 0, "20_40MHz" -HKR,defaults,BWSetting,0,"1" -HKR,,BWSetting,0,"1" -HKR,,BWSetting,,"1" - -HKR,,Channel,0,"10" - -[11gWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,defaults,WirelessMode, 0, "4" -HKR,,WirelessMode, 0, "4" - -HKR,,BWSetting,0,"0" - -HKR,,Channel,0,"10" - -[11acWirelessMode.reg] -HKR,Ndi\params\WirelessMode, ParamDesc, 0, %WL_MODE_STR% -HKR,Ndi\params\WirelessMode, type, 0, "enum" -HKR,Ndi\params\WirelessMode, default, 0, "8" -HKR,Ndi\params\WirelessMode\enum, "8", 0, %AUTO_STR% -HKR,Ndi\params\WirelessMode\enum, "1", 0, %IEEE_802_11A_STR% -HKR,Ndi\params\WirelessMode\enum, "2", 0, %IEEE_802_11B_STR% -HKR,Ndi\params\WirelessMode\enum, "4", 0, %IEEE_802_11BG_STR% -HKR,Ndi\params\WirelessMode\enum, "16", 0, %IEEE_802_11BGN_STR% -HKR,Ndi\params\WirelessMode\enum, "32", 0, %IEEE_802_11AN_STR% -HKR,Ndi\params\WirelessMode\enum, "64", 0, %IEEE_802_11ANAC_STR% -HKR,defaults,WirelessMode, 0, "8" -HKR,,WirelessMode, 0, "8" - -HKR,,Channel,0,"36" - -;; RF Type -HKR,,RFType,0,"15" - - -HKR,defaults,BWSetting,0,"2" -HKR,,BWSetting,0,"2" - -;;---------------------------------------------------------------------------- -;; LPS 32k Control Parameters -;;---------------------------------------------------------------------------- -[32kEnable.reg] -HKR,,bLowPowerEnable,0,"1" -[32kDisable.reg] -HKR,,bLowPowerEnable,0,"0" - -;------------------------------------------------------------------------------- -; PnP pre-transition handling -;------------------------------------------------------------------------------- -[PnpPreTransOn.reg] -HKR,,PreTransPnP,0,"1" -[PnpPreTransOff.reg] -HKR,,PreTransPnP,0,"0" - -;;---------------------------------------------------------------------------- -;; WOWLAN Control Parameters -;;---------------------------------------------------------------------------- -[WowlanAllEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanDisable.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"0" -HKR,,GTKOffloadEnable,0,"0" - -[WowlanAllEnableNoLPS.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -[WowlanEnableNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[WowlanEnableNoLPSNoPatternMatch.reg] -HKR,,WoWLANLPSLevel,0,"0" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "1" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"1" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "0" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"0" - -[ConnectedStandbyEnable.reg] -HKR,,WoWLANLPSLevel,0,"2" -HKR,,ARPOffloadEnable,0,"1" -HKR,,GTKOffloadEnable,0,"1" -HKR,,D2ListenIntvl,0,"4" -HKR,,NSOffloadEnable,0,"1" -HKR,,NLOEnable,0,"1" - -HKR, Ndi\params\*WakeOnMagicPacket, ParamDesc, 0, %WakeOnMagicPacket% -HKR, Ndi\params\*WakeOnMagicPacket, default, 0, "0" -HKR, Ndi\params\*WakeOnMagicPacket, type, 0, "enum" -HKR, Ndi\params\*WakeOnMagicPacket\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnMagicPacket\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnMagicPacket,0,"0" - -HKR, Ndi\params\*WakeOnPattern , ParamDesc, 0, %WakeOnPattern% -HKR, Ndi\params\*WakeOnPattern, default, 0, "1" -HKR, Ndi\params\*WakeOnPattern, type, 0, "enum" -HKR, Ndi\params\*WakeOnPattern\enum, "0", 0, %DISABLED_STR% -HKR, Ndi\params\*WakeOnPattern\enum, "1", 0, %ENABLED_STR% -HKR,,*WakeOnPattern,0,"1" - -;; Packet coalescing should be enabled in WHCK test -HKR,defaults,*PacketCoalescing,0,"0" -HKR,,*PacketCoalescing,0,"0" - -;------------------------------------------------------------------------------- -; Auto Channel Selection -;------------------------------------------------------------------------------- -[AutoChnlSelon.reg] -HKR,,AutoChnlSel,0,"1" -[AutoChnlSeloff.reg] -HKR,,AutoChnlSel,0,"0" - -;;---------------------------------------------------------------------------- -;; RSSI to Grid Mode Parameters -;;---------------------------------------------------------------------------- -[RSSI2GridRealMode.reg] -HKR,,RSSI2GridMode,0,"1" -[RSSI2GridMode_2.reg] -HKR,,RSSI2GridMode,0,"2" -[RSSI2GridMode_4.reg] -HKR,,RSSI2GridMode,0,"4" - -;;---------------------------------------------------------------------------- -;; KFREE parameters -;;---------------------------------------------------------------------------- -[KFREE_COMMON.reg] -HKR,,RfKFreeEnable,0,"0" - -;******************************************************************************* -; Customer reg section -;******************************************************************************* -[ScanType.reg] -HKR,defaults,PassiveScan, 0, "0" -HKR,,PassiveScan, 0, "0" - -;******************************************************************************* -; Multi-Channel Concurrent section -;******************************************************************************* -[MCC.reg] -HKR,Ndi\params\MultiChannelFcsMode, ParamDesc, 0, %MCC_STR% -HKR,Ndi\params\MultiChannelFcsMode, type, 0, "enum" -HKR,Ndi\params\MultiChannelFcsMode, default, 0, "0" -HKR,Ndi\params\MultiChannelFcsMode\enum, "0", 0, %DISABLED_STR% -HKR,Ndi\params\MultiChannelFcsMode\enum, "4", 0, %ENABLED_STR% -HKR,defaults,MultiChannelFcsMode, 0, "0" -HKR,,MultiChannelFcsMode, 0, "0" - -;******************************************************************************* -; Destination Directory -;******************************************************************************* -[RTWlanS.CopyFiles] -rtwlans.sys,,,2 - -[DestinationDirs] -DefaultDestDir = 11 -RTWlanS.CopyFiles = 12 -CIHVS.CopyFiles = 11 -RtlUI2.CopyFiles = 10 - -;;**************************************************************************** -;; Source Files -;;**************************************************************************** -[CIHVS.CopyFiles] -Rtlihvs.dll,,,2 - -[RegisterUIExt] -11,,RtlExtUI.dll,1 - -[RtlUI2.CopyFiles] -RtlUI2.exe,,,2 - -[SourceDisksFiles] -rtwlans.sys = 1 -Rtlihvs.dll = 1 - -[SourceDisksNames] -1=%DISKNAME%,,, - - -;******************************************************************************* -; Strings -;******************************************************************************* -[Strings] -SSID_STR = "SSID" -CHANNEL_STR = "Channel" -NETWORK_TYPE_STR = "Network Type" -LED_CONTROL_STR = "LED Control" -POWER_SAVE_STR = "Power Save Mode" -WIFI_IBSS_STR = "IBSS Default 11b Mode" -RATE_ADAPTIVE_STR = "Rate Adaptive" -QOS_STR = "QoS" -WiFiConfg_STR = "WiFiConfg" -WMM_APSD = "WMM APSD" -CCX_RM_STR = "CCX Radio Measurement" -CCX_OFF_LINE_DUR_UP_LIMIT_STR = "CCX Max Off-Line Measurement (0: unlimited)" -FORCE_PRIORITY_STR = "Forced Priority" -HW_PARA_STR = "Init from HwParaFile" -THREE_WIRE_MODE_STR = "Three Wire Programming Mode" -BOARD_TYPE_STR = "Board Type" -PROTECTION_MODE_STR = "Protection Mode" -TPC_STR = "Transmit Power Control" -TPC_POLARITY_STR = "TPC Polarity Select" -HIGH_POWER_STR = "High Power Mechanism" -INIT_GAIN_STR = "Initial Gain State" -CW_MAX_MIN_STR = "Contention Window" -PSP_XLINK_STR = "PSP XLink Mode" -DISABLE_STR = "Disable" -ENABLE_STR = "Enable" -DISABLED_STR = "Disabled" -ENABLED_STR = "Enabled" -AUTO_STR = "Auto" -AD_HOC_STR = "Ad Hoc" -INFRASTRUCTURE_STR = "Infrastructure" -AUTO_SELECT = "Auto select" -WL_MODE_STR = "Wireless Mode" -RX_REORDER_STR = "Rx Reorder" -CAM_STR = "CAM" -MAX_PSP_STR = "MAX_PSP" -Fast_PSP_STR = "Fast_PSP" -NO_AC_STR = "No AC (Disable)" -ALL_AC_STR = "ALL AC" -IEEE_802_11A_STR = "IEEE 802.11a" -IEEE_802_11B_STR = "IEEE 802.11b" -IEEE_802_11BG_STR = "IEEE 802.11b/g" -IEEE_802_11BGN_STR = "IEEE 802.11b/g/n" -IEEE_802_11AN_STR = "IEEE 802.11a/n" -IEEE_802_11ANAC_STR = "IEEE 802.11a/n/ac" -IEEE_802_11AC_STR = "IEEE 802.11 ac" -WakeOnMagicPacket = "Wake on Magic Packet" -WakeOnPattern = "Wake on Pattern Match" -MCC_STR = "Multi-Channel Concurrent" - -;******************************************************************************* -; manufacture description -;******************************************************************************* -Realtek = "Realtek Semiconductor Corp." - - -;******************************************************************************* -; Source disk name -;******************************************************************************* -DISKNAME = "Realtek Wireless LAN 802.11n SDIO Network Adapter Driver Disk" -RtlWlans.DeviceDesc = "Realtek Wireless LAN 802.11n SDIO Network Adapter" -RtlWlans.DeviceDesc.DispName = "Realtek Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8723as Device description -;******************************************************************************* -RTL8723as.DeviceDesc = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723as.DeviceDesc.DispName = "Realtek RTL8723AS Wireless LAN 802.11n SDIO Network Adapter" - - - -;******************************************************************************* -; RTL8723bs Device description -;******************************************************************************* -RTL8723bs.DeviceDesc = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723bs.DeviceDesc.DispName = "Realtek RTL8723BS Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8814as Device description -;******************************************************************************* -RTL8814as.DeviceDesc = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" -RTL8814as.DeviceDesc.DispName = "Realtek RTL8814AS Wireless LAN 802.11ac SDIO Network Adapter" - -;******************************************************************************* -; RTL8188ES Device description -;******************************************************************************* -RTL8188es.DeviceDesc = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8188es.DeviceDesc.DispName = "Realtek RTL8189ES Wireless LAN 802.11n USB 2.0 Network Adapter" -;******************************************************************************* -; RTL8821as Device description -;******************************************************************************* -RTL8821as.DeviceDesc = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8821as.DeviceDesc.DispName = "Realtek RTL8821AS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -;******************************************************************************* -; RTL8192E Device description -;******************************************************************************* -RTL8192es.DeviceDesc = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" -RTL8192es.DeviceDesc.DispName = "Realtek RTL8192ES Wireless LAN 802.11n USB 2.0 Network Adapter" - -;******************************************************************************* -; RTL8703bs Device description -;******************************************************************************* -RTL8703bs.DeviceDesc = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" -RTL8703bs.DeviceDesc.DispName = "Realtek RTL8703BS Wireless LAN 802.11n SDIO Network Adapter" - -;******************************************************************************* -; RTL8188Fs Device description -;******************************************************************************* -RTL8188fs.DeviceDesc = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -RTL8188fs.DeviceDesc.DispName = "Realtek RTL8189FTV Wireless LAN 802.11n SDIO Network Adapter" -;******************************************************************************* -; RTL8822bs Device description -;******************************************************************************* -RTL8822bs.DeviceDesc = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" -RTL8822bs.DeviceDesc.DispName = "Realtek RTL8822BS Wireless LAN 802.11ac SDIO 2.0 Network Adapter" - -;******************************************************************************* -; RTL8723ds Device description -;******************************************************************************* -RTL8723ds.DeviceDesc = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" -RTL8723ds.DeviceDesc.DispName = "Realtek RTL8723DS Wireless LAN 802.11n SDIO Network Adapter" diff --git a/network/wlan/WDI/windows.msbuild.rtwssample.sln b/network/wlan/WDI/windows.msbuild.rtwssample.sln index 0d8732a83..ccca52781 100644 --- a/network/wlan/WDI/windows.msbuild.rtwssample.sln +++ b/network/wlan/WDI/windows.msbuild.rtwssample.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.23107.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33530.505 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sdio", "PLATFORM\NDIS6\SDIO\sdio.vcxproj", "{105EA485-B9B6-48AE-B8B0-96BBEA575973}" ProjectSection(ProjectDependencies) = postProject @@ -15,65 +15,25 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NdisComm", "PLATFORM\NdisCo EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Win10 Debug|Arm = Win10 Debug|Arm - Win10 Debug|Win32 = Win10 Debug|Win32 Win10 Debug|x64 = Win10 Debug|x64 - Win10 Release|Arm = Win10 Release|Arm - Win10 Release|Win32 = Win10 Release|Win32 Win10 Release|x64 = Win10 Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Arm.ActiveCfg = Win10 Debug|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Arm.Build.0 = Win10 Debug|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Arm.Deploy.0 = Win10 Debug|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Win32.ActiveCfg = Win10 Debug|Win32 - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Win32.Build.0 = Win10 Debug|Win32 - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|Win32.Deploy.0 = Win10 Debug|Win32 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|x64.ActiveCfg = Win10 Debug|x64 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|x64.Build.0 = Win10 Debug|x64 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Debug|x64.Deploy.0 = Win10 Debug|x64 - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Arm.ActiveCfg = Win10 Release|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Arm.Build.0 = Win10 Release|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Arm.Deploy.0 = Win10 Release|Arm - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Win32.ActiveCfg = Win10 Release|Win32 - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Win32.Build.0 = Win10 Release|Win32 - {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|Win32.Deploy.0 = Win10 Release|Win32 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|x64.ActiveCfg = Win10 Release|x64 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|x64.Build.0 = Win10 Release|x64 {105EA485-B9B6-48AE-B8B0-96BBEA575973}.Win10 Release|x64.Deploy.0 = Win10 Release|x64 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Arm.ActiveCfg = Win10 Debug|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Arm.Build.0 = Win10 Debug|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Arm.Deploy.0 = Win10 Debug|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Win32.ActiveCfg = Win10 Debug|Win32 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Win32.Build.0 = Win10 Debug|Win32 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|Win32.Deploy.0 = Win10 Debug|Win32 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|x64.ActiveCfg = Win10 Debug|x64 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|x64.Build.0 = Win10 Debug|x64 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Debug|x64.Deploy.0 = Win10 Debug|x64 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Arm.ActiveCfg = Win10 Release|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Arm.Build.0 = Win10 Release|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Arm.Deploy.0 = Win10 Release|Arm - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Win32.ActiveCfg = Win10 Release|Win32 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Win32.Build.0 = Win10 Release|Win32 - {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|Win32.Deploy.0 = Win10 Release|Win32 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|x64.ActiveCfg = Win10 Release|x64 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|x64.Build.0 = Win10 Release|x64 {956B060D-1055-4584-9CF4-9FE14C428545}.Win10 Release|x64.Deploy.0 = Win10 Release|x64 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Arm.ActiveCfg = Win10 Debug|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Arm.Build.0 = Win10 Debug|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Arm.Deploy.0 = Win10 Debug|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Win32.ActiveCfg = Win10 Debug|Win32 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Win32.Build.0 = Win10 Debug|Win32 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|Win32.Deploy.0 = Win10 Debug|Win32 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|x64.ActiveCfg = Win10 Debug|x64 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|x64.Build.0 = Win10 Debug|x64 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Debug|x64.Deploy.0 = Win10 Debug|x64 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Arm.ActiveCfg = Win10 Release|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Arm.Build.0 = Win10 Release|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Arm.Deploy.0 = Win10 Release|Arm - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Win32.ActiveCfg = Win10 Release|Win32 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Win32.Build.0 = Win10 Release|Win32 - {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|Win32.Deploy.0 = Win10 Release|Win32 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|x64.ActiveCfg = Win10 Release|x64 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|x64.Build.0 = Win10 Release|x64 {C0A51792-1338-4294-ADAA-EDC4EE30CF05}.Win10 Release|x64.Deploy.0 = Win10 Release|x64 diff --git a/network/wsk/echosrv/echosrv.vcxproj b/network/wsk/echosrv/echosrv.vcxproj index c97a2baeb..d511133db 100644 --- a/network/wsk/echosrv/echosrv.vcxproj +++ b/network/wsk/echosrv/echosrv.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/network/wwan/cxwmbclass/cxwmbclass/cxwmbclass.inf b/network/wwan/cxwmbclass/cxwmbclass/cxwmbclass.inf index 69055bfbd..48f893c6a 100644 Binary files a/network/wwan/cxwmbclass/cxwmbclass/cxwmbclass.inf and b/network/wwan/cxwmbclass/cxwmbclass/cxwmbclass.inf differ diff --git a/nfc/NfcCxSample/windows-drivertemplate-nfc/windows-drivertemplate-nfc.inf b/nfc/NfcCxSample/windows-drivertemplate-nfc/windows-drivertemplate-nfc.inf index 2c26ad5be..5d1afa6e7 100644 Binary files a/nfc/NfcCxSample/windows-drivertemplate-nfc/windows-drivertemplate-nfc.inf and b/nfc/NfcCxSample/windows-drivertemplate-nfc/windows-drivertemplate-nfc.inf differ diff --git a/nfp/net/README.md b/nfp/net/README.md index 0df760298..159d2697c 100644 --- a/nfp/net/README.md +++ b/nfp/net/README.md @@ -14,6 +14,8 @@ products: > UMDF 2 is the latest version of UMDF and supersedes UMDF 1. All new UMDF drivers should be written using UMDF 2. No new features are being added to UMDF 1 and there is limited support for UMDF 1 on newer versions of Windows 10. Universal Windows drivers must use UMDF 2. > > For more info, see [Getting Started with UMDF](https://docs.microsoft.com/windows-hardware/drivers/wdf/getting-started-with-umdf-version-2). +> +> The UMDF v1 sample can be accessed using `git checkout win11-22h2`. A direct link is: https://github.com/microsoft/Windows-driver-samples/tree/win11-22h2 This sample demonstrates how to use User-Mode Driver Framework (UMDF) version 1 to write a near-field proximity driver. diff --git a/nfp/net/driver/Connection.cpp b/nfp/net/driver/Connection.cpp deleted file mode 100644 index 1aed9008d..000000000 --- a/nfp/net/driver/Connection.cpp +++ /dev/null @@ -1,296 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Author: - - Travis Martin (TravM) 06-24-2010 - ---*/ -#include "internal.h" - -#include "Connection.tmh" - -HRESULT SetSocketIpv6Only(_In_ SOCKET socket, _In_ BOOL Ipv6Only); - -HRESULT SynchronousReadSocket(_In_ SOCKET Socket, _In_reads_bytes_(cbBuffer) PVOID pBuffer, _In_ DWORD cbBuffer) -{ - HRESULT hr = S_OK; - DWORD dwIgnore; - OVERLAPPED Overlapped; - ZeroMemory(&Overlapped, sizeof(Overlapped)); - if (!ReadFile((HANDLE)Socket, pBuffer, cbBuffer, &dwIgnore, &Overlapped)) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING)) - { - if (!GetOverlappedResult((HANDLE)Socket, &Overlapped, &dwIgnore, TRUE)) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - else - { - hr = S_OK; - } - } - } - return hr; -} - -//CConnection -// static -HRESULT CConnection::Create(_In_ IConnectionCallback* pCallback, _Outptr_ CConnection** ppConnection) -{ - CConnection* pConnection; - pConnection = new CConnection(pCallback); - HRESULT hr = (pConnection != NULL ? S_OK : E_OUTOFMEMORY); - if (SUCCEEDED(hr)) - { - *ppConnection = pConnection; - } - - return hr; -} - -void CConnection::Terminate() -{ - MethodEntry("void"); - - // Only want to terminate once - STATE PriorState = (STATE)(InterlockedExchange((long*)&_State, (long)TERMINATED)); - if (PriorState != TERMINATED) - { - // Graceful shutdown - shutdown(_Socket, SD_SEND); - - // Don't wait for threadpool callbacks when this thread is actually the threadpool callback - if (_ThreadpoolThreadId != GetCurrentThreadId()) - { - // Let the ReceiveThreadProc gracefully shutdown - WaitForThreadpoolWorkCallbacks(_ThreadpoolWork, false); - } - - SOCKET Socket = (SOCKET)InterlockedExchangePointer((PVOID*)&_Socket, (PVOID)INVALID_SOCKET); - if (Socket != INVALID_SOCKET) - { - closesocket(Socket); - } - } - - MethodReturnVoid(); -} - -/* 9C7D2C68-5AD8-4A14-BE20-F8741D60D100 */ -const GUID MAGIC_PACKET = - {0x9C7D2C68, 0x5AD8, 0x4A14, {0xBE, 0x20, 0xF8, 0x74, 0x1D, 0x60, 0xD1, 0x00}}; - -HRESULT CConnection::InitializeAsClient(_In_ BEGIN_PROXIMITY_ARGS* pArgs) -{ - pArgs->szName[MAX_PATH-1] = L'\0'; - - MethodEntry("pArgs->szName = '%S'", - pArgs->szName); - - // Open a TCP/IP Socket to the remote Network NearFieldProximity device - HRESULT hr = S_OK; - - _Socket = socket(AF_INET6, SOCK_STREAM, 0); - if (_Socket == INVALID_SOCKET) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - - if (SUCCEEDED(hr)) - { - hr = SetSocketIpv6Only(_Socket, FALSE); - } - - if (SUCCEEDED(hr)) - { - SOCKADDR_STORAGE LocalAddress = {}; - SOCKADDR_STORAGE RemoteAddress = {}; - DWORD cbLocalAddress = sizeof(LocalAddress); - DWORD cbRemoteAddress = sizeof(RemoteAddress); - timeval Timeout = {8, 0}; - if (!WSAConnectByName(_Socket, pArgs->szName, L"9299", - &cbLocalAddress, (SOCKADDR*)&LocalAddress, - &cbRemoteAddress, (SOCKADDR*)&RemoteAddress, &Timeout, NULL)) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - TraceErrorHR(hr, L"WSAConnectByName FAILED"); - } - } - - if (SUCCEEDED(hr)) - { - if (setsockopt(_Socket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - } - - if (SUCCEEDED(hr)) - { - // Send the Magic Packet - if (send(_Socket, (char*)&MAGIC_PACKET, sizeof(MAGIC_PACKET), 0) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - - if (SUCCEEDED(hr)) - { - GUID MagicPacket = {}; - hr = SynchronousReadSocket(_Socket, &MagicPacket, sizeof(MagicPacket)); - if (SUCCEEDED(hr)) - { - if (memcmp(&MagicPacket, &MAGIC_PACKET, sizeof(MAGIC_PACKET)) != 0) - { - hr = E_FAIL; - } - } - } - - if (SUCCEEDED(hr)) - { - // This doesn't take the socket, because we're the client and already - // have the socket in _Socket. - hr = FinalizeEstablish(INVALID_SOCKET); - } - } - - - if (FAILED(hr)) - { - if (_Socket != INVALID_SOCKET) - { - // Abortive shutdown of the socket - closesocket(_Socket); - _Socket = INVALID_SOCKET; - } - } - - MethodReturnHR(hr); -} - -void CConnection::ValidateAccept(_In_ SOCKET Socket, _In_ GUID* pMagicPacket) -{ - MethodEntry("..."); - - TraceASSERT(Socket != INVALID_SOCKET); - - HRESULT hr = S_OK; - if (memcmp(pMagicPacket, &MAGIC_PACKET, sizeof(MAGIC_PACKET)) != 0) - { - hr = E_FAIL; - } - - if (SUCCEEDED(hr)) - { - // Send the MAGIC_PACKET - if (send(Socket, (char*)&MAGIC_PACKET, sizeof(MAGIC_PACKET), 0) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - } - - if (SUCCEEDED(hr)) - { - hr = FinalizeEstablish(Socket); - } - - if (FAILED(hr)) - { - // Abortive shutdown of the socket - closesocket(Socket); - } - - MethodReturnVoid(); -} - -HRESULT CConnection::FinalizeEstablish(_In_ SOCKET Socket) -{ - MethodEntry("..."); - - HRESULT hr = S_OK; - STATE PriorState = (STATE)(InterlockedCompareExchange((long*)&_State, (long)ESTABLISHED, (long)INITIAL)); - if (PriorState != INITIAL) - { - // Already established (or terminated), drop this - hr = HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED); - } - - if (SUCCEEDED(hr)) - { - // Init Threadpool work item for the receieve thread proc. - _ThreadpoolWork = CreateThreadpoolWork(s_ReceiveThreadProc, this, NULL); - if (_ThreadpoolWork == NULL) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - else - { - if (Socket != INVALID_SOCKET) - { - // Take ownership of the socket - _Socket = Socket; - } - SubmitThreadpoolWork(_ThreadpoolWork); - - _pCallback->ConnectionEstablished(this); - } - } - - MethodReturnHR(hr); -} - -BOOL CConnection::ReceiveThreadProc() -{ - MethodEntry("void"); - - MESSAGE* pMessage = new MESSAGE(); - if (pMessage == NULL) - { - Terminate(); - } - else - { - while (_Socket != INVALID_SOCKET) - { - if (recv(_Socket, (char*)pMessage, sizeof(*pMessage), MSG_WAITALL) == sizeof(*pMessage)) - { - _pCallback->HandleReceivedMessage(pMessage); - } - else - { - Terminate(); - break; - } - } - delete pMessage; - } - - // The connection is now terminated - BOOL fConnectionDeleted = _pCallback->ConnectionTerminated(this); - - MethodReturnBool(fConnectionDeleted); -} - -HRESULT CConnection::TransmitMessage(_In_ MESSAGE* pMessage) -{ - HRESULT hr = S_OK; - if (_Socket == INVALID_SOCKET) - { - hr = HRESULT_FROM_WIN32(WSAENOTSOCK); - } - else - { - if (send(_Socket, (char*)pMessage, sizeof(*pMessage), 0) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - Terminate(); - } - } - - return hr; -} - diff --git a/nfp/net/driver/FileContext.cpp b/nfp/net/driver/FileContext.cpp deleted file mode 100644 index 193c637ab..000000000 --- a/nfp/net/driver/FileContext.cpp +++ /dev/null @@ -1,713 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - filecontext.cpp - -Abstract: - - This file implements the class for context associated with the file object - -Environment: - - user mode only - -Revision History: - ---*/ -#include "internal.h" - -#include "FileContext.tmh" - -CFileContext::~CFileContext() -{ - MethodEntry("void"); - - while (!IsListEmpty(&m_SubscribedMessageQueue)) - { - delete CMyPayload::FromListEntry(RemoveHeadList(&m_SubscribedMessageQueue)); - } - - if (m_pszType != NULL) - { - delete [] m_pszType; - m_pszType = NULL; - } - - if (m_pConnection != NULL) - { - delete m_pConnection; - m_pConnection = NULL; - } - - m_pWdfFile = NULL; - - EnterCriticalSection(&m_RoleLock); - CompleteRequest(E_ABORT, 0, true); - LeaveCriticalSection(&m_RoleLock); - - DeleteCriticalSection(&m_RoleLock); - - MethodReturnVoid(); -} - -HRESULT -CFileContext::Disable() -{ - MethodEntry("void"); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if ((m_Role == ROLE_UNDEFINED) || (m_Role == ROLE_PROXIMITY)) - { - // Only Pub/Sub handles can be disabled - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (!m_fEnabled) - { - // Already disabled - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (SUCCEEDED(hr)) - { - m_fEnabled = FALSE; - - CompleteRequest(HRESULT_FROM_NT(STATUS_CANCELLED), 0, true); - - // Purge all already received payloads - while (!IsListEmpty(&m_SubscribedMessageQueue)) - { - delete CMyPayload::FromListEntry(RemoveHeadList(&m_SubscribedMessageQueue)); - } - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnHR(hr); -} - -HRESULT -CFileContext::Enable() -{ - MethodEntry("void"); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if ((m_Role == ROLE_UNDEFINED) || (m_Role == ROLE_PROXIMITY)) - { - // Only Pub/Sub handles can be enabled - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (m_fEnabled) - { - // Already enabled - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (SUCCEEDED(hr)) - { - m_fEnabled = TRUE; - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnHR(hr); -} - -HRESULT -CFileContext::SetType(_In_ PCWSTR pszType) -{ - MethodEntry("pszType = '%S'", pszType); - - HRESULT hr = S_OK; - WUDF_SAMPLE_DRIVER_ASSERT(m_pszType == NULL); - - SIZE_T cchStr = wcslen(pszType) + 1; - if ((cchStr > MinCchType) && (cchStr < MaxCchType)) - { - m_pszType = new WCHAR[cchStr]; - if (m_pszType != NULL) - { - hr = StringCchCopy(m_pszType, cchStr, pszType); - } - else - { - hr = E_OUTOFMEMORY; - } - } - else - { - hr = E_INVALIDARG; - } - - MethodReturnHR(hr); -} - -#define STATUS_BUFFER_TOO_SMALL 0xC0000023L -#define STATUS_BUFFER_OVERFLOW 0x80000005L - - -bool -CFileContext::CompleteOneGetNextSubscribedMessage( - _In_ DWORD cbPayload, - _In_reads_bytes_opt_(cbPayload) PBYTE pbPayload - ) -/* - * m_RoleLock must already be acquired - */ -{ - MethodEntry("cbPayload = 0x%d", - (DWORD)cbPayload); - - WUDF_SAMPLE_DRIVER_ASSERT(m_pWdfRequest != NULL); - - bool fDelivered = false; - IWDFMemory* pWdfOutputMemory; - m_pWdfRequest->GetOutputMemory(&pWdfOutputMemory); - if (pWdfOutputMemory != NULL) - { - SIZE_T cbOutputBuffer = 0; - // Set the first 4 bytes as the size of the payload as a hint for future - // subscriptions. - HRESULT hr = pWdfOutputMemory->CopyFromBuffer(0, &cbPayload, 4); - if (SUCCEEDED(hr)) - { - cbOutputBuffer = 4; - if (pbPayload != NULL) - { - if (pWdfOutputMemory->GetSize() < (cbPayload + 4)) - { - // We are unable to copy the payload into the output memory, - // Returning this signals to the client to send a bigger buffer - hr = HRESULT_FROM_NT(STATUS_BUFFER_OVERFLOW); - } - else - { - hr = pWdfOutputMemory->CopyFromBuffer(4, pbPayload, cbPayload); - } - } - - if (SUCCEEDED(hr)) - { - fDelivered = true; - cbOutputBuffer += cbPayload; - if (m_dwQueueSize > 0) - { - m_dwQueueSize--; - } - } - } - pWdfOutputMemory->Release(); - - if (!CompleteRequest(hr, cbOutputBuffer, true)) - { - fDelivered = false; - } - } - - MethodReturnBool(fDelivered); -} - -HRESULT -CFileContext::GetNextSubscribedMessage(_In_ IRequestCallbackCancel* pCallbackCancel, _In_ IWDFIoRequest* pWdfRequest) -{ - MethodEntry("..."); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if (m_pWdfRequest != NULL) - { - // Only one pended request at a time allowed - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (!m_fEnabled) - { - // The handle is disabled - hr = HRESULT_FROM_NT(HRESULT_FROM_NT(STATUS_CANCELLED)); - } - - if (SUCCEEDED(hr)) - { - IWDFMemory* pWdfInputMemory; - pWdfRequest->GetInputMemory(&pWdfInputMemory); - SIZE_T cbInput; - if (pWdfInputMemory->GetDataBuffer(&cbInput) == NULL) - { - if (m_Role == ROLE_SUBSCRIPTION) - { - m_pWdfRequest = pWdfRequest; - m_pWdfRequest->MarkCancelable(pCallbackCancel); // MarkCancelable can run the OnCancel routine in this thread - - if ((m_pWdfRequest != NULL) && !IsListEmpty(&m_SubscribedMessageQueue)) - { - CMyPayload* pMyPayload = - CMyPayload::FromListEntry(m_SubscribedMessageQueue.Flink); - - if (CompleteOneGetNextSubscribedMessage(pMyPayload->GetSize(), - pMyPayload->GetPayload())) - { - RemoveHeadList(&m_SubscribedMessageQueue); - delete pMyPayload; - } - } - } - else if (m_Role == ROLE_ARRIVEDSUBSCRIPTION) - { - m_pWdfRequest = pWdfRequest; - m_pWdfRequest->MarkCancelable(pCallbackCancel); // MarkCancelable can run the OnCancel routine in this thread - if (m_pWdfRequest != NULL) - { - CompleteOneArrivalEvent(); - } - } - else if (m_Role == ROLE_DEPARTEDSUBSCRIPTION) - { - m_pWdfRequest = pWdfRequest; - m_pWdfRequest->MarkCancelable(pCallbackCancel); // MarkCancelable can run the OnCancel routine in this thread - if (m_pWdfRequest != NULL) - { - CompleteOneRemovalEvent(); - } - } - else - { - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - } - else - { - hr = E_INVALIDARG; - } - pWdfInputMemory->Release(); - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnHR(hr); -} - -HRESULT -CFileContext::SetPayload(_In_ IWDFIoRequest* pWdfRequest) -{ - MethodEntry("..."); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if ((m_Role != ROLE_PUBLICATION) || (m_MyPayload.GetPayload() != NULL)) - { - // SetPayload can only be called once per handle - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (SUCCEEDED(hr)) - { - IWDFMemory* pWdfOutputMemory; - pWdfRequest->GetOutputMemory(&pWdfOutputMemory); - SIZE_T cbOutput; - if (pWdfOutputMemory->GetDataBuffer(&cbOutput) == NULL) - { - IWDFMemory* pWdfMemory; - pWdfRequest->GetInputMemory(&pWdfMemory); - if (pWdfMemory != NULL) - { - SIZE_T cbPayload = pWdfMemory->GetSize(); - if ((cbPayload > 0) && (cbPayload <= MaxCbPayload)) - { - hr = m_MyPayload.Initialize((DWORD)cbPayload, (PBYTE)pWdfMemory->GetDataBuffer(NULL)); - } - else - { - hr = HRESULT_FROM_NT(STATUS_INVALID_BUFFER_SIZE); - } - - pWdfMemory->Release(); - } - else - { - hr = E_INVALIDARG; - } - pWdfOutputMemory->Release(); - } - else - { - hr = E_INVALIDARG; - } - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnHR(hr); -} - -HRESULT -CFileContext::GetNextTransmittedMessage(_In_ IRequestCallbackCancel* pCallbackCancel, _In_ IWDFIoRequest* pWdfRequest) -{ - MethodEntry("..."); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if ((m_Role != ROLE_PUBLICATION) || (m_pWdfRequest != NULL)) - { - // Only one pended request at a time allowed - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - - if (!m_fEnabled) - { - // The handle is disabled - hr = HRESULT_FROM_NT(HRESULT_FROM_NT(STATUS_CANCELLED)); - } - - if (SUCCEEDED(hr)) - { - IWDFMemory* pWdfInputMemory; - pWdfRequest->GetInputMemory(&pWdfInputMemory); - SIZE_T cbInput; - if (pWdfInputMemory->GetDataBuffer(&cbInput) == NULL) - { - IWDFMemory* pWdfOutputMemory; - pWdfRequest->GetOutputMemory(&pWdfOutputMemory); - SIZE_T cbOutput; - if (pWdfOutputMemory->GetDataBuffer(&cbOutput) == NULL) - { - m_pWdfRequest = pWdfRequest; - - if (m_cCompleteReady > 0) - { - if (CompleteRequest(S_OK, 0, false)) - { - m_cCompleteReady--; - } - } - } - else - { - hr = E_INVALIDARG; - } - pWdfOutputMemory->Release(); - } - else - { - hr = E_INVALIDARG; - } - pWdfInputMemory->Release(); - } - - if (SUCCEEDED(hr) && (m_pWdfRequest != NULL)) - { - m_pWdfRequest->MarkCancelable(pCallbackCancel); - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnHR(hr); -} - -HRESULT -CFileContext::BeginProximity( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IConnectionCallback* pCallback - ) -{ - MethodEntry("..."); - - EnterCriticalSection(&m_RoleLock); - - HRESULT hr = S_OK; - if (m_Role != ROLE_UNDEFINED) - { - // BeginProximity can only be called once per handle - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - } - else - { - m_Role = ROLE_PROXIMITY; - } - - LeaveCriticalSection(&m_RoleLock); - - if (SUCCEEDED(hr)) - { - IWDFMemory* pWdfMemory; - pWdfRequest->GetInputMemory(&pWdfMemory); - if (pWdfMemory != NULL) - { - if (pWdfMemory->GetSize() == sizeof(BEGIN_PROXIMITY_ARGS)) - { - hr = CConnection::Create(pCallback, &m_pConnection); - if (SUCCEEDED(hr)) - { - BEGIN_PROXIMITY_ARGS* pArgs = - (BEGIN_PROXIMITY_ARGS*)pWdfMemory->GetDataBuffer(NULL); - hr = m_pConnection->InitializeAsClient(pArgs); - } - } - else - { - hr = E_INVALIDARG; - } - - pWdfMemory->Release(); - } - else - { - hr = E_INVALIDARG; - } - } - - - if (FAILED(hr)) - { - m_pConnection = NULL; - } - - MethodReturnHR(hr); -} - -VOID -CFileContext::HandleArrivalEvent() -{ - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_ARRIVEDSUBSCRIPTION); - - EnterCriticalSection(&m_RoleLock); - - if (m_fEnabled) - { - m_cCompleteReady++; - CompleteOneArrivalEvent(); - } - - LeaveCriticalSection(&m_RoleLock); -} - -VOID -CFileContext::HandleRemovalEvent() -{ - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_DEPARTEDSUBSCRIPTION); - - EnterCriticalSection(&m_RoleLock); - - if (m_fEnabled) - { - m_cCompleteReady++; - CompleteOneRemovalEvent(); - } - - LeaveCriticalSection(&m_RoleLock); -} - -VOID -CFileContext::CompleteOneArrivalEvent() -{ - MethodEntry("void"); - - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_ARRIVEDSUBSCRIPTION); - - EnterCriticalSection(&m_RoleLock); - - if (m_cCompleteReady > 0) - { - if (m_pWdfRequest != NULL) - { - // Arrival payload should either be a DWORD = 1 or 0 - // 1 == Device capable of bi-directional communication - // 0 == Device is a dumb tag - DWORD ArrivalFlags = 0x1; - if (CompleteOneGetNextSubscribedMessage(sizeof(ArrivalFlags), (PBYTE)&ArrivalFlags)) - { - m_cCompleteReady--; - } - } - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnVoid(); -} - -VOID -CFileContext::CompleteOneRemovalEvent() -{ - MethodEntry("void"); - - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_DEPARTEDSUBSCRIPTION); - - EnterCriticalSection(&m_RoleLock); - - if (m_cCompleteReady > 0) - { - if (m_pWdfRequest != NULL) - { - // Removal payload should be a single zeroed DWORD - DWORD RemovalFlags = 0x0; - if (CompleteOneGetNextSubscribedMessage(sizeof(RemovalFlags), (PBYTE)&RemovalFlags)) - { - m_cCompleteReady--; - } - } - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnVoid(); -} - -void -CFileContext::HandleReceivedPublication( - _In_ PCWSTR pszType, - _In_ DWORD cbPayload, - _In_reads_bytes_(cbPayload) PBYTE pbPayload - ) -{ - MethodEntry("..."); - - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_SUBSCRIPTION); - - EnterCriticalSection(&m_RoleLock); - - if (m_fEnabled) - { - bool fSubscriptionMatches = false; - BYTE* pbNewPayload = NULL; - - if ((CompareStringOrdinal(m_pszType, -1, WINDOWSMIME_PROTOCOL, -1, FALSE) == CSTR_EQUAL) && - (wcslen(pszType) > WINDOWSMIME_PROTOCOL_CHARS) && - (CompareStringOrdinal(pszType, WINDOWSMIME_PROTOCOL_CHARS, - WINDOWSMIME_PROTOCOL, -1, FALSE) == CSTR_EQUAL)) - { - // If this is a WindowsMime message, and the subscription is for the general WINDOWSMIME_PROTOCOL type, - // the Mime type needs to be added to the message payload. - CHAR szMimeType[MaxCchMimeType + 1] = {}; - // Copy the mime type and convert from wide to multibyte chars - if (SUCCEEDED(StringCchPrintfA(szMimeType, ARRAYSIZE(szMimeType), "%S", pszType + WINDOWSMIME_PROTOCOL_CHARS + 1))) - { - pbNewPayload = new BYTE[cbPayload + MaxCchMimeType]; - if (pbNewPayload != NULL) - { - TraceInfo("Received Mime message of type = '%s'", szMimeType); - CopyMemory(pbNewPayload, szMimeType, MaxCchMimeType); - CopyMemory(pbNewPayload + MaxCchMimeType, pbPayload, cbPayload); - cbPayload += MaxCchMimeType; - pbPayload = pbNewPayload; - - fSubscriptionMatches = true; - } - } - } - else if (CompareStringOrdinal(pszType, -1, m_pszType, -1, FALSE) == CSTR_EQUAL) - { - fSubscriptionMatches = true; - } - - if (fSubscriptionMatches) - { - bool fDelivered = false; - - if (m_pWdfRequest != NULL) - { - fDelivered = CompleteOneGetNextSubscribedMessage(cbPayload, pbPayload); - } - - if ((!fDelivered) && (m_dwQueueSize < MAX_MESSAGE_QUEUE_SIZE)) - { - // Add message to the client delivery queue - - CMyPayload* pMyPayload = new CMyPayload(); - if (pMyPayload) - { - if (SUCCEEDED(pMyPayload->Initialize(cbPayload, pbPayload))) - { - InsertTailList(&m_SubscribedMessageQueue, pMyPayload->GetListEntry()); - m_dwQueueSize++; - } - else - { - delete pMyPayload; - } - } - } - } - - delete [] pbNewPayload; - } - else - { - TraceErrorHR(HRESULT_FROM_NT(STATUS_CANCELLED), "Subscription Disabled!"); - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnVoid(); -} - -void -CFileContext::HandleMessageTransmitted() -{ - MethodEntry("void"); - - WUDF_SAMPLE_DRIVER_ASSERT(m_Role == ROLE_PUBLICATION); - - EnterCriticalSection(&m_RoleLock); - - if (!CompleteRequest(S_OK, 0, true)) - { - m_cCompleteReady++; - } - - LeaveCriticalSection(&m_RoleLock); - - MethodReturnVoid(); -} - -void -CFileContext::OnCancel() -{ - EnterCriticalSection(&m_RoleLock); - - CompleteRequest(E_ABORT, 0, false); - - LeaveCriticalSection(&m_RoleLock); -} - -bool -CFileContext::CompleteRequest(_In_ HRESULT hr, _In_ SIZE_T cbSize, _In_ bool fIsCancelable) -/* - * m_RoleLock must already be acquired - */ -{ - MethodEntry("hr = %!HRESULT!, cbSize = %d, fIsCancelable = %!bool!", - hr, (DWORD)cbSize, fIsCancelable); - - bool fCompleted = false; - if (m_pWdfRequest != NULL) - { - bool fCompleteRequest = true; - if (fIsCancelable) - { - if (m_pWdfRequest->UnmarkCancelable() == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)) - { - fCompleteRequest = false; - } - } - - if (fCompleteRequest) - { - m_pWdfRequest->CompleteWithInformation(hr, cbSize); - m_pWdfRequest = NULL; - fCompleted = true; - } - } - - MethodReturnBool(fCompleted); -} diff --git a/nfp/net/driver/FileContext.h b/nfp/net/driver/FileContext.h deleted file mode 100644 index 0247636e7..000000000 --- a/nfp/net/driver/FileContext.h +++ /dev/null @@ -1,340 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - filecontext.h - -Abstract: - - This header file defines the structure type for context associated with the file object - -Environment: - - user mode only - -Revision History: - ---*/ -#pragma once - -class CMyPayload -{ -public: - CMyPayload() - { - m_pbPayload = NULL; - m_cbPayload = 0; - - InitializeListHead(&m_ListEntry); - } - ~CMyPayload() - { - if (m_pbPayload != NULL) - { - delete [] m_pbPayload; - m_pbPayload = NULL; - } - } - - STDMETHOD(Initialize)( - _In_ DWORD cbPayload, - _In_reads_bytes_(cbPayload) PBYTE pbPayload - ) - { - HRESULT hr = S_OK; - m_pbPayload = new BYTE[cbPayload]; - if (m_pbPayload != NULL) - { - m_cbPayload = cbPayload; - CopyMemory(m_pbPayload, pbPayload, cbPayload); - } - else - { - hr = E_OUTOFMEMORY; - } - - return hr; - } - - PBYTE GetPayload() - { - return m_pbPayload; - } - DWORD GetSize() - { - return m_cbPayload; - } - - PLIST_ENTRY GetListEntry() - { - return &m_ListEntry; - } - static CMyPayload* FromListEntry(PLIST_ENTRY pEntry) - { - return (CMyPayload*) CONTAINING_RECORD(pEntry, CMyPayload, m_ListEntry); - } - -private: - PBYTE m_pbPayload; - DWORD m_cbPayload; - - LIST_ENTRY m_ListEntry; -}; - -/* - * Use this to refactor to only keep one copy of received messages - * -class CMyPayloadItem -{ -public: - CMyPayloadItem(_In_ CMyPayload* pPayload) - { - m_spPayload = pPayload; - InitializeListHead(&m_ListEntry); - } - ~CMyPayloadItem() - { - } - - PBYTE GetPayload() - { - return m_spPayload->GetPayload(); - } - DWORD GetSize() - { - return m_spPayload->GetSize(); - } - - PLIST_ENTRY GetListEntry() - { - return &m_ListEntry; - } - static CMyPayloadItem* FromListEntry(PLIST_ENTRY pEntry) - { - return (CMyPayloadItem*) CONTAINING_RECORD(pEntry, CMyPayloadItem, m_ListEntry); - } - -private: - CComPtr m_spPayload; - - LIST_ENTRY m_ListEntry; -}; -*/ - -class CFileContext -{ -public: - - CFileContext() : - m_Role(ROLE_UNDEFINED), - m_pszType(NULL), - m_fEnabled(TRUE), - m_dwQueueSize(0), - m_cCompleteReady(0), - m_pConnection(NULL), - m_pWdfRequest(NULL) - { - InitializeListHead(&m_SubscribedMessageQueue); - - InitializeListHead(&m_ListEntry); - - InitializeCriticalSection(&m_RoleLock); - } - - ~CFileContext(); - - HRESULT - Disable(); - - HRESULT - Enable(); - - HRESULT - SetType(_In_ PCWSTR pszType); - - HRESULT - GetNextSubscribedMessage(_In_ IRequestCallbackCancel* pCallbackCancel, _In_ IWDFIoRequest* pWdfRequest); - - HRESULT - SetPayload(_In_ IWDFIoRequest* pWdfRequest); - - HRESULT - GetNextTransmittedMessage(_In_ IRequestCallbackCancel* pCallbackCancel, _In_ IWDFIoRequest* pWdfRequest); - - HRESULT - BeginProximity( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IConnectionCallback* pCallback - ); - - VOID - HandleArrivalEvent(); - VOID - HandleRemovalEvent(); - - void - HandleReceivedPublication( - _In_ PCWSTR pszType, - _In_ DWORD cbPayload, - _In_reads_bytes_(cbPayload) PBYTE pbPayload - ); - - void - HandleMessageTransmitted(); - - void - OnCancel(); - - void - SetRoleSubcription() - { - m_Role = ROLE_SUBSCRIPTION; - } - - void - SetRolePublication() - { - m_Role = ROLE_PUBLICATION; - } - - BOOL - SetRoleArrivedSubcription() - { - if (m_Role == ROLE_SUBSCRIPTION) - { - m_Role = ROLE_ARRIVEDSUBSCRIPTION; - return TRUE; - } - return FALSE; - } - - BOOL - SetRoleDepartedSubcription() - { - if (m_Role == ROLE_SUBSCRIPTION) - { - m_Role = ROLE_DEPARTEDSUBSCRIPTION; - return TRUE; - } - return FALSE; - } - - BOOL - IsNormalSubscription() - { - return (m_Role == ROLE_SUBSCRIPTION); - } - BOOL - IsArrivedSubscription() - { - return (m_Role == ROLE_ARRIVEDSUBSCRIPTION); - } - BOOL - IsDepartedSubscription() - { - return (m_Role == ROLE_DEPARTEDSUBSCRIPTION); - } - BOOL - IsSubscription() - { - return (m_Role == ROLE_SUBSCRIPTION); - } - BOOL - IsPublication() - { - return (m_Role == ROLE_PUBLICATION); - } - - PCWSTR - GetType() - { - return m_pszType; - } - - DWORD - GetSize() - { - return m_MyPayload.GetSize(); - } - - PBYTE - GetPayload() - { - return m_MyPayload.GetPayload(); - } - - BOOL - IsEnabled() - { - return m_fEnabled; - } - - PLIST_ENTRY GetListEntry() - { - return &m_ListEntry; - } - static CFileContext* FromListEntry(PLIST_ENTRY pEntry) - { - return (CFileContext*) CONTAINING_RECORD(pEntry, CFileContext, m_ListEntry); - } - -private: - - VOID - CompleteOneArrivalEvent(); - VOID - CompleteOneRemovalEvent(); - - bool - CompleteOneGetNextSubscribedMessage( - _In_ DWORD cbPayload, - _In_reads_bytes_opt_(cbPayload) PBYTE pbPayload - ); - - bool - CompleteRequest( - _In_ HRESULT hr, - _In_ SIZE_T cbSize, - _In_ bool fIsCancelable - ); - -private: - - enum ROLE - { - ROLE_UNDEFINED, - ROLE_SUBSCRIPTION, - ROLE_ARRIVEDSUBSCRIPTION, - ROLE_DEPARTEDSUBSCRIPTION, - ROLE_PUBLICATION, - ROLE_PROXIMITY - }; - - ROLE m_Role; - - PWSTR m_pszType; - - BOOL m_fEnabled; - - DWORD m_dwQueueSize; - - // Queue of received messages - LIST_ENTRY m_SubscribedMessageQueue; // Unique to ROLE_SUBSCRIPTION - - CMyPayload m_MyPayload; // Unique to ROLE_PUBLICATION - SIZE_T m_cCompleteReady; // Unique to ROLE_PUBLICATION, ROLE_ARRIVEDSUBSCRIPTION, and ROLE_DEPARTEDSUBSCRIPTION - - CConnection* m_pConnection; // Unique to ROLE_PROXIMITY - - // Pended "Get Next" Request. - IWDFIoRequest* m_pWdfRequest; - - // The Fx File object this CFileObject is a companion to - IWDFFile* m_pWdfFile; - - CRITICAL_SECTION m_RoleLock; - - LIST_ENTRY m_ListEntry; -}; diff --git a/nfp/net/driver/NetNfpProvider.vcxproj b/nfp/net/driver/NetNfpProvider.vcxproj deleted file mode 100644 index f1a034aae..000000000 --- a/nfp/net/driver/NetNfpProvider.vcxproj +++ /dev/null @@ -1,276 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC} - $(MSBuildProjectName) - 1 - Debug - Win32 - {0748320F-1B24-4B57-A2C3-9BF984CB3365} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - WppDefs.h - - - $(InfArch) - true - true - .\$(IntDir)\NetNfpProvider.inf - - - true - true - WppDefs.h - - - - NetNfpProvider - Dynamic - - - NetNfpProvider - Dynamic - - - NetNfpProvider - Dynamic - - - NetNfpProvider - Dynamic - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib;$(SDK_LIB_PATH)\mswsock.lib - exports.def - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib;$(SDK_LIB_PATH)\mswsock.lib - exports.def - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib;$(SDK_LIB_PATH)\mswsock.lib - exports.def - - - sha256 - - - - - true - Level4 - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\user32.lib;$(SDK_LIB_PATH)\ole32.lib;$(SDK_LIB_PATH)\oleaut32.lib;$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ws2_32.lib;$(SDK_LIB_PATH)\mswsock.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/nfp/net/driver/NetNfpProvider.vcxproj.Filters b/nfp/net/driver/NetNfpProvider.vcxproj.Filters deleted file mode 100644 index d19c90677..000000000 --- a/nfp/net/driver/NetNfpProvider.vcxproj.Filters +++ /dev/null @@ -1,88 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {4D4354C7-DA31-4F68-A565-3887F77EDBA7} - - - h;hpp;hxx;hm;inl;inc;xsd - {A34DD649-9226-40E4-9E8B-A7208AA93216} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {4A95486B-95A9-4771-81FD-C76F8CA7FFDD} - - - inf;inv;inx;mof;mc; - {5D7D5FF7-7AC6-413F-9538-509E52CE4046} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Driver Files - - - - - Resource Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - \ No newline at end of file diff --git a/nfp/net/driver/Queue.cpp b/nfp/net/driver/Queue.cpp deleted file mode 100644 index 129a54398..000000000 --- a/nfp/net/driver/Queue.cpp +++ /dev/null @@ -1,824 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - user mode only - -Revision History: - ---*/ -#include "internal.h" - -#include "queue.tmh" - -CMyQueue::CMyQueue( - VOID - ) -{ - InitializeListHead(&m_SubsHead); - InitializeListHead(&m_ArrivalSubsHead); - InitializeListHead(&m_DepartureSubsHead); - InitializeListHead(&m_PubsHead); - InitializeListHead(&m_ConnectionHead); - - InitializeCriticalSection(&m_SubsLock); - InitializeCriticalSection(&m_PubsLock); - InitializeCriticalSection(&m_ConnectionLock); -} - -CMyQueue::~CMyQueue( - VOID - ) -{ - MethodEntry("void"); - - m_SocketListener.StopAccepting(); - - while (!IsListEmpty(&m_ConnectionHead)) - { - delete CConnection::FromListEntry(RemoveHeadList(&m_ConnectionHead)); - } - - DeleteCriticalSection(&m_SubsLock); - DeleteCriticalSection(&m_PubsLock); - DeleteCriticalSection(&m_ConnectionLock); -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ CMyDevice * Device - ) -/*++ - -Routine Description: - - Queue Initialize helper routine. - This routine will Create a default parallel queue associated with the Fx device object - and pass the IUnknown for this queue - -Aruments: - Device object pointer - -Return Value: - - S_OK if Initialize succeeds - ---*/ -{ - MethodEntry("..."); - - CComPtr fxQueue; - - HRESULT hr; - - // - // Create the I/O Queue object. - // - { - CComPtr pUnk; - - HRESULT hrQI = this->QueryInterface(__uuidof(IUnknown),(void**)&pUnk); - - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - hr = Device->GetFxDevice()->CreateIoQueue( - pUnk, - TRUE, - WdfIoQueueDispatchParallel, - TRUE, - FALSE, - &fxQueue - ); - } - - if (FAILED(hr)) - { - TraceErrorHR(hr, "Failed to initialize driver queue"); - } - - if (SUCCEEDED(hr)) - { - hr = m_SocketListener.Bind(); - if (FAILED(hr)) - { - TraceErrorHR(hr, "Failed to Bind"); - } - } - - if (SUCCEEDED(hr)) - { - hr = m_SocketListener.EnableAccepting(this); - if (FAILED(hr)) - { - TraceErrorHR(hr, "Failed to EnableAccepting"); - } - } - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - } - - MethodReturnHR(hr); -} - -HRESULT -CMyQueue::Configure( - VOID - ) -/*++ - -Routine Description: - - Queue configuration function . - It is called after queue object has been succesfully initialized. - -Aruments: - - NONE - - Return Value: - - S_OK if succeeds. - ---*/ -{ - MethodEntry("void"); - - HRESULT hr = S_OK; - - MethodReturnHR(hr); -} - - -STDMETHODIMP_(void) -CMyQueue::OnCreateFile( - _In_ IWDFIoQueue* /*pWdfQueue*/, - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFFile* pWdfFile - ) - -/*++ - -Routine Description: - - Create callback from the framework for this default parallel queue - - The create request will create a socket connection , create a file i/o target associated - with the socket handle for this connection and store in the file object context. - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - pWdfFile - WDF file object for this create - - Return Value: - - VOID - ---*/ -{ - MethodEntry("pWdfRequest = %p, pWdfFile = %p", - pWdfRequest, pWdfFile); - - HRESULT hr = S_OK; - - // - // Create file context for this file object - // - - CFileContext *pContext = new CFileContext(); - if (NULL == pContext) - { - hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); - TraceErrorHR(hr, "Could not create file context"); - } - - if (SUCCEEDED(hr)) - { - DWORD cchFileName = 0; - hr = pWdfFile->RetrieveFileName(NULL, &cchFileName); - if (SUCCEEDED(hr) && (cchFileName > 0) && (cchFileName <= MaxCchType)) - { - // Allocate a buffer big enough for the filename plus some extra to prevent - // overruns in the parsing below: The extra needs to be larger than the biggest - // *_CHARS value. The value 20 is overly big, but allows room to grow without - // hitting the OACR issue again. If the OACR issue is hit, just increase this - // to be larger than the biggest *_CHARS value used below in parsing. - DWORD cchFileNameBuffer = cchFileName + 20; - PWSTR pszFileNameBuffer = new WCHAR[cchFileNameBuffer]; - hr = (pszFileNameBuffer != NULL) ? S_OK : E_OUTOFMEMORY; - if (SUCCEEDED(hr)) - { - ZeroMemory(pszFileNameBuffer, cchFileNameBuffer * sizeof(WCHAR)); - - hr = pWdfFile->RetrieveFileName(pszFileNameBuffer, &cchFileName); - } - - if (SUCCEEDED(hr)) - { - PCWSTR pszFileName = pszFileNameBuffer; - if (pszFileNameBuffer[0] == L'\\') - { - // If it exists, remove the inital slash - pszFileName++; - cchFileName--; - } - - TraceInfo("cchFileName = %d, pszFileName = %S", cchFileName, pszFileName); - - PCWSTR pszProtocol = NULL; - if (CompareStringOrdinal(pszFileName, PUBS_NAMESPACE_CHARS, - PUBS_NAMESPACE, PUBS_NAMESPACE_CHARS, - TRUE) == CSTR_EQUAL) - { - pContext->SetRolePublication(); - pszProtocol = pszFileName + PUBS_NAMESPACE_CHARS; - } - else if (CompareStringOrdinal(pszFileName, SUBS_NAMESPACE_CHARS, - SUBS_NAMESPACE, SUBS_NAMESPACE_CHARS, - TRUE) == CSTR_EQUAL) - { - pContext->SetRoleSubcription(); - pszProtocol = pszFileName + SUBS_NAMESPACE_CHARS; - } - else - { - hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); - } - - if (SUCCEEDED(hr)) - { - if (CompareStringOrdinal(pszProtocol, WINDOWS_PROTOCOL_CHARS, - WINDOWS_PROTOCOL, WINDOWS_PROTOCOL_CHARS, - TRUE) == CSTR_EQUAL) - { - pContext->SetType(pszProtocol); - } - else if (CompareStringOrdinal(pszProtocol, -1, - WINDOWSURI_PROTOCOL, -1, - TRUE) == CSTR_EQUAL) - { - pContext->SetType(pszProtocol); - } - else if (CompareStringOrdinal(pszProtocol, WINDOWSMIME_PROTOCOL_CHARS, - WINDOWSMIME_PROTOCOL, WINDOWSMIME_PROTOCOL_CHARS, - TRUE) == CSTR_EQUAL) - { - pContext->SetType(pszProtocol); - } - else if (CompareStringOrdinal(pszProtocol, -1, DEVICE_ARRIVED, -1, - TRUE) == CSTR_EQUAL) - { - if (!pContext->SetRoleArrivedSubcription()) - { - hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); - } - } - else if (CompareStringOrdinal(pszProtocol, -1, DEVICE_DEPARTED, -1, - TRUE) == CSTR_EQUAL) - { - if (!pContext->SetRoleDepartedSubcription()) - { - hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); - } - } - else if (CompareStringOrdinal(pszProtocol, PAIRING_PROTOCOL_CHARS, - PAIRING_PROTOCOL, PAIRING_PROTOCOL_CHARS, - TRUE) == CSTR_EQUAL) - { - pContext->SetType(pszProtocol); - } - else if (CompareStringOrdinal(pszProtocol, NDEF_PROTOCOL_CHARS, - NDEF_PROTOCOL, NDEF_PROTOCOL_CHARS, - TRUE) == CSTR_EQUAL) - { - PCWSTR pszType = pszProtocol + NDEF_PROTOCOL_CHARS; - - if (CompareStringOrdinal(pszType, NDEF_EMPTY_TYPE_CHARS, - NDEF_EMPTY_TYPE, NDEF_EMPTY_TYPE_CHARS, - TRUE) != CSTR_EQUAL) - { - pContext->SetType(pszProtocol); - } - else - { - hr = HRESULT_FROM_NT(STATUS_INVALID_PARAMETER); - } - } - else - { - hr = HRESULT_FROM_NT(STATUS_OBJECT_PATH_NOT_FOUND); - } - } - } - - if (pszFileNameBuffer != NULL) - { - delete [] pszFileNameBuffer; - } - } - } - - if (SUCCEEDED(hr)) - { - hr = pWdfFile->AssignContext(NULL, (void*)pContext); - if (FAILED(hr)) - { - TraceErrorHR(hr, "Unable to Assign Context to this File Object"); - } - } - - if (SUCCEEDED(hr)) - { - EnterCriticalSection(&m_SubsLock); - - if (pContext->IsNormalSubscription()) - { - // Place this CFileContext into a list of Subscriptions - InsertHeadList(&m_SubsHead, pContext->GetListEntry()); - } - else if (pContext->IsArrivedSubscription()) - { - // Place this CFileContext into a list of arrival registrations - InsertHeadList(&m_ArrivalSubsHead, pContext->GetListEntry()); - } - else if (pContext->IsDepartedSubscription()) - { - // Place this CFileContext into a list of removal registrations - InsertHeadList(&m_DepartureSubsHead, pContext->GetListEntry()); - } - - LeaveCriticalSection(&m_SubsLock); - } - - if (FAILED(hr)) - { - if (pContext != NULL) - { - delete pContext; - pContext = NULL; - } - } - - pWdfRequest->Complete(hr); - - MethodReturnVoid(); -} - -STDMETHODIMP_(void) -CMyQueue::OnCloseFile( - _In_ IWDFFile* pWdfFileObject - ) -/*++ - - Routine Description: - - This method is called when an app closes the file handle to this device. - This will free the context memory associated with this file object, close - the connection object associated with this file object and delete the file - handle i/o target object associated with this file object. - - Arguments: - - pWdfFileObject - the framework file object for which close is handled. - - Return Value: - - None - ---*/ -{ - MethodEntry("..."); - - HRESULT hr = S_OK ; - CFileContext* pContext = NULL; - hr = pWdfFileObject->RetrieveContext((void**)&pContext); - if (SUCCEEDED(hr) && (pContext != NULL)) - { - CRITICAL_SECTION* pCritSec = NULL; - LIST_ENTRY* pHead = NULL; - - if (pContext->IsNormalSubscription()) - { - pCritSec = &m_SubsLock; - pHead = &m_SubsHead; - } - else if (pContext->IsArrivedSubscription()) - { - pCritSec = &m_SubsLock; - pHead = &m_ArrivalSubsHead; - } - else if (pContext->IsDepartedSubscription()) - { - pCritSec = &m_SubsLock; - pHead = &m_DepartureSubsHead; - } - else if (pContext->IsPublication()) - { - pCritSec = &m_PubsLock; - pHead = &m_PubsHead; - } - - if (pHead != NULL) - { - EnterCriticalSection(pCritSec); - - LIST_ENTRY* pFindEntry = pContext->GetListEntry(); - LIST_ENTRY* pEntry = pHead->Flink; - while (pEntry != pHead) - { - if (pEntry == pFindEntry) - { - RemoveEntryList(pEntry); - break; - } - - pEntry = pEntry->Flink; - } - - LeaveCriticalSection(pCritSec); - } - - delete pContext; - } - - MethodReturnVoid(); -} - -STDMETHODIMP_ (void) -CMyQueue::OnCancel( - _In_ IWDFIoRequest* pWdfRequest - ) -{ - MethodEntry("pWdfRequest = %p", - pWdfRequest); - - IWDFFile* pFxFile; - pWdfRequest->GetFileObject(&pFxFile); - if (pFxFile != NULL) - { - CFileContext* pFileContext; - HRESULT hr = pFxFile->RetrieveContext((void**)&pFileContext); - if (SUCCEEDED(hr)) - { - pFileContext->OnCancel(); - } - } - - MethodReturnVoid(); -} - -#define IOCTL_BEGIN_PROXIMITY CTL_CODE(FILE_DEVICE_UNKNOWN, 0x1000, METHOD_BUFFERED, FILE_ANY_ACCESS) - -STDMETHODIMP_ (void) -CMyQueue::OnDeviceIoControl( - _In_ IWDFIoQueue* /*pWdfQueue*/, - _In_ IWDFIoRequest* pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T /*InBufferSize*/, - _In_ SIZE_T /*OutBufferSize*/ - ) -{ - MethodEntry("pWdfRequest = %p, ControlCode = %d", - pWdfRequest, ControlCode); - - IWDFFile* pFxFile; - - pWdfRequest->GetFileObject(&pFxFile); - - bool fCompleteRequest = true; - - CFileContext *pFileContext; - HRESULT hr = pFxFile->RetrieveContext((void**)&pFileContext); - if (SUCCEEDED(hr)) - { - switch (ControlCode) - { - case IOCTL_NFP_GET_MAX_MESSAGE_BYTES: - { - IWDFMemory* pWdfOutputMemory; - pWdfRequest->GetOutputMemory(&pWdfOutputMemory); - if (pWdfOutputMemory != NULL) - { - SIZE_T cbOutputBuffer = 0; - // Set the first 4 bytes as the maximum message size of this device/driver - DWORD dwMaxCbPayload = MaxCbPayload; - hr = pWdfOutputMemory->CopyFromBuffer(0, &dwMaxCbPayload, 4); - if (SUCCEEDED(hr)) - { - cbOutputBuffer = 4; - } - pWdfOutputMemory->Release(); - - pWdfRequest->CompleteWithInformation(hr, cbOutputBuffer); - fCompleteRequest = false; - } - } - break; - - case IOCTL_NFP_GET_KILO_BYTES_PER_SECOND: - { - IWDFMemory* pWdfOutputMemory; - pWdfRequest->GetOutputMemory(&pWdfOutputMemory); - if (pWdfOutputMemory != NULL) - { - SIZE_T cbOutputBuffer = 0; - // Set the first 4 bytes as transfer speed of this device/driver - DWORD dwKilobytesPerSecond = KilobytesPerSecond; - hr = pWdfOutputMemory->CopyFromBuffer(0, &dwKilobytesPerSecond, 4); - if (SUCCEEDED(hr)) - { - cbOutputBuffer = 4; - } - pWdfOutputMemory->Release(); - - pWdfRequest->CompleteWithInformation(hr, cbOutputBuffer); - fCompleteRequest = false; - } - } - break; - - case IOCTL_NFP_DISABLE: - hr = pFileContext->Disable(); - break; - - case IOCTL_NFP_ENABLE: - hr = pFileContext->Enable(); - break; - - case IOCTL_NFP_SET_PAYLOAD: - hr = pFileContext->SetPayload(pWdfRequest); - if (SUCCEEDED(hr)) - { - MESSAGE* pMessage = new MESSAGE(); - hr = (pMessage != NULL) ? S_OK : E_OUTOFMEMORY; - if (SUCCEEDED(hr)) - { - pMessage->Initialize(pFileContext->GetType(), pFileContext->GetSize(), pFileContext->GetPayload()); - - EnterCriticalSection(&m_ConnectionLock); - - for (LIST_ENTRY* pEntry = m_ConnectionHead.Flink; - pEntry != &m_ConnectionHead; - pEntry = pEntry->Flink) - { - CConnection* pConnection = CConnection::FromListEntry(pEntry); - if (SUCCEEDED(pConnection->TransmitMessage(pMessage))) - { - pFileContext->HandleMessageTransmitted(); - } - } - - LeaveCriticalSection(&m_ConnectionLock); - - // Place this CFileContext into a list of published messages - EnterCriticalSection(&m_PubsLock); - InsertHeadList(&m_PubsHead, pFileContext->GetListEntry()); - LeaveCriticalSection(&m_PubsLock); - - delete pMessage; - } - } - break; - - case IOCTL_BEGIN_PROXIMITY: - hr = pFileContext->BeginProximity(pWdfRequest, this); - break; - - case IOCTL_NFP_GET_NEXT_SUBSCRIBED_MESSAGE: - hr = pFileContext->GetNextSubscribedMessage(this, pWdfRequest); - if (SUCCEEDED(hr)) - { - fCompleteRequest = false; - } - break; - - case IOCTL_NFP_GET_NEXT_TRANSMITTED_MESSAGE: - hr = pFileContext->GetNextTransmittedMessage(this, pWdfRequest); - if (SUCCEEDED(hr)) - { - fCompleteRequest = false; - } - break; - - default: - hr = HRESULT_FROM_NT(STATUS_INVALID_DEVICE_STATE); - break; - } - } - - if (fCompleteRequest) - { - TraceInfo("Completing Request: %!HRESULT!", hr); - pWdfRequest->Complete(hr); - } - - MethodReturnVoid(); -} - -void -CMyQueue::ValidateAccept(_In_ SOCKET Socket, _In_ GUID* pMagicPacket) -{ - MethodEntry("..."); - - CConnection* pConnection; - HRESULT hr = CConnection::Create(this, &pConnection); - if (SUCCEEDED(hr)) - { - // Mark it as an Inbound connection, so we know to delete it when - // it's removed from the list - pConnection->SetInboundConnection(); - - pConnection->ValidateAccept(Socket, pMagicPacket); - Socket = INVALID_SOCKET; - } - - if (Socket != INVALID_SOCKET) - { - closesocket(Socket); - } - - MethodReturnVoid(); -} - -void -CMyQueue::HandleReceivedMessage(_In_ MESSAGE* pMessage) -{ - MethodEntry("pMessage->m_szType = '%S'", - pMessage->m_szType); - - if ((pMessage->m_cbPayload > 0) && (pMessage->m_cbPayload <= MaxCbPayload)) - { - EnterCriticalSection(&m_SubsLock); - - LIST_ENTRY* pEntry = m_SubsHead.Flink; - while (pEntry != &m_SubsHead) - { - CFileContext* pSub = CFileContext::FromListEntry(pEntry); - - pSub->HandleReceivedPublication(pMessage->m_szType, - pMessage->m_cbPayload, - pMessage->m_Payload); - - pEntry = pEntry->Flink; - } - - LeaveCriticalSection(&m_SubsLock); - } - - MethodReturnVoid(); -} - -void -CMyQueue::ConnectionEstablished(_In_ CConnection* pConnection) -{ - MethodEntry("..."); - - EnterCriticalSection(&m_ConnectionLock); - BOOL fFirstConnection = IsListEmpty(&m_ConnectionHead); - InsertHeadList(&m_ConnectionHead, pConnection->GetListEntry()); - LeaveCriticalSection(&m_ConnectionLock); - - if (fFirstConnection) - { - AddArrivalEvent(); - } - - MESSAGE* pMessage = new MESSAGE(); - if (pMessage != NULL) - { - EnterCriticalSection(&m_PubsLock); - - LIST_ENTRY* pEntry = m_PubsHead.Flink; - while (pEntry != &m_PubsHead) - { - CFileContext* pPub = CFileContext::FromListEntry(pEntry); - if (pPub->IsEnabled()) - { - pMessage->Initialize(pPub->GetType(), pPub->GetSize(), pPub->GetPayload()); - if (SUCCEEDED(pConnection->TransmitMessage(pMessage))) - { - pPub->HandleMessageTransmitted(); - } - } - pEntry = pEntry->Flink; - } - - LeaveCriticalSection(&m_PubsLock); - delete pMessage; - } - - MethodReturnVoid(); -} - -BOOL -CMyQueue::ConnectionTerminated(_In_ CConnection* pConnection) -{ - MethodEntry("pConnection = 0x%p", - pConnection); - - LIST_ENTRY* pRemoveListEntry = pConnection->GetListEntry(); - - EnterCriticalSection(&m_ConnectionLock); - LIST_ENTRY* pEntry = m_ConnectionHead.Flink; - while (pEntry != &m_ConnectionHead) - { - if (pEntry == pRemoveListEntry) - { - RemoveEntryList(pEntry); - break; - } - pEntry = pEntry->Flink; - } - BOOL fNoMoreConnections = IsListEmpty(&m_ConnectionHead); - - LeaveCriticalSection(&m_ConnectionLock); - - BOOL fConnectionDeleted = FALSE; - if (pConnection->IsInboundConnection()) - { - delete pConnection; - fConnectionDeleted = TRUE; - } - - if (fNoMoreConnections) - { - AddRemovalEvent(); - } - - MethodReturnBool(fConnectionDeleted); -} - -void -CMyQueue::AddArrivalEvent() -{ - MethodEntry("void"); - - EnterCriticalSection(&m_SubsLock); - - for (LIST_ENTRY* pEntry = m_ArrivalSubsHead.Flink; - pEntry != &m_ArrivalSubsHead; - pEntry = pEntry->Flink) - { - CFileContext::FromListEntry(pEntry)->HandleArrivalEvent(); - } - - LeaveCriticalSection(&m_SubsLock); - - MethodReturnVoid(); -} - -void -CMyQueue::AddRemovalEvent() -{ - MethodEntry("void"); - - EnterCriticalSection(&m_SubsLock); - - for (LIST_ENTRY* pEntry = m_DepartureSubsHead.Flink; - pEntry != &m_DepartureSubsHead; - pEntry = pEntry->Flink) - { - CFileContext::FromListEntry(pEntry)->HandleRemovalEvent(); - } - - LeaveCriticalSection(&m_SubsLock); - - MethodReturnVoid(); -} - -STDMETHODIMP_(void) -CMyQueue::OnCleanup( - _In_ IWDFObject* /*pWdfObject*/ - ) -{ - MethodEntry("..."); - - // - // CMyQueue has a reference to framework device object via m_Queue. - // Framework queue object has a reference to CMyQueue object via the callbacks. - // This leads to circular reference and both the objects can't be destroyed until this circular reference is broken. - // To break the circular reference we release the reference to the framework queue object here in OnCleanup. - // - - m_FxQueue = NULL; - - MethodReturnVoid(); -} diff --git a/nfp/net/driver/Queue.h b/nfp/net/driver/Queue.h deleted file mode 100644 index 55b2ff39d..000000000 --- a/nfp/net/driver/Queue.h +++ /dev/null @@ -1,175 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - user mode only - -Revision History: - ---*/ - -#pragma once - -#include "device.h" -#include "Connection.h" - -static const int KilobytesPerSecond = 20; - -static const int MaxCbPayload = 10240; -static const int MaxCchType = 507; // maximum message type length is 5 for "?ubs\\", 250 for protocol + 250 for subtype + 1 each for dot "." and NULL terminator. -static const int MaxCchTypeNetwork = 502; // maximum message type length over the network is 250 for protocol + 250 for subtype + 1 each for dot "." and NULL terminator. -static const int MinCchType = 2; -static const int MaxCchMimeType = 256; - -#define WINDOWS_PROTOCOL L"Windows." -#define WINDOWS_PROTOCOL_CHARS 8 - -#define WINDOWSURI_PROTOCOL L"WindowsUri" - -#define WINDOWSMIME_PROTOCOL L"WindowsMime" -#define WINDOWSMIME_PROTOCOL_CHARS 11 - -#define PUBS_NAMESPACE L"Pubs\\" -#define PUBS_NAMESPACE_CHARS 5 - -#define SUBS_NAMESPACE L"Subs\\" -#define SUBS_NAMESPACE_CHARS 5 - -#define DEVICE_ARRIVED L"DeviceArrived" -#define DEVICE_DEPARTED L"DeviceDeparted" - -#define PAIRING_PROTOCOL L"Pairing:" -#define PAIRING_PROTOCOL_CHARS 8 - -#define NDEF_PROTOCOL L"NDEF" -#define NDEF_PROTOCOL_CHARS 4 - -#define NDEF_EMPTY_TYPE L"Empty" -#define NDEF_EMPTY_TYPE_CHARS 5 - -struct MESSAGE -{ - MESSAGE() : - m_cbPayload(0) - { - ZeroMemory(m_szType, sizeof(m_szType)); - ZeroMemory(m_Payload, sizeof(m_Payload)); - } - - void Initialize( - _In_ PCWSTR szType, - _In_ DWORD cbPayload, - _In_reads_bytes_(cbPayload) PBYTE pbPayload - ) - { - ZeroMemory(m_szType, sizeof(m_szType)); - ZeroMemory(m_Payload, sizeof(m_Payload)); - - m_cbPayload = cbPayload; - StringCchCopy(m_szType, ARRAY_SIZE(m_szType), szType); - CopyMemory(m_Payload, pbPayload, cbPayload); - } - - wchar_t m_szType[MaxCchTypeNetwork]; - DWORD m_cbPayload; - BYTE m_Payload[MaxCbPayload]; -}; - - -// -// Queue Callback Object. -// - -class ATL_NO_VTABLE CMyQueue : - public CComObjectRootEx, - public IQueueCallbackCreate, - public IQueueCallbackDeviceIoControl, - public IRequestCallbackCancel, - public IObjectCleanup, - public IValidateAccept, - public IConnectionCallback -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyQueue) - -BEGIN_COM_MAP(CMyQueue) - COM_INTERFACE_ENTRY(IQueueCallbackCreate) - COM_INTERFACE_ENTRY(IQueueCallbackDeviceIoControl) - COM_INTERFACE_ENTRY(IRequestCallbackCancel) - COM_INTERFACE_ENTRY(IObjectCleanup) -END_COM_MAP() - -public: - - //IQueueCallbackCreate - STDMETHOD_(void,OnCreateFile)(_In_ IWDFIoQueue* pWdfQueue, _In_ IWDFIoRequest* pWDFRequest, _In_ IWDFFile* pWdfFileObject); - - //IQueueCallbackDeviceIoControl - STDMETHOD_(void,OnDeviceIoControl)(_In_ IWDFIoQueue* pWdfQueue, _In_ IWDFIoRequest* pWDFRequest, _In_ ULONG ControlCode, _In_ SIZE_T InBufferSize, _In_ SIZE_T OutBufferSize); - - //IObjectCleanup - STDMETHOD_(void,OnCleanup)(_In_ IWDFObject* pWdfObject); - - //IValidateAccept - void ValidateAccept(_In_ SOCKET Socket, _In_ GUID* pMagicPacket); - - - //IRequestCallbackCancel - STDMETHODIMP_(void) - OnCancel( - _In_ IWDFIoRequest* pWdfRequest - ); - - //IConnectionCallback - virtual void HandleReceivedMessage(_In_ MESSAGE* pMessageData); - virtual void ConnectionEstablished(_In_ CConnection* pBthConnection); - virtual BOOL ConnectionTerminated(_In_ CConnection* pBthConnection); - -public: - CMyQueue(); - ~CMyQueue(); - - STDMETHOD(Initialize)(_In_ CMyDevice * Device); - - HRESULT - Configure( - VOID - ); - - STDMETHODIMP_(void) - OnCloseFile( - _In_ IWDFFile* pWdfFileObject - ); - -private: - - void AddArrivalEvent(); - void AddRemovalEvent(); - -private: - CComPtr m_FxQueue; - - LIST_ENTRY m_SubsHead; - LIST_ENTRY m_ArrivalSubsHead; - LIST_ENTRY m_DepartureSubsHead; - CRITICAL_SECTION m_SubsLock; - - LIST_ENTRY m_PubsHead; - CRITICAL_SECTION m_PubsLock; - - LIST_ENTRY m_ConnectionHead; - CRITICAL_SECTION m_ConnectionLock; - - CSocketListener m_SocketListener; -}; diff --git a/nfp/net/driver/connection.h b/nfp/net/driver/connection.h deleted file mode 100644 index 6ab900e08..000000000 --- a/nfp/net/driver/connection.h +++ /dev/null @@ -1,125 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Abstract: - - Defines a simple NearFieldProximity Provider implementation using the network - for use in selfhosting. - -Author: - - Travis Martin (TravM) 06-24-2010 - ---*/ -#pragma once - -#include "SocketListener.h" - -class CConnection; - -struct MESSAGE; - -interface IConnectionCallback -{ - virtual void HandleReceivedMessage(_In_ MESSAGE* pMessage) = 0; - virtual void ConnectionEstablished(_In_ CConnection* pConnection) = 0; - virtual BOOL ConnectionTerminated(_In_ CConnection* pConnection) = 0; -}; - -class CConnection : public IValidateAccept -{ -private: - CConnection(_In_ IConnectionCallback* pCallback) : - _State(INITIAL), - _Socket(INVALID_SOCKET), - _pCallback(pCallback), - _ThreadpoolWork(NULL), - _fInboundConnection(false) - { - } - -public: - - virtual ~CConnection() - { - Terminate(); - - if (_ThreadpoolWork != NULL) - { - // Don't wait for threadpool callbacks when this thread is actually the threadpool callback - if (_ThreadpoolThreadId != GetCurrentThreadId()) - { - WaitForThreadpoolWorkCallbacks(_ThreadpoolWork, false); - } - CloseThreadpoolWork(_ThreadpoolWork); - _ThreadpoolWork = NULL; - } - } - - static HRESULT Create(_In_ IConnectionCallback* pCallback, _Outptr_ CConnection** ppConnection); - - void SetInboundConnection() { _fInboundConnection = true; } - bool IsInboundConnection() { return _fInboundConnection; } - - //IValidateAccept - void ValidateAccept(_In_ SOCKET Socket, _In_ GUID* pMagicPacket); - - HRESULT FinalizeEstablish(_In_ SOCKET Socket); - - HRESULT InitializeAsClient(_In_ BEGIN_PROXIMITY_ARGS* pArgs); - - HRESULT TransmitMessage(_In_ MESSAGE* pMessage); - - BOOL ReceiveThreadProc(); - static VOID CALLBACK s_ReceiveThreadProc( - _Inout_ PTP_CALLBACK_INSTANCE Instance, - _Inout_ PVOID Context, - _Inout_ PTP_WORK /*Work*/) - { - CallbackMayRunLong(Instance); - - CConnection* pConnection = (CConnection*)Context; - pConnection->_ThreadpoolThreadId = GetCurrentThreadId(); - BOOL fConnectionDeleted = pConnection->ReceiveThreadProc(); - - if (!fConnectionDeleted) - { - // Only clear the member variable if the connection object wasn't deleted. - pConnection->_ThreadpoolThreadId = 0; - } - } - - LIST_ENTRY* GetListEntry() { return &_ListEntry; } - static CConnection* FromListEntry(LIST_ENTRY* pListEntry) - { - return (CConnection*) CONTAINING_RECORD(pListEntry, CConnection, _ListEntry); - } - -private: - - void Terminate(); - -private: - - enum STATE - { - INITIAL = 0, - ESTABLISHED, - TERMINATED - }; - - volatile STATE _State; - - SOCKET _Socket; - - PTP_WORK _ThreadpoolWork; - DWORD _ThreadpoolThreadId; - - IConnectionCallback* _pCallback; - - bool _fInboundConnection; - - LIST_ENTRY _ListEntry; - -}; diff --git a/nfp/net/driver/device.cpp b/nfp/net/driver/device.cpp deleted file mode 100644 index 599d57b50..000000000 --- a/nfp/net/driver/device.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF sample - driver's device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver* FxDriver, - _In_ IWDFDeviceInitialize* FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - FxDriver - IWDF Driver for this device. - - Return Value: - - status. - ---*/ -{ - MethodEntry("..."); - - CComPtr fxDevice; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // Set the locking model - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - CComPtr pUnk; - HRESULT hrQI = this->QueryInterface(__uuidof(IUnknown),(void**)&pUnk); - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - hr = FxDriver->CreateDevice(FxDeviceInit, pUnk, &fxDevice); - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - } - - MethodReturnHR(hr); -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - MethodEntry("void"); - - // - // Create a new instance of our Queue callback object - // - CComObject * defaultQueue = NULL; - HRESULT hr = CComObject::CreateInstance(&defaultQueue); - - if (SUCCEEDED(hr)) - { - defaultQueue->AddRef(); - hr = defaultQueue->Initialize(this); - } - - if (SUCCEEDED(hr)) - { - hr = defaultQueue->Configure(); - } - - // - // Create and Enable Device Interfaces for this device. - // - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_NETNFP, - NULL); - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->AssignDeviceInterfaceState(&GUID_DEVINTERFACE_NETNFP, - NULL, - TRUE); - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_NFP, - NULL); - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->AssignDeviceInterfaceState(&GUID_DEVINTERFACE_NFP, - NULL, - TRUE); - } - - if (SUCCEEDED(hr)) - { - // - // Save a pointer to our queue, so we can lock it during file cleanup - // - m_MyQueue = defaultQueue; - } - - // - // Release the reference we took on the queue object. - // The framework took its own references on the object's callback interfaces - // when we called m_FxDevice->CreateIoQueue, and will manage the object's lifetime. - // - SAFE_RELEASE(defaultQueue); - - MethodReturnHR(hr); -} - -STDMETHODIMP_(void) -CMyDevice::OnCloseFile( - _In_ IWDFFile* pWdfFileObject - ) -{ - MethodEntry("..."); - - m_MyQueue->OnCloseFile(pWdfFileObject); - - MethodReturnVoid(); -} - -STDMETHODIMP_(void) -CMyDevice::OnCleanupFile( - _In_ IWDFFile* /*pWdfFileObject*/ - ) -/*++ - - Routine Description: - - This method is when app with open handle device terminates. - - Arguments: - - pWdfFileObject - the framework file object for which close is handled. - - Return Value: - - None - ---*/ -{ -} - -STDMETHODIMP_(void) -CMyDevice::OnCleanup( - _In_ IWDFObject* pWdfObject - ) -/*++ - - Routine Description: - - This device callback method is invoked by the framework when the WdfObject - is about to be released by the framework. - - Arguments: - - pWdfObject - the framework device object for which OnCleanup. - - Return Value: - - None - ---*/ -{ - MethodEntry("..."); - - WUDF_SAMPLE_DRIVER_ASSERT(pWdfObject == m_FxDevice); - - m_MyQueue = NULL; - - // - // CMyDevice has a reference to framework device object via m_Device. - // Framework device object has a reference to CMyDevice object via the callbacks. - // This leads to circular reference and both the objects can't be destroyed until this circular reference is broken. - // To break the circular reference we release the reference to the framework device object here in OnCleanup. - // - m_FxDevice = NULL; - - MethodReturnVoid(); -} diff --git a/nfp/net/driver/device.h b/nfp/net/driver/device.h deleted file mode 100644 index c4eeb1215..000000000 --- a/nfp/net/driver/device.h +++ /dev/null @@ -1,73 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ -#pragma once - -class CMyQueue; - -class ATL_NO_VTABLE CMyDevice : - public CComObjectRootEx, - public IFileCallbackCleanup, - public IFileCallbackClose, - public IObjectCleanup -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyDevice) - -BEGIN_COM_MAP(CMyDevice) - COM_INTERFACE_ENTRY(IFileCallbackCleanup) - COM_INTERFACE_ENTRY(IFileCallbackClose) - COM_INTERFACE_ENTRY(IObjectCleanup) -END_COM_MAP() - -public: - - //IFileCallbackCleanup - STDMETHOD_(void,OnCleanupFile)(_In_ IWDFFile* pWdfFileObject); - //IFileCallbackClose - STDMETHOD_(void,OnCloseFile)(_In_ IWDFFile* pWdfFileObject); - //IObjectCleanup - STDMETHOD_(void,OnCleanup)(_In_ IWDFObject* pWdfObject); - -public: - - STDMETHOD(Initialize)(_In_ IWDFDriver* pWdfDriver, _In_ IWDFDeviceInitialize* pWdfDeviceInit); - - HRESULT - Configure( - VOID - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - -private: - CComPtr m_FxDevice; - - CMyQueue* m_MyQueue; - - HRESULT ReadAndAssignPropertyStoreValue(); - HRESULT GetAnsiValFromPropVariant(_In_ PROPVARIANT val, _Inout_ LPSTR *PropertyValueA); - -}; diff --git a/nfp/net/driver/dllsup.cpp b/nfp/net/driver/dllsup.cpp deleted file mode 100644 index 85c866ecb..000000000 --- a/nfp/net/driver/dllsup.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Socktecho Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -class CNetNfpProviderModule : public CAtlDllModuleT< CNetNfpProviderModule > -{ -}; - - -OBJECT_ENTRY_AUTO(CLSID_MyDriverCoClass, CMyDriver) - - -CNetNfpProviderModule _AtlModule; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID Reserved - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - UNREFERENCED_PARAMETER( ModuleHandle ); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - TracingTlsInitialize(); - - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - TracingTlsFree(); - WPP_CLEANUP(); - } - - return _AtlModule.DllMain(Reason, Reserved); -; -} - -_Check_return_ -STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv) -{ - return _AtlModule.DllGetClassObject(rclsid, riid, ppv); -} diff --git a/nfp/net/driver/driver.cpp b/nfp/net/driver/driver.cpp deleted file mode 100644 index 2c28f16e1..000000000 --- a/nfp/net/driver/driver.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Socketecho Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ -#include "internal.h" - -#include "driver.tmh" - -DECLARE_TRACING_TLS; - -STDMETHODIMP -CMyDriver::OnInitialize( - _In_ IWDFDriver* /*pWdfDriver*/ - ) - - -/*++ - - Routine Description: - - This routine is invoked by the framework at driver load . - This method will invoke the Winsock Library for using - Winsock API in this driver. - - Arguments: - - pWdfDriver - Framework driver object - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ - -{ - MethodEntry("..."); - - HRESULT hr = S_OK; - - WSADATA wsaData; - int result = WSAStartup(MAKEWORD(2,2), &wsaData); - if (result != 0) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - TraceErrorHR(hr, "Failed to initialize Winsock 2.0"); - } - - MethodReturnHR(hr); -} - -STDMETHODIMP_(void) -CMyDriver::OnDeinitialize( - _In_ IWDFDriver* /*pWdfDriver*/ - ) - -/*++ - Routine Description: - - The FX invokes this method when it unloads the driver. - This routine will Cleanup Winsock library - - Arguments: - - pWdfDriver - the Fx driver object. - - Return Value: - - None - - --*/ -{ - MethodEntry("..."); - - WSACleanup(); - - MethodReturnVoid(); -} - -STDMETHODIMP -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - MethodEntry("..."); - - // - // Create a new instance of our device callback object - // - - CComObject * device; - HRESULT hr = CComObject::CreateInstance(&device); - if (SUCCEEDED(hr)) - { - device->AddRef(); - hr = device->Initialize(FxWdfDriver, FxDeviceInit); - if (SUCCEEDED(hr)) - { - // - // If that succeeded then call the device's configure method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - hr = device->Configure(); - } - - // - // Release the reference we took on the device object. - // The framework took its own references on the object's callback interfaces - // when we called FxWdfDriver->CreateDevice, and will manage the object's lifetime. - // - SAFE_RELEASE(device); - } - - MethodReturnHR(hr); -} diff --git a/nfp/net/driver/driver.h b/nfp/net/driver/driver.h deleted file mode 100644 index 6affa20fb..000000000 --- a/nfp/net/driver/driver.h +++ /dev/null @@ -1,53 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Socketecho sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the socktecho sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -extern const GUID CLSID_MyDriverCoClass; - -class ATL_NO_VTABLE CMyDriver : - public CComObjectRootEx, - public CComCoClass, - public IDriverEntry -{ -public: - -DECLARE_NOT_AGGREGATABLE(CMyDriver) - -DECLARE_CLASSFACTORY(); - -DECLARE_NO_REGISTRY(); - -BEGIN_COM_MAP(CMyDriver) - COM_INTERFACE_ENTRY(IDriverEntry) -END_COM_MAP() - -public: - // IDriverEntry - STDMETHOD(OnInitialize)(_In_ IWDFDriver* pWdfDriver); - STDMETHOD(OnDeviceAdd)(_In_ IWDFDriver* pWdfDriver, _In_ IWDFDeviceInitialize* pWdfDeviceInit); - STDMETHOD_(void,OnDeinitialize)(_In_ IWDFDriver* pWdfDriver); -}; - diff --git a/nfp/net/driver/exports.def b/nfp/net/driver/exports.def deleted file mode 100644 index 964e5f798..000000000 --- a/nfp/net/driver/exports.def +++ /dev/null @@ -1,6 +0,0 @@ -; exports.def : Declares the module parameters. - -LIBRARY "NetNfpProvider" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/nfp/net/driver/internal.h b/nfp/net/driver/internal.h deleted file mode 100644 index 80aa01526..000000000 --- a/nfp/net/driver/internal.h +++ /dev/null @@ -1,152 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Socketecho sample - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the winsock headers before any other windows headers. -// -#include -#include - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Define the tracing GUID for this driver -// - -#define TRACE_CONTROL_GUID (12579E92,1B46,40A6,9CFC,C718A677830B) - - -// -// Driver specific #defines -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\NetNfpProvider" - -/* 278F44F0-FF5C-4FE3-BF20-F8AA158EA7BC */ -#define MYDRIVER_CLASS_ID { 0x278F44F0, 0xFF5C, 0x4FE3, {0xBF, 0x20, 0xF8, 0xAA, 0x15, 0x8E, 0xA7, 0xBC} } -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} -#endif - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_SAMPLE_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -// -// define the maximum size of the message queue -// - -#define MAX_MESSAGE_QUEUE_SIZE 50 - -// -// MessageId: STATUS_CANCELLED -// -// MessageText: -// -// The I/O request was canceled. -// -#define STATUS_CANCELLED (0xC0000120L) - -// -// MessageId: STATUS_INVALID_DEVICE_STATE -// -// MessageText: -// -// The device is not in a valid state to perform this request. -// -#define STATUS_INVALID_DEVICE_STATE (0xC0000184L) - -// -// MessageId: STATUS_INVALID_BUFFER_SIZE -// -// MessageText: -// -// The size of the buffer is invalid for the specified operation. -// -#define STATUS_INVALID_BUFFER_SIZE (0xC0000206L) - -// -// MessageId: STATUS_OBJECT_PATH_NOT_FOUND -// -// MessageText: -// -// {Path Not Found} -// The path %hs does not exist. -// -#define STATUS_OBJECT_PATH_NOT_FOUND ((NTSTATUS)0xC000003AL) - -// -// Include the type specific headers. -// -#include -#include - -// Windows Headers -#include -#include -#include -#include -#include -#include - -// Sample headers -#include "NetNfp.h" -#include "WppDefs.h" -#include "list.h" -#include "connection.h" -#include "filecontext.h" -#include "driver.h" -#include "device.h" -#include "queue.h" - -_Analysis_mode_(_Analysis_operator_new_null_) - diff --git a/nfp/net/driver/list.h b/nfp/net/driver/list.h deleted file mode 100644 index d2bfce3f2..000000000 --- a/nfp/net/driver/list.h +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -FORCEINLINE -VOID -InitializeListHead( - _Out_ PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -_Check_return_ -BOOLEAN -FORCEINLINE -IsListEmpty( - _In_ const LIST_ENTRY * ListHead - ) -{ - return (BOOLEAN)(ListHead->Flink == ListHead); -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - _In_ PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -PLIST_ENTRY -RemoveHeadList( - _Inout_ PLIST_ENTRY ListHead - ) -{ - PLIST_ENTRY Flink; - PLIST_ENTRY Entry; - - Entry = ListHead->Flink; - Flink = Entry->Flink; - ListHead->Flink = Flink; - Flink->Blink = ListHead; - return Entry; -} - - - -FORCEINLINE -PLIST_ENTRY -RemoveTailList( - _Inout_ PLIST_ENTRY ListHead - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Entry; - - Entry = ListHead->Blink; - Blink = Entry->Blink; - ListHead->Blink = Blink; - Blink->Flink = ListHead; - return Entry; -} - - -FORCEINLINE -VOID -InsertTailList( - _Inout_ PLIST_ENTRY ListHead, - _Inout_ __drv_aliasesMem PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} - - -FORCEINLINE -VOID -InsertHeadList( - _Inout_ PLIST_ENTRY ListHead, - _Inout_ __drv_aliasesMem PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -AppendTailList( - _Inout_ PLIST_ENTRY ListHead, - _Inout_ PLIST_ENTRY ListToAppend - ) -{ - PLIST_ENTRY ListEnd = ListHead->Blink; - - ListHead->Blink->Flink = ListToAppend; - ListHead->Blink = ListToAppend->Blink; - ListToAppend->Blink->Flink = ListHead; - ListToAppend->Blink = ListEnd; -} diff --git a/nfp/net/driver/netnfpprovider.inx b/nfp/net/driver/netnfpprovider.inx deleted file mode 100644 index fa19a86dd..000000000 Binary files a/nfp/net/driver/netnfpprovider.inx and /dev/null differ diff --git a/nfp/net/driver/netnfpprovider.rc b/nfp/net/driver/netnfpprovider.rc deleted file mode 100644 index 98d1f8ab2..000000000 --- a/nfp/net/driver/netnfpprovider.rc +++ /dev/null @@ -1,18 +0,0 @@ -//--------------------------------------------------------------------------- -// Skeleton.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF Network NearFieldProximity Provider" -#define VER_INTERNALNAME_STR "NetNfpProvider" -#define VER_ORIGINALFILENAME_STR "NetNfpProvider.dll" - -#include "common.ver" diff --git a/nfp/net/driver/socketlistener.cpp b/nfp/net/driver/socketlistener.cpp deleted file mode 100644 index 3aaa687b9..000000000 --- a/nfp/net/driver/socketlistener.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Abstract: - - Implements a socket listener class - -Author: - - Travis Martin (TravM) 06-24-2010 - -Environment: - - User-mode only. - ---*/ -#include "internal.h" - -#include "SocketListener.tmh" - -HRESULT SetSocketIpv6Only(_In_ SOCKET socket, _In_ BOOL Ipv6Only) -{ - HRESULT hr = S_OK; - if (setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&Ipv6Only, sizeof(Ipv6Only)) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - USE_DEFAULT_TRACING_CONTEXT; - TraceErrorHR(hr, "setsockopt IPV6_V6ONLY"); - } - return hr; -} - -HRESULT CSocketListener::EnableAccepting(_In_ IValidateAccept* pValidator) -{ - HRESULT hr = S_OK; - if (_pValidator == NULL) - { - USE_DEFAULT_TRACING_CONTEXT; - - _ThreadpoolIo = CreateThreadpoolIo((HANDLE)_ListenSocket, s_AcceptThreadProc, this, NULL); - if (_ThreadpoolIo == NULL) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - - if (SUCCEEDED(hr)) - { - int backlog = 2; - if (listen(_ListenSocket, backlog) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - } - - if (SUCCEEDED(hr)) - { - // We're now accepting - _pValidator = pValidator; - - hr = BeginAccept(); - if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING)) - { - hr = S_OK; - } - } - - TraceInfo("EnableAccepting(): %!HRESULT!", hr); - } - - return hr; -} - -void CSocketListener::StopAccepting() -{ - MethodEntry("void"); - - SOCKET listenSocket = InterlockedExchange(&_ListenSocket, INVALID_SOCKET); - if (listenSocket != INVALID_SOCKET) - { - closesocket(listenSocket); - } - - PTP_IO threadpoolIo = (PTP_IO)InterlockedExchangePointer((PVOID*)&_ThreadpoolIo, NULL); - if (threadpoolIo != NULL) - { - // Don't wait for threadpool callbacks when this thread is actually the threadpool callback - if (_ThreadpoolThreadId != GetCurrentThreadId()) - { - WaitForThreadpoolIoCallbacks(threadpoolIo, false); - } - CloseThreadpoolIo(threadpoolIo); - } - - _pValidator = NULL; - - if (_ClientSocket != INVALID_SOCKET) - { - closesocket(_ClientSocket); - _ClientSocket = INVALID_SOCKET; - } - - MethodReturnVoid(); -} - -HRESULT CSocketListener::BeginAccept() -{ - MethodEntry("void"); - - HRESULT hr = S_OK; - _ClientSocket = socket(AF_INET6, SOCK_STREAM, 0); - if (_ClientSocket == INVALID_SOCKET) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - - if (SUCCEEDED(hr)) - { - hr = SetSocketIpv6Only(_ClientSocket, FALSE); - } - - if (SUCCEEDED(hr)) - { - PTP_IO threadpoolIo = _ThreadpoolIo; - if (threadpoolIo != NULL) - { - StartThreadpoolIo(threadpoolIo); - - ULONG_PTR cbReceived = 0; - ZeroMemory(&_Overlapped, sizeof(_Overlapped)); - if (!AcceptEx(_ListenSocket, _ClientSocket, &_AcceptBuffer, - sizeof(_AcceptBuffer.MagicPacket), - sizeof(_AcceptBuffer.DestAddress), - sizeof(_AcceptBuffer.SourceAddress), - (LPDWORD)&cbReceived, &_Overlapped)) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - if (hr != HRESULT_FROM_WIN32(ERROR_IO_PENDING)) - { - // Failed to accept, so cleanup - CancelThreadpoolIo(threadpoolIo); - StopAccepting(); - } - } - } - } - - MethodReturnHR(hr); -} - -void CSocketListener::AcceptThreadProc(_In_ HRESULT hr, _In_ ULONG_PTR cbReceived) -{ - MethodEntry("hr = %!HRESULT!, cbReceived = %d", - hr, (ULONG)cbReceived); - - if (SUCCEEDED(hr)) - { - if (cbReceived == sizeof(_AcceptBuffer.MagicPacket)) - { - // Transfer ownership of _ClientSocket - _pValidator->ValidateAccept(_ClientSocket, &_AcceptBuffer.MagicPacket); - } - else - { - // Wrong header size, close immediately - closesocket(_ClientSocket); - } - _ClientSocket = INVALID_SOCKET; - } - - // Start up another accept request - BeginAccept(); - - MethodReturnVoid(); -} - -HRESULT CSocketListener::Bind() -{ - MethodEntry("void"); - - // Create a SOCKET for connecting to this server - HRESULT hr = S_OK; - addrinfoW* pResult = NULL; - addrinfoW Hints = {}; - Hints.ai_family = AF_INET6; - Hints.ai_socktype = SOCK_STREAM; - Hints.ai_flags = AI_PASSIVE; - - // Resolve the server address and port - if (GetAddrInfoW(NULL, L"9299", &Hints, &pResult) != ERROR_SUCCESS ) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - - if (SUCCEEDED(hr)) - { - // Create a SOCKET for connecting to server - _ListenSocket = socket(AF_INET6, SOCK_STREAM, 0); - if (_ListenSocket == INVALID_SOCKET) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - - if (SUCCEEDED(hr)) - { - hr = SetSocketIpv6Only(_ListenSocket, FALSE); - } - - if (SUCCEEDED(hr)) - { - // Setup the TCP listening socket - if (bind(_ListenSocket, pResult->ai_addr, (int)pResult->ai_addrlen) == SOCKET_ERROR) - { - hr = HRESULT_FROM_WIN32(WSAGetLastError()); - } - } - FreeAddrInfoW(pResult); - } - - MethodReturnHR(hr); -} - diff --git a/nfp/net/driver/socketlistener.h b/nfp/net/driver/socketlistener.h deleted file mode 100644 index dffb11a2b..000000000 --- a/nfp/net/driver/socketlistener.h +++ /dev/null @@ -1,84 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Abstract: - - Declares a socket listener class - -Author: - - Travis Martin (TravM) 06-24-2010 - -Environment: - - User-mode only. - ---*/ -#pragma once - -struct ACCEPT_BUFFER -{ - GUID MagicPacket; - - SOCKADDR_STORAGE DestAddress; - SOCKADDR_STORAGE SourceAddress; -}; - -interface IValidateAccept -{ - virtual void ValidateAccept(_In_ SOCKET Socket, _In_ GUID* pMagicPacket) = 0; -}; - -class CSocketListener -{ -public: - CSocketListener() : - _pValidator(NULL), - _ThreadpoolIo(NULL), - _ListenSocket(INVALID_SOCKET), - _ClientSocket(INVALID_SOCKET) - { - ZeroMemory(&_Overlapped, sizeof(_Overlapped)); - } - - ~CSocketListener() - { - StopAccepting(); - } - -public: - HRESULT Bind(); - HRESULT EnableAccepting(_In_ IValidateAccept* pValidator); - void StopAccepting(); - -private: - - HRESULT BeginAccept(); - void AcceptThreadProc(_In_ HRESULT hr, _In_ ULONG_PTR cbReceived); - static void CALLBACK s_AcceptThreadProc( - _Inout_ PTP_CALLBACK_INSTANCE /*Instance*/, - _Inout_ PVOID Context, - _Inout_opt_ PVOID /*Overlapped*/, - _In_ ULONG IoResult, - _In_ ULONG_PTR NumberOfBytesTransferred, - _Inout_ PTP_IO /*Io*/) - { - CSocketListener* pSocketListener = (CSocketListener*)Context; - pSocketListener->_ThreadpoolThreadId = GetCurrentThreadId(); - pSocketListener->AcceptThreadProc(HRESULT_FROM_WIN32(IoResult), NumberOfBytesTransferred); - pSocketListener->_ThreadpoolThreadId = 0; - } - -private: - ACCEPT_BUFFER _AcceptBuffer; - - OVERLAPPED _Overlapped; - volatile PTP_IO _ThreadpoolIo; - DWORD _ThreadpoolThreadId; - - IValidateAccept* _pValidator; - - SOCKET _ListenSocket; - SOCKET _ClientSocket; -}; diff --git a/nfp/net/driver/wppdefs.h b/nfp/net/driver/wppdefs.h deleted file mode 100644 index da0a176e7..000000000 --- a/nfp/net/driver/wppdefs.h +++ /dev/null @@ -1,452 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All Rights Reserved - -Abstract: - - WPP Macro definitions. - -Author: - - Travis Martin (TravM) - ---*/ - -// -// Helpful macros -// - -#ifndef WIDEN2 -#define WIDEN2(x) L ## x -#define WIDEN(x) WIDEN2(x) -#endif - - -// -// WPP definitions. Listed below is a set of WPP Trace macros. The comments -// between "//begin_wpp config" and "//end_wpp" are used by the WPP pre-processor -// to create the *.tmh files -// - - -#define PROXIMITY_COMMON_TRACE L"Microsoft\\Windows\\ProximityCommon" - -#ifndef TRACE_CONTROL_GUID -#define TRACE_CONTROL_GUID (93bfc19b, a967, 4339, a3e6, 3a4cc30681d1) -#endif - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID(PROXIMITY, TRACE_CONTROL_GUID, \ - WPP_DEFINE_BIT(EntryExit) \ - WPP_DEFINE_BIT(AllocFree) \ - WPP_DEFINE_BIT(Info) \ - WPP_DEFINE_BIT(Warning) \ - WPP_DEFINE_BIT(Error) \ - \ - WPP_DEFINE_BIT(NoisyEntryExit) \ - WPP_DEFINE_BIT(NoisyAllocFree) \ - WPP_DEFINE_BIT(NoisyInfo) \ - WPP_DEFINE_BIT(NoisyWarning)) - - -// -// Used for trace messages indentation -// -const char __indentSpacer[] = -" " -" " -" " -" " -" " -" "; - -#define INDENT_STR(indent) \ - (__indentSpacer + ((sizeof(__indentSpacer) >= (indent)*5) ? (sizeof(__indentSpacer)-2-(indent)*5) : 0)) - - -//--------------------------------------------------------------------------- -// Stores a pointer to current tracing context -//--------------------------------------------------------------------------- -extern DWORD __g_tracingTlsSlot; - -//--------------------------------------------------------------------------- -// This macro declares the global variable that will store TLS index for the -// tracing context pointer. -//--------------------------------------------------------------------------- -#define DECLARE_TRACING_TLS DWORD __g_tracingTlsSlot = TLS_OUT_OF_INDEXES - -//--------------------------------------------------------------------------- -// To be used only within non-WDTF EXE init routines or by the Tracer. -//--------------------------------------------------------------------------- -inline bool TracingTlsInitialize() -{ - if (__g_tracingTlsSlot == TLS_OUT_OF_INDEXES) - { - __g_tracingTlsSlot = TlsAlloc(); - if (__g_tracingTlsSlot == TLS_OUT_OF_INDEXES) - { - // Return error: cannot allocate TLS slot - return false; - } - } - return true; -} - -//--------------------------------------------------------------------------- -// To be used only within non-WDTF EXE exit routines or by the Tracer. -//--------------------------------------------------------------------------- -inline void TracingTlsFree() -{ - if (__g_tracingTlsSlot != TLS_OUT_OF_INDEXES) - { - TlsFree(__g_tracingTlsSlot); - __g_tracingTlsSlot = TLS_OUT_OF_INDEXES; - } -} - - -namespace TracingInternal -{ - -//--------------------------------------------------------------------------- -// Used for storing current tracing context within a TLS slot -//--------------------------------------------------------------------------- -struct TracingContext -{ - ULONG CallDepth; // Current depth of internal calls - DWORD Context; // A context value (used to correlate scenarios that cross-threads) -}; - -//--------------------------------------------------------------------------- -// Auto-incrementing and decrementing variable -//--------------------------------------------------------------------------- -class AutoStackDepth -{ -public: - __forceinline AutoStackDepth(ULONG *pCallDepth) - : _pCallDepth(pCallDepth) - { - WUDF_SAMPLE_DRIVER_ASSERT(_pCallDepth); - if (_pCallDepth) - { - ++*_pCallDepth; - } - } - - __forceinline ~AutoStackDepth() - { - if (_pCallDepth) - { - --*_pCallDepth; - } - } - -private: - AutoStackDepth(AutoStackDepth& rh); - const AutoStackDepth& operator =(AutoStackDepth& rh); - -private: - ULONG* _pCallDepth; -}; - -//--------------------------------------------------------------------------- -// Sets new value to a variable but saves old value and restores it on -// destrutcion -//--------------------------------------------------------------------------- -template -class AutoRestoredValue -{ -public: - __forceinline AutoRestoredValue(T* pVar, T newVal) - : _pVar(pVar) - , _oldVal() - { - WUDF_SAMPLE_DRIVER_ASSERT(_pVar); - if (_pVar) - { - _oldVal = *_pVar; - *_pVar = newVal; - } - } - - __forceinline ~AutoRestoredValue() - { - if (_pVar) - { - *_pVar = _oldVal; - } - } - -private: - AutoRestoredValue(AutoRestoredValue& rh); - const AutoRestoredValue& operator =(AutoRestoredValue& rh); - -private: - - T* _pVar; - T _oldVal; -}; - -//--------------------------------------------------------------------------- -// Auto-pointer stored in TLS -//--------------------------------------------------------------------------- -template -class AutoTlsPtr -{ -public: - __forceinline AutoTlsPtr() - : _dwSlotIndex(TLS_OUT_OF_INDEXES) - { - } - - __forceinline ~AutoTlsPtr() - { - if (_dwSlotIndex != TLS_OUT_OF_INDEXES) - { - LPVOID pCtx = TlsGetValue(_dwSlotIndex); - if (pCtx) - { - TlsSetValue(_dwSlotIndex, NULL); - } - } - } - - __forceinline Attach(Pointee* pCtx, DWORD dwSlotIndex) - { - _dwSlotIndex = dwSlotIndex; - TlsSetValue(_dwSlotIndex, pCtx); - } - -private: - - DWORD _dwSlotIndex; -}; - -} - - -//--------------------------------------------------------------------------- -// This macro should be used at entry point of all functions with tracing. -// It reads from a Tracing context structure stored in the TLS. -// If the slot contains a NULL a new TracingContext is used. An object -// is created that increments CallDepth and auto-decrements it on function exit. -//--------------------------------------------------------------------------- -#define USE_DEFAULT_TRACING_CONTEXT \ - TracingInternal::TracingContext* __pCtx = (TracingInternal::TracingContext*)TlsGetValue(__g_tracingTlsSlot); \ - TracingInternal::AutoTlsPtr __autoTlsPtr; \ - TracingInternal::TracingContext __ctx; \ - if (__pCtx == NULL) \ - { \ - __pCtx = &__ctx; \ - __pCtx->CallDepth = 0; \ - __autoTlsPtr.Attach(__pCtx, __g_tracingTlsSlot); \ - } \ - TracingInternal::AutoStackDepth __autoStackDepth(&__pCtx->CallDepth); - - -//MACRO: MethodEntry -// -//begin_wpp config -//USEPREFIX (MethodEntry, "%!STDPREFIX!%s-->this(%p):%!FUNC!(", INDENT_STR(__pCtx->CallDepth), this); -//FUNC MethodEntry{ENTRYLEVEL=EntryExit}(MSG, ...); -//USESUFFIX (MethodEntry, ")"); -//end_wpp -#define WPP_ENTRYLEVEL_ENABLED(LEVEL) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_ENTRYLEVEL_LOGGER(LEVEL) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_ENTRYLEVEL_PRE(LEVEL) USE_DEFAULT_TRACING_CONTEXT; - - -//MACRO: MethodReturn -// -//begin_wpp config -//USEPREFIX (MethodReturn, "%!STDPREFIX!%s<--this(%p):%!FUNC!(): ", INDENT_STR(__pCtx->CallDepth), this); -//FUNC MethodReturn{RETURNLEVEL=EntryExit}(RET, MSG, ...); -//end_wpp -#define WPP_RETURNLEVEL_RET_ENABLED(LEVEL, Ret) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_RETURNLEVEL_RET_LOGGER(LEVEL, Ret) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_RETURNLEVEL_RET_POST(LEVEL, Ret) ;return Ret; - - -//MACRO: MethodReturnHR -// -//begin_wpp config -//USEPREFIX (MethodReturnHR, "%!STDPREFIX!%s<--this(%p):%!FUNC!(): %!HRESULT!", INDENT_STR(__pCtx->CallDepth), this, __hr); -//FUNC MethodReturnHR{RETURNHRLEVEL=EntryExit}(HR); -//end_wpp -#define WPP_RETURNHRLEVEL_HR_ENABLED(LEVEL, hr) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_RETURNHRLEVEL_HR_LOGGER(LEVEL, hr) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_RETURNHRLEVEL_HR_PRE(LEVEL, hr) { \ - HRESULT __hr = hr; -#define WPP_RETURNHRLEVEL_HR_POST(LEVEL, hr) /*TraceMessage()*/; \ - return __hr; \ - } -//MACRO: MethodReturnVoid -// -//begin_wpp config -//USEPREFIX (MethodReturnVoid, "%!STDPREFIX!%s<--this(%p):%!FUNC!()", INDENT_STR(__pCtx->CallDepth), this); -//FUNC MethodReturnVoid{RETURNVOIDLEVEL=EntryExit}(...); -//end_wpp -#define WPP_RETURNVOIDLEVEL_ENABLED(LEVEL) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_RETURNVOIDLEVEL_LOGGER(LEVEL) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_RETURNVOIDLEVEL_POST(LEVEL) ;return; - - -//MACRO: MethodReturnBool -// -//begin_wpp config -//USEPREFIX (MethodReturnBool, "%!STDPREFIX!%s<--this(%p):%!FUNC!(): %!bool!", INDENT_STR(__pCtx->CallDepth), this, __bRet); -//FUNC MethodReturnBool{RETURNBOOLLEVEL=EntryExit}(BOOLRETVAL); -//end_wpp -#define WPP_RETURNBOOLLEVEL_BOOLRETVAL_ENABLED(LEVEL, bRet) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_RETURNBOOLLEVEL_BOOLRETVAL_LOGGER(LEVEL, bRet) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_RETURNBOOLLEVEL_BOOLRETVAL_PRE(LEVEL, bRet) { \ - bool __bRet = (bRet ? true : false); -#define WPP_RETURNBOOLLEVEL_BOOLRETVAL_POST(LEVEL, bRet) /*TraceMessage()*/; \ - return __bRet; \ - } -//MACRO: MethodReturnPtr -// -//begin_wpp config -//USEPREFIX (MethodReturnPtr, "%!STDPREFIX!%s<--this(%p):%!FUNC!(): %p", INDENT_STR(__pCtx->CallDepth), this, __ptrRetVal); -//FUNC MethodReturnPtr{RETURNPTRLEVEL=EntryExit}(TYPE, PRET); -//end_wpp -#define WPP_RETURNPTRLEVEL_TYPE_PRET_ENABLED(LEVEL, Type, pRet) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_RETURNPTRLEVEL_TYPE_PRET_LOGGER(LEVEL, Type, pRet) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_RETURNPTRLEVEL_TYPE_PRET_PRE(LEVEL, Type, pRet) { \ - Type __pRet = pRet; -#define WPP_RETURNPTRLEVEL_TYPE_PRET_POST(LEVEL, Type, pRet) /*TraceMessage()*/; \ - return __pRet; \ - } -//MACRO: MethodReturnIfNull -// -//begin_wpp config -//USEPREFIX (MethodReturnIfNull, "%!STDPREFIX!%s<-this(%p):%!FUNC!(): E_POINTER %s=NULL, bailing out!", INDENT_STR(__pCtx->CallDepth), this, #PTR); -//FUNC MethodReturnIfNull{METHOD_POINTER_LEVEL=EntryExit}(PTR); -//end_wpp -#define WPP_METHOD_POINTER_LEVEL_PTR_ENABLED(LEVEL, PTR) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_METHOD_POINTER_LEVEL_PTR_LOGGER(LEVEL, PTR) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_METHOD_POINTER_LEVEL_PTR_PRE(LEVEL, PTR) if ((PTR) == NULL) \ - { -#define WPP_METHOD_POINTER_LEVEL_PTR_POST(LEVEL, PTR) /*TraceMessage()*/; \ - return E_POINTER; \ - } -//MACRO: FunctionEntry -// -//begin_wpp config -//USEPREFIX (FunctionEntry, "%!STDPREFIX!%s-->%!FUNC!(", INDENT_STR(__pCtx->CallDepth)); -//FUNC FunctionEntry{FUNCENTRYLEVEL=EntryExit}(MSG, ...); -//USESUFFIX (FunctionEntry, ")"); -//end_wpp -#define WPP_FUNCENTRYLEVEL_ENABLED(LEVEL) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCENTRYLEVEL_LOGGER(LEVEL) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCENTRYLEVEL_PRE(LEVEL) USE_DEFAULT_TRACING_CONTEXT; - - -//MACRO: FunctionReturn -// -//begin_wpp config -//USEPREFIX (FunctionReturn, "%!STDPREFIX!%s<--%!FUNC!(): ", INDENT_STR(__pCtx->CallDepth)); -//FUNC FunctionReturn{FUNCRETURNLEVEL=EntryExit}(RET, MSG, ...); -//end_wpp -#define WPP_FUNCRETURNLEVEL_RET_ENABLED(LEVEL, Ret) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCRETURNLEVEL_RET_LOGGER(LEVEL, Ret) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCRETURNLEVEL_RET_POST(LEVEL, Ret) ;return Ret; - - -//MACRO: FunctionReturnHR -// -//begin_wpp config -//USEPREFIX (FunctionReturnHR, "%!STDPREFIX!%s<--%!FUNC!(): %!HRESULT!", INDENT_STR(__pCtx->CallDepth), __hr); -//FUNC FunctionReturnHR{FUNCRETURNHRLEVEL=EntryExit}(HR); -//end_wpp -#define WPP_FUNCRETURNHRLEVEL_HR_ENABLED(LEVEL, hr) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCRETURNHRLEVEL_HR_LOGGER(LEVEL, hr) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCRETURNHRLEVEL_HR_PRE(LEVEL, hr) { \ - HRESULT __hr = hr; -#define WPP_FUNCRETURNHRLEVEL_HR_POST(LEVEL, hr) /*TraceMessage()*/; \ - return __hr; \ - } -//MACRO: FunctionReturnVoid -// -//begin_wpp config -//USEPREFIX (FunctionReturnVoid, "%!STDPREFIX!%s<--%!FUNC!()", INDENT_STR(__pCtx->CallDepth)); -//FUNC FunctionReturnVoid{FUNCRETURNLEVELVOID=EntryExit}(...); -//end_wpp -#define WPP_FUNCRETURNLEVELVOID_ENABLED(LEVEL) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCRETURNLEVELVOID_LOGGER(LEVEL) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCRETURNLEVELVOID_POST(LEVEL) ;return; - - -//MACRO: FunctionReturnBool -// -//begin_wpp config -//USEPREFIX (FunctionReturnBool, "%!STDPREFIX!%s<--%!FUNC!(): %!bool!", INDENT_STR(__pCtx->CallDepth), __bRet); -//FUNC FunctionReturnBool{FUNCRETURNLEVELBOOL=EntryExit}(BOOLRETVAL); -//end_wpp -#define WPP_FUNCRETURNLEVELBOOL_BOOLRETVAL_ENABLED(LEVEL, bRet) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCRETURNLEVELBOOL_BOOLRETVAL_LOGGER(LEVEL, bRet) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCRETURNLEVELBOOL_BOOLRETVAL_PRE(LEVEL, bRet) { \ - bool __bRet = (bRet ? true : false); -#define WPP_FUNCRETURNLEVELBOOL_BOOLRETVAL_POST(LEVEL, bRet) /*TraceMessage()*/; \ - return __bRet; \ - } -//MACRO: FunctionReturnPtr -// -//begin_wpp config -//USEPREFIX (FunctionReturnPtr, "%!STDPREFIX!%s<--%!FUNC!(): %p", INDENT_STR(__pCtx->CallDepth), __pRet); -//FUNC FunctionReturnPtr{FUNCRETURNLEVELPTR=EntryExit}(TYPE, PRET); -//end_wpp -#define WPP_FUNCRETURNLEVELPTR_TYPE_PRET_ENABLED(LEVEL, Type, pRet) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_FUNCRETURNLEVELPTR_TYPE_PRET_LOGGER(LEVEL, Type, pRet) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_FUNCRETURNLEVELPTR_TYPE_PRET_PRE(LEVEL, Type, pRet) { \ - Type __pRet = pRet; -#define WPP_FUNCRETURNLEVELPTR_TYPE_PRET_POST(LEVEL, Type, pRet) /*TraceMessage()*/; \ - return __pRet; \ - } - - - -// Define Non-empty debug break for checked builds only -#ifndef NDEBUG - #define DEBUG_BREAK() __debugbreak() -#else - #define DEBUG_BREAK() do {} while (false) -#endif - - -//MACRO: TraceASSERT -// -// ASSERT with tracing -// -//begin_wpp config -//USEPREFIX (TraceASSERT, "%!STDPREFIX!%sWARN: ASSERTION FAILED - expression \"%s\" is false.", INDENT_STR(__pCtx->CallDepth+1), #EXPR); -//FUNC TraceASSERT{ASSERTLEVEL=Warning}(EXPR); -//end_wpp -#define WPP_ASSERTLEVEL_EXPR_ENABLED(LEVEL, EXPR) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_ASSERTLEVEL_EXPR_LOGGER(LEVEL, EXPR) WPP_LEVEL_LOGGER(LEVEL) -#define WPP_ASSERTLEVEL_EXPR_PRE(LEVEL, EXPR) if (!(EXPR)) \ - { -#define WPP_ASSERTLEVEL_EXPR_POST(LEVEL, EXPR) /*TraceMessage()*/; \ - WUDF_SAMPLE_DRIVER_ASSERT(FALSE); \ - } - -//MACRO: TraceErrorHR -// -// ERROR trace -// -//begin_wpp config -//USEPREFIX (TraceErrorHR, "%!STDPREFIX!%sERROR: ", INDENT_STR(__pCtx->CallDepth+1)); -//FUNC TraceErrorHR{ERRORLEVEL=Error}(HR, MSG, ...); -//USESUFFIX (TraceErrorHR, ": %!HRESULT!", HR); -//end_wpp -#define WPP_ERRORLEVEL_HR_ENABLED(LEVEL, HR) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_ERRORLEVEL_HR_LOGGER(LEVEL, HR) WPP_LEVEL_LOGGER(LEVEL) - -//MACRO: TraceInfo -// -//begin_wpp config -//USEPREFIX (TraceInfo, "%!STDPREFIX!%s", INDENT_STR(__pCtx->CallDepth+1)); -//FUNC TraceInfo{INFOLEVEL=Info}(MSG, ...); -//end_wpp -#define WPP_INFOLEVEL_ENABLED(LEVEL) WPP_LEVEL_ENABLED(LEVEL) -#define WPP_INFOLEVEL_LOGGER(LEVEL) WPP_LEVEL_LOGGER(LEVEL) \ No newline at end of file diff --git a/nfp/net/exe/NetNfpControl.vcxproj b/nfp/net/exe/NetNfpControl.vcxproj index 9d80e0ebc..6dbe997c0 100644 --- a/nfp/net/exe/NetNfpControl.vcxproj +++ b/nfp/net/exe/NetNfpControl.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/nfp/net/netnfp.sln b/nfp/net/netnfp.sln index d8897915b..dff6f191f 100644 --- a/nfp/net/netnfp.sln +++ b/nfp/net/netnfp.sln @@ -3,12 +3,8 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0 MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Driver", "Driver", "{BFCC1107-0069-463E-B32F-5796262F79AB}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{4AD37F99-392D-419E-91D1-E8CB02B5E908}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NetNfpProvider", "driver\NetNfpProvider.vcxproj", "{7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NetNfpControl", "exe\NetNfpControl.vcxproj", "{6F9C9973-9703-40D9-AA4B-F3D4610DDDB1}" EndProject Global @@ -19,14 +15,6 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Debug|Win32.ActiveCfg = Debug|Win32 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Debug|Win32.Build.0 = Debug|Win32 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Release|Win32.ActiveCfg = Release|Win32 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Release|Win32.Build.0 = Release|Win32 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Debug|x64.ActiveCfg = Debug|x64 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Debug|x64.Build.0 = Debug|x64 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Release|x64.ActiveCfg = Release|x64 - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC}.Release|x64.Build.0 = Release|x64 {6F9C9973-9703-40D9-AA4B-F3D4610DDDB1}.Debug|Win32.ActiveCfg = Debug|Win32 {6F9C9973-9703-40D9-AA4B-F3D4610DDDB1}.Debug|Win32.Build.0 = Debug|Win32 {6F9C9973-9703-40D9-AA4B-F3D4610DDDB1}.Release|Win32.ActiveCfg = Release|Win32 @@ -40,7 +28,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {7CA060D7-267A-48BC-8FAD-F1B6BA53C2FC} = {BFCC1107-0069-463E-B32F-5796262F79AB} {6F9C9973-9703-40D9-AA4B-F3D4610DDDB1} = {4AD37F99-392D-419E-91D1-E8CB02B5E908} EndGlobalSection EndGlobal diff --git a/pofx/PEP/acpi/acpispecific.c b/pofx/PEP/acpi/acpispecific.c index 0e501ad3d..7160622be 100644 --- a/pofx/PEP/acpi/acpispecific.c +++ b/pofx/PEP/acpi/acpispecific.c @@ -30,7 +30,7 @@ Module Name: #endif // -// To add new devices that will be accpeted by the platform extension, +// To add new devices that will be accepted by the platform extension, // follow to the example below. // @@ -50,9 +50,9 @@ Module Name: // // The common library will consume the PepDeviceMatchArray to determine -// whether a device should be accpeted by the platform extension. +// whether a device should be accepted by the platform extension. // And then the common library will consult PepDeviceDefinitionArray for -// the native methods and device-specific notification handlers of the accpeted +// the native methods and device-specific notification handlers of the accepted // devices. // diff --git a/pofx/PEP/acpi/sampleacpipep.inx b/pofx/PEP/acpi/sampleacpipep.inx index b4059974f..9f93ad5b4 100644 Binary files a/pofx/PEP/acpi/sampleacpipep.inx and b/pofx/PEP/acpi/sampleacpipep.inx differ diff --git a/pofx/PEP/acpi/sampleacpipep.vcxproj b/pofx/PEP/acpi/sampleacpipep.vcxproj index 19607f91f..357b22056 100644 --- a/pofx/PEP/acpi/sampleacpipep.vcxproj +++ b/pofx/PEP/acpi/sampleacpipep.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/pofx/PEP/common/pepcommon.vcxproj b/pofx/PEP/common/pepcommon.vcxproj index b3e90eead..d17289da2 100644 --- a/pofx/PEP/common/pepcommon.vcxproj +++ b/pofx/PEP/common/pepcommon.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary diff --git a/pofx/UMDF2/App/PowerFxApp.vcxproj b/pofx/UMDF2/App/PowerFxApp.vcxproj index 2a0233b3e..54e81f3eb 100644 --- a/pofx/UMDF2/App/PowerFxApp.vcxproj +++ b/pofx/UMDF2/App/PowerFxApp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.inx b/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.inx index 4883fc286..ffdf54143 100644 Binary files a/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.inx and b/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.inx differ diff --git a/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.vcxproj b/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.vcxproj index a148bb1b7..f7c2fbe37 100644 --- a/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.vcxproj +++ b/pofx/UMDF2/Driver/SingleComp/SingleComponentSingleStateUm.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/pofx/WDF/App/PowerFxApp.vcxproj b/pofx/WDF/App/PowerFxApp.vcxproj index 2f099791a..89952032d 100644 --- a/pofx/WDF/App/PowerFxApp.vcxproj +++ b/pofx/WDF/App/PowerFxApp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.inx b/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.inx index c6c65e742..4642ce27b 100644 Binary files a/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.inx and b/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.inx differ diff --git a/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.vcxproj b/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.vcxproj index ac397edc3..fa74c7930 100644 --- a/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.vcxproj +++ b/pofx/WDF/Driver/MultiComp/driver/WdfMultiComp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/pofx/WDF/Driver/MultiComp/lib/WdfPoFx.vcxproj b/pofx/WDF/Driver/MultiComp/lib/WdfPoFx.vcxproj index eeac38591..6248d1b3a 100644 --- a/pofx/WDF/Driver/MultiComp/lib/WdfPoFx.vcxproj +++ b/pofx/WDF/Driver/MultiComp/lib/WdfPoFx.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 StaticLibrary diff --git a/pofx/WDF/Driver/SingleComp/SingleComponentFStateDriver.vcxproj b/pofx/WDF/Driver/SingleComp/SingleComponentFStateDriver.vcxproj index caf40e5da..3fa117192 100644 --- a/pofx/WDF/Driver/SingleComp/SingleComponentFStateDriver.vcxproj +++ b/pofx/WDF/Driver/SingleComp/SingleComponentFStateDriver.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/pofx/WDF/Driver/SingleComp/SingleComponentFStateSample.inx b/pofx/WDF/Driver/SingleComp/SingleComponentFStateSample.inx index 277e48282..adaa24118 100644 Binary files a/pofx/WDF/Driver/SingleComp/SingleComponentFStateSample.inx and b/pofx/WDF/Driver/SingleComp/SingleComponentFStateSample.inx differ diff --git a/pos/drivers/MagneticStripeReader/SampleMagneticStripeReaderDrv.inf b/pos/drivers/MagneticStripeReader/SampleMagneticStripeReaderDrv.inf index 44dead0a4..4257d513c 100644 Binary files a/pos/drivers/MagneticStripeReader/SampleMagneticStripeReaderDrv.inf and b/pos/drivers/MagneticStripeReader/SampleMagneticStripeReaderDrv.inf differ diff --git a/pos/drivers/barcodescanner/SampleBarcodeScannerDrv.inf b/pos/drivers/barcodescanner/SampleBarcodeScannerDrv.inf index db0c975fe..41c18afb3 100644 Binary files a/pos/drivers/barcodescanner/SampleBarcodeScannerDrv.inf and b/pos/drivers/barcodescanner/SampleBarcodeScannerDrv.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/PTPCPlPr/install/ptpcplpr.inf b/print/OEM Printer Customization Plug-in Samples/C++/PTPCPlPr/install/ptpcplpr.inf index 0f6151921..067896bd5 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/PTPCPlPr/install/ptpcplpr.inf and b/print/OEM Printer Customization Plug-in Samples/C++/PTPCPlPr/install/ptpcplpr.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/bitmap.inf b/print/OEM Printer Customization Plug-in Samples/C++/bitmap.inf index 3a13228c1..5d01b2605 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/bitmap.inf and b/print/OEM Printer Customization Plug-in Samples/C++/bitmap.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/gdl/res/gdlsmpl.inf b/print/OEM Printer Customization Plug-in Samples/C++/gdl/res/gdlsmpl.inf index 7c65f5628..8794fa8ed 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/gdl/res/gdlsmpl.inf and b/print/OEM Printer Customization Plug-in Samples/C++/gdl/res/gdlsmpl.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/oemdll.inf b/print/OEM Printer Customization Plug-in Samples/C++/oemdll.inf index d70c15680..5f49b5772 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/oemdll.inf and b/print/OEM Printer Customization Plug-in Samples/C++/oemdll.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/oemprean.inf b/print/OEM Printer Customization Plug-in Samples/C++/oemprean.inf index 6885d73a2..e2905f70a 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/oemprean.inf and b/print/OEM Printer Customization Plug-in Samples/C++/oemprean.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/uisamples.inf b/print/OEM Printer Customization Plug-in Samples/C++/uisamples.inf index aed127621..6c07b2c7b 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/uisamples.inf and b/print/OEM Printer Customization Plug-in Samples/C++/uisamples.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/uniuirep/res/uniuirep.inf b/print/OEM Printer Customization Plug-in Samples/C++/uniuirep/res/uniuirep.inf index 46ce36775..2dba999f4 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/uniuirep/res/uniuirep.inf and b/print/OEM Printer Customization Plug-in Samples/C++/uniuirep/res/uniuirep.inf differ diff --git a/print/OEM Printer Customization Plug-in Samples/C++/winxp.inf b/print/OEM Printer Customization Plug-in Samples/C++/winxp.inf index 1692dbd54..cf0ab0503 100644 Binary files a/print/OEM Printer Customization Plug-in Samples/C++/winxp.inf and b/print/OEM Printer Customization Plug-in Samples/C++/winxp.inf differ diff --git a/print/XPSDrvSmpl/install/xdsmpl.inf b/print/XPSDrvSmpl/install/xdsmpl.inf index 37a0b5696..e696a2643 100644 Binary files a/print/XPSDrvSmpl/install/xdsmpl.inf and b/print/XPSDrvSmpl/install/xdsmpl.inf differ diff --git a/print/XpsRasFilter/install/xpsrassmpl.inf b/print/XpsRasFilter/install/xpsrassmpl.inf index fbfdcf940..d080e4285 100644 Binary files a/print/XpsRasFilter/install/xpsrassmpl.inf and b/print/XpsRasFilter/install/xpsrassmpl.inf differ diff --git a/print/autoconfig/AutoCnfg.inf b/print/autoconfig/AutoCnfg.inf index 2a64ab8dd..8e0f0859f 100644 Binary files a/print/autoconfig/AutoCnfg.inf and b/print/autoconfig/AutoCnfg.inf differ diff --git a/print/v4PrintDriverSamples/v4PrintDriver-HostBasedSampleDriver/usb_host_based_sample.inf b/print/v4PrintDriverSamples/v4PrintDriver-HostBasedSampleDriver/usb_host_based_sample.inf index 7c2370315..ae7f6e05c 100644 Binary files a/print/v4PrintDriverSamples/v4PrintDriver-HostBasedSampleDriver/usb_host_based_sample.inf and b/print/v4PrintDriverSamples/v4PrintDriver-HostBasedSampleDriver/usb_host_based_sample.inf differ diff --git a/sd/miniport/sdhc/sdhc.inx b/sd/miniport/sdhc/sdhc.inx index 31e3a9642..8ae9f3035 100644 Binary files a/sd/miniport/sdhc/sdhc.inx and b/sd/miniport/sdhc/sdhc.inx differ diff --git a/security/elam/elamsample.vcxproj b/security/elam/elamsample.vcxproj index b0dcb931a..e41487958 100644 --- a/security/elam/elamsample.vcxproj +++ b/security/elam/elamsample.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/serial/VirtualSerial/ComPort/exports.def b/serial/VirtualSerial/ComPort/exports.def deleted file mode 100644 index 5d92ff036..000000000 --- a/serial/VirtualSerial/ComPort/exports.def +++ /dev/null @@ -1,6 +0,0 @@ -; exports.def : Declares the module parameters. - -LIBRARY "Virtualserial.DLL" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/serial/VirtualSerial/ComPort/virtualserial.inx b/serial/VirtualSerial/ComPort/virtualserial.inx deleted file mode 100644 index 4782e2f29..000000000 Binary files a/serial/VirtualSerial/ComPort/virtualserial.inx and /dev/null differ diff --git a/serial/VirtualSerial/ComPort/virtualserial.rc b/serial/VirtualSerial/ComPort/virtualserial.rc deleted file mode 100644 index eeda38a78..000000000 --- a/serial/VirtualSerial/ComPort/virtualserial.rc +++ /dev/null @@ -1,17 +0,0 @@ -//--------------------------------------------------------------------------- -// Virtualserial.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF VirtualSerial User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "VirtualSerial" -#define VER_ORIGINALFILENAME_STR "Virtualserial.dll" - -#include "common.ver" diff --git a/serial/VirtualSerial/ComPort/virtualserial.vcxproj b/serial/VirtualSerial/ComPort/virtualserial.vcxproj deleted file mode 100644 index 4adeded9f..000000000 --- a/serial/VirtualSerial/ComPort/virtualserial.vcxproj +++ /dev/null @@ -1,250 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184} - $(MSBuildProjectName) - 1 - Debug - Win32 - {A88B1CA4-202D-4915-94D1-94E8D74FCFF5} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - ..\internal.h - - - true - true - ..\internal.h - - - - virtualserial - - - virtualserial - - - virtualserial - - - virtualserial - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/serial/VirtualSerial/ComPort/virtualserial.vcxproj.Filters b/serial/VirtualSerial/ComPort/virtualserial.vcxproj.Filters deleted file mode 100644 index d8da803f8..000000000 --- a/serial/VirtualSerial/ComPort/virtualserial.vcxproj.Filters +++ /dev/null @@ -1,49 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {FD27BABE-0C58-4B98-AF81-08289AA3B68B} - - - h;hpp;hxx;hm;inl;inc;xsd - {F310CB18-6DEC-47F7-8CA0-21A1439D1363} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {52CDBF35-D541-4FFF-A0C5-8C8189885A23} - - - inf;inv;inx;mof;mc; - {51F65D19-3BDF-4759-9AD1-DDA85ACA2524} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/serial/VirtualSerial/FakeModem/exports.def b/serial/VirtualSerial/FakeModem/exports.def deleted file mode 100644 index 48845d0c1..000000000 --- a/serial/VirtualSerial/FakeModem/exports.def +++ /dev/null @@ -1,6 +0,0 @@ -; exports.def : Declares the module parameters. - -LIBRARY "FakeModem.DLL" - -EXPORTS - DllGetClassObject PRIVATE diff --git a/serial/VirtualSerial/FakeModem/fakemodem.inx b/serial/VirtualSerial/FakeModem/fakemodem.inx deleted file mode 100644 index a57b63144..000000000 Binary files a/serial/VirtualSerial/FakeModem/fakemodem.inx and /dev/null differ diff --git a/serial/VirtualSerial/FakeModem/fakemodem.rc b/serial/VirtualSerial/FakeModem/fakemodem.rc deleted file mode 100644 index 6bb6ed962..000000000 --- a/serial/VirtualSerial/FakeModem/fakemodem.rc +++ /dev/null @@ -1,17 +0,0 @@ -//--------------------------------------------------------------------------- -// FakeModem.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF Fake Modem User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "FakeModem" -#define VER_ORIGINALFILENAME_STR "FakeModem.dll" - -#include "common.ver" diff --git a/serial/VirtualSerial/FakeModem/fakemodem.vcxproj b/serial/VirtualSerial/FakeModem/fakemodem.vcxproj deleted file mode 100644 index fb0caada4..000000000 --- a/serial/VirtualSerial/FakeModem/fakemodem.vcxproj +++ /dev/null @@ -1,250 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {ACC7F2B5-F886-4169-84C0-32E44847E2B3} - $(MSBuildProjectName) - 1 - Debug - Win32 - {632318C9-FA2B-44A3-BB8C-3ADC5F2E2A86} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - ..\internal.h - - - true - true - ..\internal.h - - - - fakemodem - - - fakemodem - - - fakemodem - - - fakemodem - - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_FAKE_MODEM=1;_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\ntdll.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\Ole32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/serial/VirtualSerial/FakeModem/fakemodem.vcxproj.Filters b/serial/VirtualSerial/FakeModem/fakemodem.vcxproj.Filters deleted file mode 100644 index 52ccc10a3..000000000 --- a/serial/VirtualSerial/FakeModem/fakemodem.vcxproj.Filters +++ /dev/null @@ -1,49 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {1F2A9E59-0673-4608-95E9-CF60343773E6} - - - h;hpp;hxx;hm;inl;inc;xsd - {10F80ED7-1AD5-4B8B-B840-DE4146B936E1} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {AA21B933-B73E-406C-AD32-1EC06E712F89} - - - inf;inv;inx;mof;mc; - {842CBD81-76BE-44AA-80B7-0BE49BE0DE56} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/serial/VirtualSerial/README.md b/serial/VirtualSerial/README.md deleted file mode 100644 index 3eeb97642..000000000 --- a/serial/VirtualSerial/README.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -page_type: sample -description: "Demonstrates a simple virtual serial driver (ComPort) and a controller-less modem driver (FakeModem)." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Virtual serial driver sample - -This sample demonstrates these two serial drivers: - -- A simple virtual serial driver (ComPort) - -- A controller-less modem driver (FakeModem).This driver supports sending and receiving AT commands using the ReadFile and WriteFile calls or via a TAPI interface using an application such as, HyperTerminal. - -This sample driver is a minimal driver meant to demonstrate the usage of the User-Mode Driver Framework. It is not intended for use in a production environment. - -For more information, see the [Serial Controller Driver Design Guide](https://docs.microsoft.com/windows-hardware/drivers/serports/). - -## Code tour - -### comsup.cpp and comsup.h - -- COM Support code - specifically base classes which provide implementations for the standard COM interfaces **IUnknown** and **IClassFactory** which are used throughout the sample. - -- The implementation of **IClassFactory** is designed to create instances of the CMyDriver class. If you should change the name of your base driver class, you would also need to modify this file. - -### dllsup.cpp - -- DLL Support code - provides the DLL's entry point as well as the single required export (**DllGetClassObject**). - -- These depend on comsup.cpp to perform the necessary class creation. - -### exports.def - -- This file lists the functions that the driver DLL exports. - -### internal.h - -- This is the main header file for the sample driver. - -### driver.cpp and driver.h - -- Definition and implementation of the driver callback class (CMyDriver) for the sample. This includes **DriverEntry** and events on the framework driver object. - -### device.cpp and driver.h - -- Definition and implementation of the device callback class (CMyDriver) for the sample. This includes events on the framework device object. - -### queue.cpp and queue.h - -- Definition and implementation of the base queue callback class (CMyQueue). This includes events on the framework I/O queue object. - -### VirtualSerial.rc /FakeModem.rc - -- This file defines resource information for the sample driver. - -### VirtualSerial.inf / FakeModem.inf - -- INF file that contains installation information for this driver. diff --git a/serial/VirtualSerial/VirtualSerial.sln b/serial/VirtualSerial/VirtualSerial.sln deleted file mode 100644 index 8ca42edbd..000000000 --- a/serial/VirtualSerial/VirtualSerial.sln +++ /dev/null @@ -1,46 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComPort", "ComPort", "{56318356-CB41-44F9-9830-F051C326B8C2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FakeModem", "FakeModem", "{209B0D63-1DB3-4114-9531-FCBDE7CE1B5C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "virtualserial", "ComPort\virtualserial.vcxproj", "{CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fakemodem", "FakeModem\fakemodem.vcxproj", "{ACC7F2B5-F886-4169-84C0-32E44847E2B3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Debug|Win32.ActiveCfg = Debug|Win32 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Debug|Win32.Build.0 = Debug|Win32 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Release|Win32.ActiveCfg = Release|Win32 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Release|Win32.Build.0 = Release|Win32 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Debug|x64.ActiveCfg = Debug|x64 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Debug|x64.Build.0 = Debug|x64 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Release|x64.ActiveCfg = Release|x64 - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184}.Release|x64.Build.0 = Release|x64 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Debug|Win32.ActiveCfg = Debug|Win32 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Debug|Win32.Build.0 = Debug|Win32 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Release|Win32.ActiveCfg = Release|Win32 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Release|Win32.Build.0 = Release|Win32 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Debug|x64.ActiveCfg = Debug|x64 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Debug|x64.Build.0 = Debug|x64 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Release|x64.ActiveCfg = Release|x64 - {ACC7F2B5-F886-4169-84C0-32E44847E2B3}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {CF30C8F0-084B-4E2D-A9C3-E76B4E9D0184} = {56318356-CB41-44F9-9830-F051C326B8C2} - {ACC7F2B5-F886-4169-84C0-32E44847E2B3} = {209B0D63-1DB3-4114-9531-FCBDE7CE1B5C} - EndGlobalSection -EndGlobal diff --git a/serial/VirtualSerial/comsup.cpp b/serial/VirtualSerial/comsup.cpp deleted file mode 100644 index fd2984700..000000000 --- a/serial/VirtualSerial/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/serial/VirtualSerial/comsup.h b/serial/VirtualSerial/comsup.h deleted file mode 100644 index a73938b6e..000000000 --- a/serial/VirtualSerial/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/serial/VirtualSerial/device.cpp b/serial/VirtualSerial/device.cpp deleted file mode 100644 index 11d477751..000000000 --- a/serial/VirtualSerial/device.cpp +++ /dev/null @@ -1,674 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF VirtualSerial sample - driver's device callback object. - - The VirtualSerial sample device does very little. It does not implement - either of the PNP interfaces so once the device is setup, it won't ever get - any callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the VirtualSerial driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - FxDeviceInit->SetLockingConstraint(WdfDeviceLevel); - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - IWDFPropertyStoreFactory *pPropertyStoreFactory = NULL; - IWDFNamedPropertyStore2 * pHardwarePropertyStore = NULL; - IWDFNamedPropertyStore2 * pLegacyHardwarePropertyStore = NULL; - WDF_PROPERTY_STORE_ROOT RootSpecifier; - PROPVARIANT comPortPV; - WCHAR portName[] = L"PortName"; - size_t comPortSuffixCch = 0; - WCHAR *comPortFullName = NULL; - size_t comPortFullNameCch = 0; - WCHAR *pdoName = NULL; - PCMyQueue defaultQueue; - -#ifdef _FAKE_MODEM - // - // Compiled as fake modem - // - LPGUID pGuid = (LPGUID) &GUID_DEVINTERFACE_MODEM; -#else - // - // Compiled as virtual serial port - // - LPGUID pGuid = (LPGUID) &GUID_DEVINTERFACE_COMPORT; -#endif - - HRESULT hr; - - PropVariantInit(&comPortPV); - - // - // Create device interface - // - hr = m_FxDevice->CreateDeviceInterface(pGuid, - NULL); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Cannot create device interface (%!GUID!)", - pGuid - ); - - goto Exit; - } - - hr = m_FxDevice->AssignDeviceInterfaceState(pGuid, - NULL, - TRUE); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Cannot enable device interface (%!GUID!)", - pGuid - ); - - goto Exit; - } - - // - // Create Symbolic Link - // - - // - // First we need to read the COM number from the registry - // - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pPropertyStoreFactory)); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: QI for IWDFPropertyStoreFactory failed" - ); - - goto Exit; - } - - RootSpecifier.LengthCb = sizeof(WDF_PROPERTY_STORE_ROOT); - RootSpecifier.RootClass = WdfPropertyStoreRootClassHardwareKey; - RootSpecifier.Qualifier.HardwareKey.ServiceName = - WDF_PROPERTY_STORE_HARDWARE_KEY_ROOT; - - hr = pPropertyStoreFactory->RetrieveDevicePropertyStore( - &RootSpecifier, - WdfPropertyStoreNormal, - KEY_QUERY_VALUE, - NULL, - &pHardwarePropertyStore, - NULL - ); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to retrieve device hardware key root" - ); - goto Exit; - } - - hr = pHardwarePropertyStore->GetNamedValue(portName, &comPortPV); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to read value %ws", - portName - ); - goto Exit; - } - - // - // Then we need to construct the COM port name - // - hr = StringCchLength(comPortPV.pwszVal, - STRSAFE_MAX_CCH, - &comPortSuffixCch); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Overflow while calculating COM port suffix length" - ); - goto Exit; - } - - hr = SizeTAdd(ARRAYSIZE(SYMBOLIC_LINK_NAME_PREFIX), - comPortSuffixCch, - &comPortFullNameCch); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Overflow while calculating symbolic link length" - ); - goto Exit; - } - - comPortFullName = (WCHAR*) new WCHAR[comPortFullNameCch]; - - if (NULL == comPortFullName) - { - hr = E_OUTOFMEMORY; - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Unable to allocate memory for full port name" - ); - goto Exit; - } - - hr = StringCchPrintf(comPortFullName, - comPortFullNameCch, - L"%ws%ws", - SYMBOLIC_LINK_NAME_PREFIX, - comPortPV.pwszVal); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Cannot create full name for COM port" - ); - goto Exit; - } - - // - // Finally we create the symbolic link - // - hr = m_FxDevice->CreateSymbolicLink(comPortFullName); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Cannot create symbolic link %ws", - comPortFullName - ); - goto Exit; - } - - // - // Write the com name to the legacy hardware key - // - hr = GetPdoName(&pdoName); - - if (FAILED(hr) || (pdoName == NULL)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Cannot retrieve PDO name" - ); - goto Exit; - } - - // - // Write the name to the legacy hardware key - // - RootSpecifier.LengthCb = sizeof(WDF_PROPERTY_STORE_ROOT); - RootSpecifier.RootClass = WdfPropertyStoreRootClassLegacyHardwareKey; - RootSpecifier.Qualifier.LegacyHardwareKey.LegacyMapName = L"SERIALCOMM"; - - hr = pPropertyStoreFactory->RetrieveDevicePropertyStore( - &RootSpecifier, - WdfPropertyStoreCreateVolatile, - KEY_SET_VALUE, - NULL, - &pLegacyHardwarePropertyStore, - NULL - ); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to retrieve device legacy hardware key" - ); - goto Exit; - } - - hr = pLegacyHardwarePropertyStore->SetNamedValue(pdoName, - &comPortPV); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to write device name to legacy hardware key" - ); - goto Exit; - } - - m_CreatedLegacyHardwareKey = TRUE; - m_LegacyHardwarePropertyStore = pLegacyHardwarePropertyStore; - m_PdoName = pdoName; - - // - // Create and configure the queues - // - hr = CMyQueue::CreateInstance(this, m_FxDevice, &defaultQueue); - - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Failed to create default queue" - ); - goto Exit; - } - - defaultQueue->Release(); - - -Exit: - - if (m_CreatedLegacyHardwareKey == FALSE) - { - // - // If the legacy hardware key has been written, then the cleanup - // will happen, when the device is unloaded - // - SAFE_RELEASE(pLegacyHardwarePropertyStore); - if (pdoName != NULL) - { - delete[] pdoName; - } - } - - SAFE_RELEASE(pHardwarePropertyStore); - SAFE_RELEASE(pPropertyStoreFactory); - - PropVariantClear(&comPortPV); - - if (comPortFullName != NULL) - { - delete[] comPortFullName; - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if(IsEqualIID(InterfaceId, __uuidof(IObjectCleanup))) - { - *Object = QueryIObjectCleanup(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -VOID -CMyDevice::OnCleanup( - IWDFObject* pWdfObject -) -{ - UNREFERENCED_PARAMETER(pWdfObject); - - if ((m_CreatedLegacyHardwareKey == TRUE) && - (m_LegacyHardwarePropertyStore != NULL)) - { - m_LegacyHardwarePropertyStore->DeleteNamedValue(m_PdoName); - SAFE_RELEASE(m_LegacyHardwarePropertyStore); - delete[] m_PdoName; - } -} - -HRESULT -CMyDevice::GetPdoName( - _Out_ LPWSTR *PdoName - ) -{ - HRESULT hr = S_OK; - WCHAR *devInstId = NULL; - ULONG devInstIdLen; - HDEVINFO hDevInfoSet = INVALID_HANDLE_VALUE; - SP_DEVINFO_DATA devInfoData; - WCHAR *pdoName = NULL; - DWORD pdoNameCb = 0; - - WUDF_TEST_DRIVER_ASSERT(m_FxDevice); - - // - // First let's get the device instance ID - // - devInstIdLen = 0; - hr = m_FxDevice->RetrieveDeviceInstanceId(NULL, &devInstIdLen); - if (SUCCEEDED(hr)) - { - devInstId = (WCHAR*) new WCHAR[devInstIdLen]; - if (NULL == devInstId) - { - hr = E_OUTOFMEMORY; - } - } - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceInstanceId(devInstId, &devInstIdLen); - } - - // - // Now use the SetupDiXxx functions to get a handle to the device's - // hardware key - // - if (SUCCEEDED(hr)) - { - // - // Create a new device information set - // - hDevInfoSet = SetupDiCreateDeviceInfoList(NULL, NULL); - if (INVALID_HANDLE_VALUE == hDevInfoSet) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - - if (SUCCEEDED(hr)) - { - // - // Add our device to this device information set - // - ZeroMemory(&devInfoData, sizeof(devInfoData)); - devInfoData.cbSize = sizeof(devInfoData); - if (!SetupDiOpenDeviceInfo(hDevInfoSet, - devInstId, - NULL, - 0, - &devInfoData)) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - - if (SUCCEEDED(hr)) - { - // - // Get the length of the PDO name - // - if (!SetupDiGetDeviceRegistryProperty(hDevInfoSet, - &devInfoData, - SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, - NULL, - (PBYTE)pdoName, - 0, - &pdoNameCb)) - { - // - // The only reason for this call is to get the length of the - // buffer. The only non acceptable reason for failure is, if we - // asked for invalid data. - // - if (GetLastError() == ERROR_INVALID_DATA) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - } - - // - // Get the PDO name - // - if (SUCCEEDED(hr)) - { - pdoName = (WCHAR *)new BYTE[pdoNameCb]; - - if (pdoName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - if (SUCCEEDED(hr)) - { - if (!SetupDiGetDeviceRegistryProperty(hDevInfoSet, - &devInfoData, - SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, - NULL, - (PBYTE)pdoName, - pdoNameCb, - NULL)) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - - } - - if (SUCCEEDED(hr)) - { - *PdoName = pdoName; - } - - // - // clean up to be done regardless of success or failure - // - if (NULL != devInstId) - { - delete[] devInstId; - } - - if (INVALID_HANDLE_VALUE != hDevInfoSet) - { - SetupDiDestroyDeviceInfoList(hDevInfoSet); - } - - // - // clean up to be done in case of failure only - // - if (FAILED(hr)) - { - if (NULL != pdoName) - { - delete[] pdoName; - pdoName = NULL; - } - } - - return hr; -} diff --git a/serial/VirtualSerial/device.h b/serial/VirtualSerial/device.h deleted file mode 100644 index 1fc54aeb0..000000000 --- a/serial/VirtualSerial/device.h +++ /dev/null @@ -1,261 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF VirtualSerial sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "initguid.h" -#include "serial.h" - -DEFINE_GUID(GUID_DEVINTERFACE_MODEM, 0x2c7089aa, 0x2e0e, 0x11d1, 0xb1, 0x14, 0x00, 0xc0, 0x4f, 0xc2, 0xaa, 0xe4); -DEFINE_GUID(GUID_DEVINTERFACE_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73); - -#define SYMBOLIC_LINK_NAME_PREFIX L"\\DosDevices\\Global\\" - -// -// Class for the VirtualSerial driver. -// - -class CMyDevice : - public CUnknown, - public IObjectCleanup -{ - -// -// Private data members. -// -private: - - IWDFDevice *m_FxDevice; - - // - // Baud rate - // - ULONG m_BaudRate; - - // - // Modem control register - // - ULONG m_MCR; - - // - // FIFO control register - // - ULONG m_FCR; - - // - // Line control register - // - ULONG m_LCR; - - // - // Valid data mask - // - UCHAR m_ValidDataMask; - - // - // Timeouts - // - SERIAL_TIMEOUTS m_Timeouts; - - // - // Legacy hardware key property store - // - BOOL m_CreatedLegacyHardwareKey; - - IWDFNamedPropertyStore2 * m_LegacyHardwarePropertyStore; - - PWCHAR m_PdoName; -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_BaudRate(0), - m_MCR(0), - m_FCR(0), - m_LCR(0), - m_ValidDataMask(0), - m_CreatedLegacyHardwareKey(FALSE), - m_LegacyHardwarePropertyStore(NULL), - m_PdoName(NULL) - { - ZeroMemory(&m_Timeouts, sizeof(SERIAL_TIMEOUTS)); - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - HRESULT - CMyDevice::GetPdoName( - _Out_ LPWSTR *PdoName - ); -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IObjectCleanup - // - IObjectCleanup * - QueryIObjectCleanup( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - virtual - void - STDMETHODCALLTYPE - OnCleanup( - IWDFObject* pWdfObject - ); - - - ULONG - GetBaudRate( - VOID - ) - { - return m_BaudRate; - } - - void - SetBaudRate( - _In_ ULONG BaudRate - ) - { - m_BaudRate = BaudRate; - - return; - } - - ULONG * - GetModemControlRegisterPtr( - VOID - ) - { - return &m_MCR; - } - - ULONG * - GetFifoControlRegisterPtr( - VOID - ) - { - return &m_FCR; - } - - ULONG * - GetLineControlRegisterPtr( - VOID - ) - { - return &m_LCR; - } - - VOID - SetValidDataMask( - _In_ UCHAR Mask - ) - { - m_ValidDataMask = Mask; - } - - VOID - SetTimeouts( - _In_ SERIAL_TIMEOUTS Timeouts - ) - { - m_Timeouts = Timeouts; - } - - VOID - GetTimeouts( - _Out_ SERIAL_TIMEOUTS *Timeouts - ) - { - *Timeouts = m_Timeouts;; - } - -}; diff --git a/serial/VirtualSerial/dllsup.cpp b/serial/VirtualSerial/dllsup.cpp deleted file mode 100644 index 6c2540853..000000000 --- a/serial/VirtualSerial/dllsup.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF VirtualSerial Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example, VirtualSerial uses - L"Microsoft\\UMDF\\VirtualSerial" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - UNREFERENCED_PARAMETER( ModuleHandle ); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -HRESULT -STDAPICALLTYPE -DllGetClassObject( - _In_ REFCLSID ClassId, - _In_ REFIID InterfaceId, - _Outptr_ LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/serial/VirtualSerial/driver.cpp b/serial/VirtualSerial/driver.cpp deleted file mode 100644 index 0ec28ec5f..000000000 --- a/serial/VirtualSerial/driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF VirtualSerial Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/serial/VirtualSerial/driver.h b/serial/VirtualSerial/driver.h deleted file mode 100644 index 5be609b19..000000000 --- a/serial/VirtualSerial/driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF VirtualSerial sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the VirtualSerial sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER( FxWdfDriver ); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/serial/VirtualSerial/internal.h b/serial/VirtualSerial/internal.h deleted file mode 100644 index dd89de21c..000000000 --- a/serial/VirtualSerial/internal.h +++ /dev/null @@ -1,133 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF VirtualSerial - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#include -#include -#include -#include -#include -#include - -// -// Include the WUDF DDI -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; -typedef class CRingBuffer *PCMyRingBuffer; - -// -// Define useful macros -// - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} - -// -// Define the tracing flags. -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (C31877A2,C8C8,4c58,B5B8,7D6311D5E343), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\VirtualSerial" -#define MYDRIVER_CLASS_ID { 0xc8ecc087, 0x6b79, 0x4de5, { 0x8f, 0xb4, 0xc0, 0x33, 0x58, 0xa2, 0x96, 0x17 } } - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define MAXULONG 0xffffffff - -// -// Device states -// -#define COMMAND_MATCH_STATE_IDLE 0 -#define COMMAND_MATCH_STATE_GOT_A 1 -#define COMMAND_MATCH_STATE_GOT_T 2 - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "ringbuffer.h" -#include "queue.h" -#include "serial.h" diff --git a/serial/VirtualSerial/queue.cpp b/serial/VirtualSerial/queue.cpp deleted file mode 100644 index 5a7b5bad1..000000000 --- a/serial/VirtualSerial/queue.cpp +++ /dev/null @@ -1,1188 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - - -#include "internal.h" - -// -// IUnknown implementation -// - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// delete critical section. -// - - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Arguments: - - -Return Value: - ---*/ -{ - WUDF_TEST_DRIVER_ASSERT(m_Device); - - m_Device->Release(); -} - - -// -// Initialize -HRESULT -CMyQueue::CreateInstance( - _In_ CMyDevice *pDevice, - _In_ IWDFDevice *FxDevice, - _Out_ PCMyQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Arguments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicating success or failure - ---*/ -{ - CMyQueue *pMyQueue = new CMyQueue(pDevice); - HRESULT hr; - - if (pMyQueue == NULL) { - return E_OUTOFMEMORY; - } - - hr = pMyQueue->Initialize(FxDevice); - - if (SUCCEEDED(hr)) - { - *Queue = pMyQueue; - } - else - { - pMyQueue->Release(); - } - return hr; -} - -HRESULT -CMyQueue::Initialize( - _In_ IWDFDevice *FxDevice - ) -{ - IWDFIoQueue *fxQueue; - IUnknown *unknown = NULL; - HRESULT hr; - - // - // Initialize ring buffer - // - - hr = m_RingBuffer.Initialize(DATA_BUFFER_SIZE); - - if (FAILED(hr)) - { - goto Exit; - } - - unknown = QueryIUnknown(); - - // - // Create the default queue - // - - { - hr = FxDevice->CreateIoQueue(unknown, - TRUE, - WdfIoQueueDispatchParallel, - TRUE, - FALSE, - &fxQueue); - } - - if (FAILED(hr)) - { - goto Exit; - } - - m_FxQueue = fxQueue; - - fxQueue->Release(); - - // - // Create a manual queue to hold pending read requests. By keeping - // them in the queue, framework takes care of cancelling them if the app - // exits - // - - { - hr = FxDevice->CreateIoQueue(NULL, - FALSE, - WdfIoQueueDispatchManual, - TRUE, - FALSE, - &fxQueue); - } - - if (FAILED(hr)) - { - goto Exit; - } - - m_FxReadQueue = fxQueue; - - fxQueue->Release(); - - // - // Create a manual queue to hold pending ioctl wait-on-mask requests. - // - - { - hr = FxDevice->CreateIoQueue(NULL, - FALSE, - WdfIoQueueDispatchManual, - TRUE, - FALSE, - &fxQueue); - } - - if (FAILED(hr)) - { - goto Exit; - } - - m_FxWaitMaskQueue = fxQueue; - - fxQueue->Release(); - -Exit: - SAFE_RELEASE(unknown); - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Arguments: - - Follows COM specifications - -Return Value: - - HRESULT indicating success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) { - *Object = QueryIQueueCallbackWrite(); - hr = S_OK; - } else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackRead))) { - *Object = QueryIQueueCallbackRead(); - hr = S_OK; - } else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) { - *Object = QueryIQueueCallbackDeviceIoControl(); - hr = S_OK; - } else { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Length of input buffer - OutputBufferSizeInBytes - Length of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(OutputBufferSizeInBytes); - UNREFERENCED_PARAMETER(InputBufferSizeInBytes); - UNREFERENCED_PARAMETER(pWdfQueue); - - HRESULT hr = S_OK; - SIZE_T reqCompletionInfo = 0; - IWDFMemory *inputMemory = NULL; - IWDFMemory *outputMemory = NULL; - UINT i; - - WUDF_TEST_DRIVER_ASSERT(pWdfRequest); - WUDF_TEST_DRIVER_ASSERT(m_Device); - - switch (ControlCode) - { - case IOCTL_SERIAL_SET_BAUD_RATE: - { - // - // This is a driver for a virtual serial port. Since there is no - // actual hardware, we just store the baud rate and don't do - // anything with it. - // - SERIAL_BAUD_RATE baudRateBuffer = {0}; - - pWdfRequest->GetInputMemory(&inputMemory); - if (NULL == inputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - hr = inputMemory->CopyToBuffer(0, - (void*) &baudRateBuffer, - sizeof(SERIAL_BAUD_RATE)); - } - - if (SUCCEEDED(hr)) - { - m_Device->SetBaudRate(baudRateBuffer.BaudRate); - } - - break; - } - case IOCTL_SERIAL_GET_BAUD_RATE: - { - SERIAL_BAUD_RATE baudRateBuffer = {0}; - - baudRateBuffer.BaudRate = m_Device->GetBaudRate(); - - pWdfRequest->GetOutputMemory(&outputMemory); - if (NULL == outputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - hr = outputMemory->CopyFromBuffer(0, - (void*) &baudRateBuffer, - sizeof(SERIAL_BAUD_RATE)); - } - - if (SUCCEEDED(hr)) - { - reqCompletionInfo = sizeof(SERIAL_BAUD_RATE); - } - - break; - } - case IOCTL_SERIAL_SET_MODEM_CONTROL: - { - // - // This is a driver for a virtual serial port. Since there is no - // actual hardware, we just store the modem control register - // configuration and don't do anything with it. - // - ULONG *pModemControlRegister = NULL; - - pWdfRequest->GetInputMemory(&inputMemory); - if (NULL == inputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - pModemControlRegister = m_Device->GetModemControlRegisterPtr(); - WUDF_TEST_DRIVER_ASSERT(pModemControlRegister); - - hr = inputMemory->CopyToBuffer(0, - (void*) pModemControlRegister, - sizeof(ULONG)); - } - - break; - } - case IOCTL_SERIAL_GET_MODEM_CONTROL: - { - ULONG *pModemControlRegister = NULL; - - pWdfRequest->GetOutputMemory(&outputMemory); - if (NULL == outputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - pModemControlRegister = m_Device->GetModemControlRegisterPtr(); - WUDF_TEST_DRIVER_ASSERT(pModemControlRegister); - - hr = outputMemory->CopyFromBuffer(0, - (void*) pModemControlRegister, - sizeof(ULONG)); - } - - if (SUCCEEDED(hr)) - { - reqCompletionInfo = sizeof(ULONG); - } - - break; - } - case IOCTL_SERIAL_SET_FIFO_CONTROL: - { - // - // This is a driver for a virtual serial port. Since there is no - // actual hardware, we just store the FIFO control register - // configuration and don't do anything with it. - // - ULONG *pFifoControlRegister = NULL; - - pWdfRequest->GetInputMemory(&inputMemory); - if (NULL == inputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - pFifoControlRegister = m_Device->GetFifoControlRegisterPtr(); - - hr = inputMemory->CopyToBuffer(0, - (void*) pFifoControlRegister, - sizeof(ULONG)); - } - - break; - } - case IOCTL_SERIAL_GET_LINE_CONTROL: - { - ULONG *pLineControlRegister = NULL; - SERIAL_LINE_CONTROL lineControl = {0}; - ULONG lineControlSnapshot; - - pLineControlRegister = m_Device->GetLineControlRegisterPtr(); - WUDF_TEST_DRIVER_ASSERT(pLineControlRegister); - - // - // Take a snapshot of the line control register variable - // - lineControlSnapshot = *pLineControlRegister; - - // - // Decode the word length - // - if ((lineControlSnapshot & SERIAL_DATA_MASK) == SERIAL_5_DATA) - { - lineControl.WordLength = 5; - } - else if ((lineControlSnapshot & SERIAL_DATA_MASK) == SERIAL_6_DATA) - { - lineControl.WordLength = 6; - } - else if ((lineControlSnapshot & SERIAL_DATA_MASK) == SERIAL_7_DATA) - { - lineControl.WordLength = 7; - } - else if ((lineControlSnapshot & SERIAL_DATA_MASK) == SERIAL_8_DATA) - { - lineControl.WordLength = 8; - } - - // - // Decode the parity - // - if ((lineControlSnapshot & SERIAL_PARITY_MASK) == SERIAL_NONE_PARITY) - { - lineControl.Parity = NO_PARITY; - } - else if ((lineControlSnapshot & SERIAL_PARITY_MASK) == SERIAL_ODD_PARITY) - { - lineControl.Parity = ODD_PARITY; - } - else if ((lineControlSnapshot & SERIAL_PARITY_MASK) == SERIAL_EVEN_PARITY) - { - lineControl.Parity = EVEN_PARITY; - } - else if ((lineControlSnapshot & SERIAL_PARITY_MASK) == SERIAL_MARK_PARITY) - { - lineControl.Parity = MARK_PARITY; - } - else if ((lineControlSnapshot & SERIAL_PARITY_MASK) == SERIAL_SPACE_PARITY) - { - lineControl.Parity = SPACE_PARITY; - } - - // - // Decode the length of the stop bit - // - if (lineControlSnapshot & SERIAL_2_STOP) - { - if (lineControl.WordLength == 5) - { - lineControl.StopBits = STOP_BITS_1_5; - } - else - { - lineControl.StopBits = STOP_BITS_2; - } - } - else - { - lineControl.StopBits = STOP_BIT_1; - } - - // - // Copy the information that was decoded to the caller's buffer - // - pWdfRequest->GetOutputMemory(&outputMemory); - if (NULL == outputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - hr = outputMemory->CopyFromBuffer(0, - (void*) &lineControl, - sizeof(SERIAL_LINE_CONTROL)); - } - - if (SUCCEEDED(hr)) - { - reqCompletionInfo = sizeof(SERIAL_LINE_CONTROL); - } - - break; - } - case IOCTL_SERIAL_SET_LINE_CONTROL: - { - ULONG *pLineControlRegister = NULL; - SERIAL_LINE_CONTROL lineControl = {0}; - UCHAR lineControlData = 0; - UCHAR lineControlStop = 0; - UCHAR lineControlParity = 0; - ULONG lineControlSnapshot; - ULONG lineControlNew; - ULONG lineControlPrevious; - - pLineControlRegister = m_Device->GetLineControlRegisterPtr(); - WUDF_TEST_DRIVER_ASSERT(pLineControlRegister); - - // - // This is a driver for a virtual serial port. Since there is no - // actual hardware, we just store the line control register - // configuration and don't do anything with it. - // - pWdfRequest->GetInputMemory(&inputMemory); - if (NULL == inputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - hr = inputMemory->CopyToBuffer(0, - (void*) &lineControl, - sizeof(SERIAL_LINE_CONTROL)); - } - - // - // Bits 0 and 1 of the line control register - // - if (SUCCEEDED(hr)) - { - switch (lineControl.WordLength) - { - case 5: - lineControlData = SERIAL_5_DATA; - m_Device->SetValidDataMask(0x1f); - break; - - case 6: - lineControlData = SERIAL_6_DATA; - m_Device->SetValidDataMask(0x3f); - break; - - case 7: - lineControlData = SERIAL_7_DATA; - m_Device->SetValidDataMask(0x7f); - break; - - case 8: - lineControlData = SERIAL_8_DATA; - m_Device->SetValidDataMask(0xff); - break; - - default: - hr = E_INVALIDARG; - } - } - - // - // Bit 2 of the line control register - // - if (SUCCEEDED(hr)) - { - switch (lineControl.StopBits) - { - case STOP_BIT_1: - lineControlStop = SERIAL_1_STOP; - break; - - case STOP_BITS_1_5: - if (lineControlData != SERIAL_5_DATA) - { - hr = E_INVALIDARG; - break; - } - lineControlStop = SERIAL_1_5_STOP; - break; - - case STOP_BITS_2: - if (lineControlData == SERIAL_5_DATA) - { - hr = E_INVALIDARG; - break; - } - lineControlStop = SERIAL_2_STOP; - break; - - default: - hr = E_INVALIDARG; - } - } - - // - // Bits 3, 4 and 5 of the line control register - // - if (SUCCEEDED(hr)) - { - switch (lineControl.Parity) - { - case NO_PARITY: - lineControlParity = SERIAL_NONE_PARITY; - break; - - case EVEN_PARITY: - lineControlParity = SERIAL_EVEN_PARITY; - break; - - case ODD_PARITY: - lineControlParity = SERIAL_ODD_PARITY; - break; - - case SPACE_PARITY: - lineControlParity = SERIAL_SPACE_PARITY; - break; - - case MARK_PARITY: - lineControlParity = SERIAL_MARK_PARITY; - break; - - default: - hr = E_INVALIDARG; - } - } - - // - // Update our line control register variable atomically - // - i=0; - do - { - i++; - if ((i & 0xf) == 0) - { - // - // We've been spinning in a loop for a while trying to - // update the line control register variable atomically. - // Yield the CPU for other threads for a while. - // - SwitchToThread(); - } - - lineControlSnapshot = *pLineControlRegister; - - lineControlNew = (lineControlSnapshot & SERIAL_LCR_BREAK) | - (lineControlData | - lineControlParity | - lineControlStop); - - lineControlPrevious = InterlockedCompareExchange((LONG *) pLineControlRegister, - lineControlNew, - lineControlSnapshot); - - } while (lineControlPrevious != lineControlSnapshot); - - break; - } - case IOCTL_SERIAL_GET_TIMEOUTS: - { - SERIAL_TIMEOUTS timeoutValues = {0}; - - pWdfRequest->GetOutputMemory(&outputMemory); - if (NULL == outputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - m_Device->GetTimeouts(&timeoutValues); - - hr = outputMemory->CopyFromBuffer(0, - (void*) &timeoutValues, - sizeof(timeoutValues)); - } - - if (SUCCEEDED(hr)) - { - reqCompletionInfo = sizeof(SERIAL_TIMEOUTS); - } - - break; - } - case IOCTL_SERIAL_SET_TIMEOUTS: - { - SERIAL_TIMEOUTS timeoutValues = {0}; - - pWdfRequest->GetInputMemory(&inputMemory); - if (NULL == inputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - hr = inputMemory->CopyToBuffer(0, - (void*) &timeoutValues, - sizeof(timeoutValues)); - } - - if (SUCCEEDED(hr)) - { - if ((timeoutValues.ReadIntervalTimeout == MAXULONG) && - (timeoutValues.ReadTotalTimeoutMultiplier == MAXULONG) && - (timeoutValues.ReadTotalTimeoutConstant == MAXULONG)) - { - hr = E_INVALIDARG; - } - } - - if (SUCCEEDED(hr)) - { - m_Device->SetTimeouts(timeoutValues); - } - - break; - } - case IOCTL_SERIAL_WAIT_ON_MASK: - { - // - // NOTE: the contract is that this ioctl should be marked pending - // and not to be completed until some wait event happens. Therefore - // it is incorrect for the driver to complete the ioctl right away, - // no matter whether success or failure is returned. In either case - // most likely the app will send down another iocl of wait-on-mask - // in a tight loop, and that gets completed again, and again. - // The end result will be high CPU utilization in task manager. - // - // The correct way would be to mark the ioctl as pending, or as in - // WDF world, keep it in a manual queue. Since this is a driver for - // a virtual serial port and there is no actual hardware, there will - // be no wait event happening. The ioctl stays in the queue until - // the calling app decides to no longer wait for it by means of - // sending down a set-wait-mask request. - // - - // - // At most one pending wait-on-mask request is expected - // - IWDFIoRequest *pSavedRequest; - hr = m_FxWaitMaskQueue->RetrieveNextRequest(&pSavedRequest); - if (SUCCEEDED(hr)) - { - pSavedRequest->Complete(E_FAIL); - - // - // RetrieveNextRequest from a manual queue increments the reference - // counter by 1. We need to decrement it, otherwise the request will - // not be released and there will be an object leak. - // - SAFE_RELEASE(pSavedRequest); - } - - // - // Keep the request in a manual queue and the framework will take - // care of cancelling them when the app exits. - // - pWdfRequest->ForwardToIoQueue(m_FxWaitMaskQueue); - - // - // Instead of "break" out of the switch statement and complete the - // request at the end of this function, use "return" directly. - // - return; - } - case IOCTL_SERIAL_SET_WAIT_MASK: - { - // - // NOTE: the contract says a set-wait-mask will cause any pending - // wait-on-mask to complete with STATUS_SUCCESS and the output wait - // event mask is set to zero. This is also the way for app to break - // out of the loop of sending down wait-on-mask - // - - IWDFIoRequest *pSavedRequest; - hr = m_FxWaitMaskQueue->RetrieveNextRequest(&pSavedRequest); - if (SUCCEEDED(hr)) - { - pSavedRequest->GetOutputMemory(&outputMemory); - if (NULL == outputMemory) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - } - - if (SUCCEEDED(hr)) - { - ULONG eventMask = 0; - - hr = outputMemory->CopyFromBuffer(0, - (void*) &eventMask, - sizeof(eventMask)); - - pSavedRequest->CompleteWithInformation(hr, sizeof(eventMask)); - } - else - { - pSavedRequest->Complete(hr); - } - - SAFE_RELEASE(pSavedRequest); - - // - // outputMemory will be released at the end of the function - // - } - - // - // NOTE: The application expects STATUS_SUCCESS for these IOCTLs. - // - hr = S_OK; - - break; - } - case IOCTL_SERIAL_SET_QUEUE_SIZE: - case IOCTL_SERIAL_SET_DTR: - case IOCTL_SERIAL_SET_RTS: - case IOCTL_SERIAL_CLR_RTS: - case IOCTL_SERIAL_SET_XON: - case IOCTL_SERIAL_SET_XOFF: - case IOCTL_SERIAL_SET_CHARS: - case IOCTL_SERIAL_GET_CHARS: - case IOCTL_SERIAL_GET_HANDFLOW: - case IOCTL_SERIAL_SET_HANDFLOW: - case IOCTL_SERIAL_RESET_DEVICE: - { - // - // NOTE: The application expects STATUS_SUCCESS for these IOCTLs. - // so don't merge this with default. - // - break; - } - - default: - { - hr = E_INVALIDARG; - } - } - - // - // clean up - // - if (inputMemory) - { - inputMemory->Release(); - } - - if (outputMemory) - { - outputMemory->Release(); - } - - // - // complete the request - // - pWdfRequest->CompleteWithInformation(hr, reqCompletionInfo); - - return; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - - Write dispatch routine - IQueueCallbackWrite - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Length of bytes in the write buffer - - Allocate and copy data to local buffer -Return Value: - - VOID - ---*/ -{ - IWDFMemory* pRequestMemory = NULL; - IWDFIoRequest* pSavedRequest = NULL; - SIZE_T availableData = 0; - SIZE_T savedRequestBufferSize = 0; - HRESULT hr = S_OK; - - UNREFERENCED_PARAMETER(pWdfQueue); - - // - // Get memory object - // - - pWdfRequest->GetInputMemory(&pRequestMemory); - - // - // Process input - // - - ProcessWriteBytes((PUCHAR)pRequestMemory->GetDataBuffer(NULL), BytesToWrite); - - // - // Release memory object and complete request - // - SAFE_RELEASE(pRequestMemory); - pWdfRequest->CompleteWithInformation(hr, BytesToWrite); - - // - // Get the amount of data available in the ring buffer - // - m_RingBuffer.GetAvailableData(&availableData); - - if (availableData > 0) - { - // - // Continue with the next request, if there is one pending - // - hr = m_FxReadQueue->RetrieveNextRequest(&pSavedRequest); - if ((pSavedRequest == NULL) || (FAILED(hr))) - { - goto Exit; - } - - pSavedRequest->GetReadParameters(&savedRequestBufferSize, NULL, NULL); - - OnRead(m_FxQueue, - pSavedRequest, - savedRequestBufferSize); - - // - // RetrieveNextRequest from a manual queue increments the reference - // counter by 1. We need to decrement it, otherwise the request will - // not be released and there will be an object leak. - // - SAFE_RELEASE(pSavedRequest); - } - -Exit: - return; -} - -VOID -STDMETHODCALLTYPE -CMyQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T SizeInBytes - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Arguments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - SizeInBytes - Length of bytes in the read buffer - - Copy available data into the read buffer -Return Value: - - VOID - ---*/ -{ - IWDFMemory* pRequestMemory = NULL; - SIZE_T BytesCopied = 0; - HRESULT hr; - - UNREFERENCED_PARAMETER(pWdfQueue); - - // - // Get memory object - // - pWdfRequest->GetOutputMemory(&pRequestMemory); - - hr = m_RingBuffer.Read((PBYTE)pRequestMemory->GetDataBuffer(NULL), - SizeInBytes, - &BytesCopied); - - // - // Release memory object. - // - SAFE_RELEASE(pRequestMemory); - - if (FAILED(hr)) - { - // - // Error reading buffer - // - pWdfRequest->Complete(hr); - goto Exit; - } - - if (BytesCopied > 0) - { - // - // Data was read from buffer succesfully - // - pWdfRequest->CompleteWithInformation(hr, BytesCopied); - } - else - { - // - // No data to read. Queue the request for later processing. - // - pWdfRequest->ForwardToIoQueue(m_FxReadQueue); - } - -Exit: - return; -} - -VOID -CMyQueue::ProcessWriteBytes( - _In_reads_bytes_(Length) PUCHAR Characters, - _In_ SIZE_T Length - ) -/*++ -Routine Description: - - This function is called when the framework receives IRP_MJ_WRITE - requests from the system. The write event handler(FmEvtIoWrite) calls ProcessWriteBytes. - It parses the Characters passed in and looks for the for sequences "AT" -ok , - "ATA" --CONNECT, ATD -- CONNECT and sets the state of the device appropriately. - These bytes are placed in the read Buffer to be processed later since this device - works in a loopback fashion. - - -Arguments: - - Characters - Pointer to the write IRP's system buffer. - - Length - Length of the IO operation - The default property of the queue is to not dispatch - zero lenght read & write requests to the driver and - complete is with status success. So we will never get - a zero length request. - -Return Value: - - VOID - ---*/ - -{ - - UCHAR currentCharacter; - UCHAR connectString[] = "\r\nCONNECT\r\n"; - UCHAR connectStringCch = ARRAY_SIZE(connectString) - 1; - UCHAR okString[] = "\r\nOK\r\n"; - UCHAR okStringCch = ARRAY_SIZE(okString) - 1; - - while (Length != 0) { - - currentCharacter = *(Characters++); - Length--; - - if(currentCharacter == '\0') - { - continue; - } - - m_RingBuffer.Write(¤tCharacter, sizeof(currentCharacter)); - - switch (m_CommandMatchState) { - case COMMAND_MATCH_STATE_IDLE: - if ((currentCharacter == 'a') || (currentCharacter == 'A')) - { - // - // got an A - // - m_CommandMatchState=COMMAND_MATCH_STATE_GOT_A; - m_ConnectCommand=FALSE; - m_IgnoreNextChar=FALSE; - } - - break; - - case COMMAND_MATCH_STATE_GOT_A: - if ((currentCharacter == 't') || (currentCharacter == 'T')) - { - // - // got a T - // - m_CommandMatchState=COMMAND_MATCH_STATE_GOT_T; - } - else - { - m_CommandMatchState=COMMAND_MATCH_STATE_IDLE; - } - - break; - - case COMMAND_MATCH_STATE_GOT_T: - - if (!m_IgnoreNextChar) - { - // - // the last char was not a special char - // check for CONNECT command - // - if ((currentCharacter == 'A') || (currentCharacter == 'a')) - { - - m_ConnectCommand=TRUE; - } - - if ((currentCharacter == 'D') || (currentCharacter == 'd')) - { - - m_ConnectCommand=TRUE; - } - } - - m_IgnoreNextChar=TRUE; - - if (currentCharacter == '\r') - { - // - // got a CR, send a response to the command - // - m_CommandMatchState = COMMAND_MATCH_STATE_IDLE; - - if (m_ConnectCommand) - { - // - // place CONNECT in the buffer - // - m_RingBuffer.Write(connectString, connectStringCch); - - // - // connected now raise CD - // - m_CurrentlyConnected = TRUE; - m_ConnectionStateChanged = TRUE; - - } - else - { - // - // place OK in the buffer - // - m_RingBuffer.Write(okString, okStringCch); - } - } - - break; - default: - break; - } - } - return; -} diff --git a/serial/VirtualSerial/queue.h b/serial/VirtualSerial/queue.h deleted file mode 100644 index 445ee48e4..000000000 --- a/serial/VirtualSerial/queue.h +++ /dev/null @@ -1,206 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#include "internal.h" - -// Set ring buffer size -#define DATA_BUFFER_SIZE 1024 - -// -// Macro definition for defining IOCTL and FSCTL function control codes. Note -// that function codes 0-2047 are reserved for Microsoft Corporation, and -// 2048-4095 are reserved for customers. -// - -#define CTL_CODE( DeviceType, Function, Method, Access ) ( \ - ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ -) - - -// -// Queue Callback Object. -// - -class CMyQueue : - public IQueueCallbackDeviceIoControl, - public IQueueCallbackRead, - public IQueueCallbackWrite, - public CUnknown -{ - UCHAR m_CommandMatchState; // Device state - BOOL m_ConnectCommand; - BOOL m_IgnoreNextChar; - BOOL m_ConnectionStateChanged; - BOOL m_CurrentlyConnected; - - IWDFIoQueue *m_FxQueue; // Default parallel queue - IWDFIoQueue *m_FxReadQueue; // Manual queue for pending reads - IWDFIoQueue *m_FxWaitMaskQueue; // Manual queue for pending ioctl wait-on-mask - - CRingBuffer m_RingBuffer; // Ring buffer for pending data - - PCMyDevice m_Device; - - CMyQueue( - CMyDevice *pDevice - ) : - m_CommandMatchState(COMMAND_MATCH_STATE_IDLE), - m_ConnectCommand(FALSE), - m_IgnoreNextChar(FALSE), - m_ConnectionStateChanged(FALSE), - m_CurrentlyConnected(FALSE), - m_FxQueue(NULL), - m_FxReadQueue(NULL) - { - WUDF_TEST_DRIVER_ASSERT(pDevice); - - pDevice->AddRef(); - m_Device = pDevice; - } - - virtual ~CMyQueue(); - - HRESULT - Initialize( - _In_ IWDFDevice *FxDevice - ); - - VOID - CMyQueue::ProcessWriteBytes( - _In_reads_bytes_(Length) PUCHAR Characters, - _In_ SIZE_T Length - ); - -public: - - static - HRESULT - CreateInstance( - _In_ CMyDevice *pDevice, - _In_ IWDFDevice *FxDevice, - _Out_ PCMyQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackRead * - QueryIQueueCallbackRead( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) { - return CUnknown::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) { - return CUnknown::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // IQueueCallbackDeviceIoControl - // - virtual - VOID - STDMETHODCALLTYPE - OnDeviceIoControl( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); - - // IQueueCallbackWrite - // - virtual - VOID - STDMETHODCALLTYPE - OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // IQueueCallbackRead - // - virtual - VOID - STDMETHODCALLTYPE - OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); -}; diff --git a/serial/VirtualSerial/ringbuffer.cpp b/serial/VirtualSerial/ringbuffer.cpp deleted file mode 100644 index fbbbd6b87..000000000 --- a/serial/VirtualSerial/ringbuffer.cpp +++ /dev/null @@ -1,258 +0,0 @@ -#include "internal.h" - -CRingBuffer::CRingBuffer( - VOID - ) : m_Size(0), - m_Base(NULL), - m_End(NULL), - m_Head(NULL), - m_Tail(NULL) -{ - return; -} - -CRingBuffer::~CRingBuffer( - VOID - ) -{ - if (m_Base) - { - delete[] m_Base; - } -} - -HRESULT -CRingBuffer::Initialize( - _In_ SIZE_T BufferSize - ) -{ - HRESULT hr = S_OK; - PBYTE buffer = NULL; - - if (0 == BufferSize) - { - hr = E_INVALIDARG; - } - - // - // Allocate the buffer. - // - if (SUCCEEDED(hr)) - { - buffer = new BYTE[BufferSize]; - if (buffer == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Initialize the ring buffer pointers. - // - if (SUCCEEDED(hr)) - { - m_Size = BufferSize; - m_Base = buffer; - m_End = buffer + BufferSize; - m_Head = buffer; - m_Tail = buffer; - } - - if (FAILED(hr)) - { - if (buffer) - { - delete[] buffer; - m_Base = NULL; - } - } - - return hr; -} - -HRESULT -CRingBuffer::Write( - _In_reads_bytes_(DataSize) PBYTE Data, - _In_ SIZE_T DataSize - ) -{ - SIZE_T availableSpace; - SIZE_T bytesToCopy; - SIZE_T spaceFromCurrToEnd; - - WUDF_TEST_DRIVER_ASSERT(Data && (0 != DataSize)); - - if (m_Tail >= m_End) - { - return E_UNEXPECTED; - } - - // - // Get the amount of space available in the buffer - // - GetAvailableSpace(&availableSpace); - - // - // If there is not enough space to fit in all the data passed in by the - // caller then copy as much as possible and throw away the rest - // - if (availableSpace < DataSize) - { - bytesToCopy = availableSpace; - } - else - { - bytesToCopy = DataSize; - } - - if (bytesToCopy) - { - // - // The buffer has some space at least - // - if ((m_Tail+bytesToCopy) > m_End) - { - // - // The data being written will wrap around the end of the buffer. - // So the copy has to be done in two steps - - // * X bytes from current position to end of the buffer - // * the remaining (bytesToCopy - X) from the start of the buffer - // - - // - // The first step of the copy ... - // - spaceFromCurrToEnd = m_End - m_Tail; - CopyMemory(m_Tail, Data, spaceFromCurrToEnd); - Data += spaceFromCurrToEnd; - bytesToCopy -= spaceFromCurrToEnd; - - // - // The second step of the copy ... - // - CopyMemory(m_Base, Data, bytesToCopy); - - // - // Advance the tail pointer - // - m_Tail = m_Base + bytesToCopy; - } - else - { - // - // Data does NOT wrap around the end of the buffer. Just copy it - // over in a single step - // - CopyMemory(m_Tail, Data, bytesToCopy); - - // - // Advance the tail pointer - // - m_Tail += bytesToCopy; - if (m_Tail == m_End) - { - // - // We have exactly reached the end of the buffer. The next - // write should wrap around and start from the beginning. - // - m_Tail = m_Base; - } - } - - WUDF_TEST_DRIVER_ASSERT(m_Tail < m_End); - } - - return S_OK; -} - -HRESULT -CRingBuffer::Read( - _Out_writes_bytes_to_(DataSize, *BytesCopied) PBYTE Data, - _In_ SIZE_T DataSize, - _Out_ SIZE_T *BytesCopied - ) -{ - SIZE_T availableData; - SIZE_T dataFromCurrToEnd; - - WUDF_TEST_DRIVER_ASSERT(Data && (DataSize != 0)); - - if (m_Head >= m_End) - { - return E_UNEXPECTED; - } - - // - // Get the amount of data available in the buffer - // - GetAvailableData(&availableData); - - if (availableData == 0) - { - *BytesCopied = 0; - return S_OK; - } - - if (DataSize > availableData) - { - DataSize = availableData; - } - - *BytesCopied = DataSize; - - if ((m_Head + DataSize) > m_End) - { - // - // The data requested by the caller is wrapped around the end of the - // buffer. So we'll do the copy in two steps - - // * Copy X bytes from the current position to the end buffer into - // the caller's buffer - // * Copy (DataSize - X) bytes from the beginning to the buffer into - // the caller's buffer - // - - // - // The first step of the copy ... - // - dataFromCurrToEnd = m_End - m_Head; - CopyMemory(Data, m_Head, dataFromCurrToEnd); - Data += dataFromCurrToEnd; - DataSize -= dataFromCurrToEnd; - - // - // The second step of the copy ... - // - CopyMemory(Data, m_Base, DataSize); - - // - // Advance the head pointer - // - m_Head = m_Base + DataSize; - } - else - { - // - // The data in the buffer is NOT wrapped around the end of the buffer. - // Simply copy the data over to the caller's buffer in a single step. - // - CopyMemory(Data, m_Head, DataSize); - - // - // Advance the head pointer - // - m_Head += DataSize; - if (m_Head == m_End) - { - // - // We have exactly reached the end of the buffer. The next - // read should wrap around and start from the beginning. - // - m_Head = m_Base; - } - } - - WUDF_TEST_DRIVER_ASSERT(m_Head < m_End); - - return S_OK; -} - diff --git a/serial/VirtualSerial/ringbuffer.h b/serial/VirtualSerial/ringbuffer.h deleted file mode 100644 index 130055d9a..000000000 --- a/serial/VirtualSerial/ringbuffer.h +++ /dev/null @@ -1,223 +0,0 @@ -#pragma once - -#include "internal.h" - -class CRingBuffer -{ -private: - - // - // Private local variables. - // - - // - // The size in bytes of the ring buffer. - // - SIZE_T m_Size; - - // - // A pointer to the base of the ring buffer. - // - PBYTE m_Base; - - // - // A pointer to the byte beyond the end of the ring buffer. Used for - // quick comparisons when determining if we need to wrap. - // - PBYTE m_End; - - // - // A pointer to the current read point in the ring buffer. - // - // Updates to this are not protected by any lock. This is different from - // the write pointer, which is protected by the "pending read pointer" - // lock. The reason for this difference is that in this driver, we do not - // keep write requests pending. If there is not enough space to write all - // the data that was requested, we write as much as we can and drop the - // rest (lossy data transfer). - // - // If we had multiple threads modifying this pointer, then that would - // provide yet another reason for protecting updates to the pointer using a - // lock. However, in this driver, at any given time we have only one thread - // that modifies this pointer (the thread that runs the read callback). - // This is true because we use a sequential queue for read requests. If we - // were to change our read queue to be a parallel queue, this would no - // longer be true. - // - // - PBYTE m_Head; - - // - // A pointer to the current write point in the ring buffer. - // - // Updates to this pointer are protected by the "pending read pointer - // lock", because we do not want a consumer thread to mark a read request - // as pending while we are in the process of writing data to the buffer. - // The reason is that the write that we are currently performing might - // actually supply enough data to satisfy the read request, in which case - // it should not be marked pending at all. - // If the read request were to be marked pending in the situation described - // above, then we would need some trigger to later retrieve the request and - // complete it. In our driver, arrival of data is the only event that can - // trigger this. So if no more data arrives, the request will remain - // pending forever, even though there is enough data in the buffer to - // complete it. Hence we do not keep a read request pending in situations - // where the read buffer contains enough data to satisfy it. - // - // If we had multiple threads modifying this pointer, then that would - // provide yet another reason for protecting updates to the pointer using a - // lock. However, in this driver, at any given time we have only one thread - // that modifies this pointer (the thread that runs the write callback). - // This is true because we use a sequential queue for write requests. If we - // were to change our write queue to be a parallel queue, this would no - // longer be true. - // - PBYTE m_Tail; - -private: - - // - // Private Internal Methods. - // - void - GetAvailableSpace( - _Out_ SIZE_T *AvailableSpace - ) - { - WUDF_TEST_DRIVER_ASSERT(AvailableSpace); - - PBYTE headSnapshot = NULL; - PBYTE tailSnapshot = NULL; - PBYTE tailPlusOne = NULL; - - // - // Take a snapshot of the head and tail pointers. We will compute the - // available space based on this snapshot. This is safe to do in a - // single-producer, single-consumer model, because - - // * A producer will call GetAvailableSpace() to determine whether - // there is enough space to write the data it is trying to write. - // The only other thread that could modify the amount of space - // available is the consumer thread, which can only increase the - // amount of space available. Hence it is safe for the producer - // to write based on this snapshot. - // * A consumer thread will call GetAvailableSpace() to determine - // whether there is enough data in the buffer for it to read. - // (Available data = Buffer size - Available space). The only - // other thread that could modify the amount of space available - // is the producer thread, which can only decrease the amount of - // space available (thereby increasing the amount of data - // available. Hence it is safe for the consumer to read based on - // this snapshot. - // - headSnapshot = m_Head; - tailSnapshot = m_Tail; - - // - // In order to distinguish between a full buffer and an empty buffer, - // we always leave the last byte of the buffer unused. So, an empty - // buffer is denoted by - - // tail == head - // ... and a full buffer is denoted by - - // (tail+1) == head - // - tailPlusOne = ((tailSnapshot+1) == m_End) ? m_Base : (tailSnapshot+1); - - if (tailPlusOne == headSnapshot) - { - // - // Buffer full - // - *AvailableSpace = 0; - } - else if (tailSnapshot == headSnapshot) - { - // - // Buffer empty - // The -1 in the computation below is to account for the fact that - // we always leave the last byte of the ring buffer unused in order - // to distinguish between an empty buffer and a full buffer. - // - *AvailableSpace = m_Size - 1; - } - else - { - if (tailSnapshot > headSnapshot) - { - // - // Data has not wrapped around the end of the buffer - // The -1 in the computation below is to account for the fact - // that we always leave the last byte of the ring buffer unused - // in order to distinguish between an empty buffer and a full - // buffer. - // - *AvailableSpace = m_Size - (tailSnapshot - headSnapshot) - 1; - } - else - { - // - // Data has wrapped around the end of the buffer - // The -1 in the computation below is to account for the fact - // that we always leave the last byte of the ring buffer unused - // in order to distinguish between an empty buffer and a full - // buffer. - // - *AvailableSpace = (headSnapshot - tailSnapshot) - 1; - } - } - - return; - } - -public: - - // - // Public Internal methods. - // - - CRingBuffer( - VOID - ); - - ~CRingBuffer( - VOID - ); - - HRESULT - Initialize( - _In_ SIZE_T BufferSize - ); - - HRESULT - Write( - _In_reads_bytes_(DataSize) PBYTE Data, - _In_ SIZE_T DataSize - ); - - HRESULT - Read( - _Out_writes_bytes_to_(DataSize, *BytesCopied) PBYTE Data, - _In_ SIZE_T DataSize, - _Out_ SIZE_T *BytesCopied - ); - - void - GetAvailableData( - _Out_ SIZE_T *AvailableData - ) - { - SIZE_T availableSpace; - - WUDF_TEST_DRIVER_ASSERT(AvailableData); - - GetAvailableSpace(&availableSpace); - - // - // The -1 in the arithmetic below accounts for the fact that we always - // keep 1 byte of the ring buffer unused in order to distinguish - // between a full buffer and an empty buffer. - // - *AvailableData = m_Size - availableSpace - 1; - - return; - } -}; diff --git a/serial/VirtualSerial/serial.h b/serial/VirtualSerial/serial.h deleted file mode 100644 index 0ae911865..000000000 --- a/serial/VirtualSerial/serial.h +++ /dev/null @@ -1,48 +0,0 @@ -/*++ - -Module Name : - - serial.h - -Abstract: - - Type definitions and data for the serial port driver - -Author: - - ---*/ - -#pragma once - -#define SYMBOLIC_NAME_LENGTH 32 -#define SYMBOLIC_LINK_NAME_PREFIX L"\\DosDevices\\Global\\" - -// -// This defines the bit used to control whether the device is sending -// a break. When this bit is set the device is sending a space (logic 0). -// -// Most protocols will assume that this is a hangup. -// -#define SERIAL_LCR_BREAK 0x40 - -// -// These defines are used to set the line control register. -// -#define SERIAL_5_DATA ((UCHAR)0x00) -#define SERIAL_6_DATA ((UCHAR)0x01) -#define SERIAL_7_DATA ((UCHAR)0x02) -#define SERIAL_8_DATA ((UCHAR)0x03) -#define SERIAL_DATA_MASK ((UCHAR)0x03) - -#define SERIAL_1_STOP ((UCHAR)0x00) -#define SERIAL_1_5_STOP ((UCHAR)0x04) // Only valid for 5 data bits -#define SERIAL_2_STOP ((UCHAR)0x04) // Not valid for 5 data bits -#define SERIAL_STOP_MASK ((UCHAR)0x04) - -#define SERIAL_NONE_PARITY ((UCHAR)0x00) -#define SERIAL_ODD_PARITY ((UCHAR)0x08) -#define SERIAL_EVEN_PARITY ((UCHAR)0x18) -#define SERIAL_MARK_PARITY ((UCHAR)0x28) -#define SERIAL_SPACE_PARITY ((UCHAR)0x38) -#define SERIAL_PARITY_MASK ((UCHAR)0x38) diff --git a/serial/VirtualSerial2/ComPort/virtualserial2um.inx b/serial/VirtualSerial2/ComPort/virtualserial2um.inx index 94ffc922e..1194ae6ad 100644 Binary files a/serial/VirtualSerial2/ComPort/virtualserial2um.inx and b/serial/VirtualSerial2/ComPort/virtualserial2um.inx differ diff --git a/serial/VirtualSerial2/FakeModem/fakemodem2um.inx b/serial/VirtualSerial2/FakeModem/fakemodem2um.inx index 1dc1c32e0..235bddddb 100644 Binary files a/serial/VirtualSerial2/FakeModem/fakemodem2um.inx and b/serial/VirtualSerial2/FakeModem/fakemodem2um.inx differ diff --git a/serial/VirtualSerial2/FakeModem/fakemodem2um.vcxproj b/serial/VirtualSerial2/FakeModem/fakemodem2um.vcxproj index a729333c2..3b1e47518 100644 --- a/serial/VirtualSerial2/FakeModem/fakemodem2um.vcxproj +++ b/serial/VirtualSerial2/FakeModem/fakemodem2um.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver UMDF WindowsUserModeDriver10.0 DynamicLibrary diff --git a/serial/serenum/SerEnum_sample.vcxproj b/serial/serenum/SerEnum_sample.vcxproj index 09753b003..d189ece03 100644 --- a/serial/serenum/SerEnum_sample.vcxproj +++ b/serial/serenum/SerEnum_sample.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WDM WindowsKernelModeDriver10.0 Driver diff --git a/serial/serenum/enum.c b/serial/serenum/enum.c index feb6f4afb..35ebe2ceb 100644 --- a/serial/serenum/enum.c +++ b/serial/serenum/enum.c @@ -230,7 +230,7 @@ SerenumDoEnumProtocol( LOGENTRY(LOG_ENUM, 'SDEP', PFdoData, PpBuf, PDSRMissing); - pReadBuf = ExAllocatePoolWithTag(NonPagedPoolNx, MAX_DEVNODE_NAME + sizeof(CHAR) ,SERENUM_POOL_TAG); + pReadBuf = ExAllocatePoolZero(NonPagedPoolNx, MAX_DEVNODE_NAME + sizeof(CHAR) ,SERENUM_POOL_TAG); if (pReadBuf == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; @@ -1580,7 +1580,7 @@ Return Value: length = sizeof(KEY_VALUE_FULL_INFORMATION) + KeyNameStringLength + DataLength; - fullInfo = ExAllocatePoolWithTag(PagedPool, length,SERENUM_POOL_TAG); + fullInfo = ExAllocatePoolZero(PagedPool, length,SERENUM_POOL_TAG); if (ActualLength != NULL) { *ActualLength = 0; diff --git a/serial/serenum/log.c b/serial/serenum/log.c index 693bb6981..ad834d4b4 100644 --- a/serial/serenum/log.c +++ b/serial/serenum/log.c @@ -146,7 +146,7 @@ Return Value: KeInitializeSpinLock(&LogSpinLock); - SerenumLStart = ExAllocatePoolWithTag(NonPagedPoolNx, logSize, 'mneS'); + SerenumLStart = ExAllocatePoolZero(NonPagedPoolNx, logSize, 'mneS'); if (SerenumLStart) { SerenumLPtr = SerenumLStart; diff --git a/serial/serial/serial.inx b/serial/serial/serial.inx index 1879188ce..d6bfc3bba 100644 Binary files a/serial/serial/serial.inx and b/serial/serial/serial.inx differ diff --git a/serial/serial/wdfserial.vcxproj b/serial/serial/wdfserial.vcxproj index fb761163d..9627ed143 100644 --- a/serial/serial/wdfserial.vcxproj +++ b/serial/serial/wdfserial.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/simbatt/func/simbatt-wdfcoinstall.inx b/simbatt/func/simbatt-wdfcoinstall.inx deleted file mode 100644 index 15c596abb..000000000 --- a/simbatt/func/simbatt-wdfcoinstall.inx +++ /dev/null @@ -1,109 +0,0 @@ -;/*++ -; -;Copyright (c) Microsoft Corporation All rights Reserved -; -;Module Name: -; -; simbatt.inf -; -;Abstract: -; -; INF file for installing Simulated Battery WDF driver. -; -; N.B. Search the file for TODO comments and make necessary changes to make -; this INF file functional. -; -; N.B. Place the WdfCoInstaller files in the same directory as this file to -; make this INF file functional. -; -;--*/ - -[Version] -Signature="$WINDOWS NT$" -Class=Battery -ClassGuid={72631e54-78a4-11d0-bcf7-00aa00b7b32a} -Provider=%ProviderName% -DriverVer=04/30/2008, 6.01.6598 -CatalogFile=simbatt-wdfcoinstall.cat ; TODO: Add a signed catalog file -PnpLockdown=1 - -[DestinationDirs] -DefaultDestDir = 12 -SimBatt_Device_CoInstaller_CopyFiles = 11 - -[SourceDisksNames] -1 = %DiskId1%,,,"" - -[SourceDisksFiles] -simbatt.sys = 1 -WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll = 1 - -;***************************************** -; Simulated Battery Install Section -;***************************************** - -[Manufacturer] -%StdMfg%=Standard,NT$ARCH$ - -[Standard.NT$ARCH$] -%SimBatt.DeviceDesc% = SimBatt_Device,{6B34C467-CE1F-4c0d-A3E4-F98A5718A9D6}\SimBatt - -[SimBatt_Device.NT] -CopyFiles=SimBatt_Device_Drivers -Include=battery.inf -Needs=Battery_Inst - -[SimBatt_Device.NT.HW] -AddReg=SimBatt_Device.NT.AddReg - -[SimBatt_Device.NT.AddReg] -HKR,,Security,,"D:P(A;;GA;;;AU)(A;;GA;;;S-1-15-2-1)" ; Allow generic-all users and appcontainers - -[SimBatt_Device_Drivers] -simbatt.sys - -;-------------- Service installation - -[SimBatt_Device.NT.Services] -AddService = simbatt,%SPSVCINST_ASSOCSERVICE%,SimBatt_Service_Inst - -; -------------- simbatt driver install sections - -[SimBatt_Service_Inst] -DisplayName = %SimBatt.SVCDESC% -ServiceType = 1 ; SERVICE_KERNEL_DRIVER -StartType = 3 ; SERVICE_DEMAND_START -ErrorControl = 1 ; SERVICE_ERROR_NORMAL -ServiceBinary = %12%\simbatt.sys - -;***************************************** -; WDF CoInstaller -;***************************************** - -[SimBatt_Device.NT.CoInstallers] -AddReg=SimBatt_Device_CoInstaller_AddReg -CopyFiles=SimBatt_Device_CoInstaller_CopyFiles - -[SimBatt_Device_CoInstaller_AddReg] -HKR,,CoInstallers32,0x00010000, "WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" - -[SimBatt_Device_CoInstaller_CopyFiles] -WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll - -[SimBatt_Device.NT.Wdf] -KmdfService = SimBatt, SimBatt_wdfsect - -[SimBatt_wdfsect] -KmdfLibraryVersion = $KMDFVERSION$ - -;***************************************** -; Literals -;***************************************** - -[Strings] -SPSVCINST_ASSOCSERVICE= 0x00000002 -ProviderName = "TODO-Set-Provider" -StdMfg = "TODO-Set-Manufacturer" -DiskId1 = "Simulated Battery Installation Disk" -SimBatt.DeviceDesc = "Simulated Battery" -SimBatt.SVCDESC = "Simulated Battery" diff --git a/simbatt/func/simbatt.inx b/simbatt/func/simbatt.inx index 3b138e05b..5aab816a0 100644 Binary files a/simbatt/func/simbatt.inx and b/simbatt/func/simbatt.inx differ diff --git a/simbatt/func/simbatt.vcxproj b/simbatt/func/simbatt.vcxproj index a9ab3b9b8..342480fb3 100644 --- a/simbatt/func/simbatt.vcxproj +++ b/simbatt/func/simbatt.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -190,7 +190,7 @@ - + diff --git a/simbatt/func/simbatt.vcxproj.Filters b/simbatt/func/simbatt.vcxproj.Filters index 42b85d1a8..bef5fc966 100644 --- a/simbatt/func/simbatt.vcxproj.Filters +++ b/simbatt/func/simbatt.vcxproj.Filters @@ -43,10 +43,7 @@ - - Driver Files - - + Driver Files diff --git a/spb/SkeletonI2C/skeletoni2c.inx b/spb/SkeletonI2C/skeletoni2c.inx index 736fe2475..056423f99 100644 Binary files a/spb/SkeletonI2C/skeletoni2c.inx and b/spb/SkeletonI2C/skeletoni2c.inx differ diff --git a/spb/SkeletonI2C/skeletoni2c.vcxproj b/spb/SkeletonI2C/skeletoni2c.vcxproj index 2a244d4b6..2844d1a8f 100644 --- a/spb/SkeletonI2C/skeletoni2c.vcxproj +++ b/spb/SkeletonI2C/skeletoni2c.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/spb/SpbTestTool/exe/SpbTestTool.vcxproj b/spb/SpbTestTool/exe/SpbTestTool.vcxproj index 55d651e9b..a4b8d011e 100644 --- a/spb/SpbTestTool/exe/SpbTestTool.vcxproj +++ b/spb/SpbTestTool/exe/SpbTestTool.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/spb/SpbTestTool/sys/SpbTestTool.vcxproj b/spb/SpbTestTool/sys/SpbTestTool.vcxproj index 4b2b263ed..072066dc1 100644 --- a/spb/SpbTestTool/sys/SpbTestTool.vcxproj +++ b/spb/SpbTestTool/sys/SpbTestTool.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/spb/SpbTestTool/sys/spbtesttool.inx b/spb/SpbTestTool/sys/spbtesttool.inx index 390e69843..baf82127e 100644 Binary files a/spb/SpbTestTool/sys/spbtesttool.inx and b/spb/SpbTestTool/sys/spbtesttool.inx differ diff --git a/storage/class/cdrom/README.md b/storage/class/cdrom/README.md deleted file mode 100644 index 4b0810143..000000000 --- a/storage/class/cdrom/README.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -page_type: sample -description: "Provide access to CD, DVD and Blu-ray drives, supports Plug and Play, Power Management, and AutoRun (media change notification)." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# CDROM Storage Class Driver - -The CD ROM driver is used to provide access to CD, DVD and Blu-ray drives. It supports Plug and Play, Power Management, and AutoRun (media change notification). - -## Build the sample - -You can build the sample in two ways: using Microsoft Visual Studio or the command line (*MSBuild*). - -> [!NOTE] -> When building in Visual Studio, INFVerifer will throw errors. This is intended. Fix those errors with your custom values to build successfully. - -## Building a Driver Using Visual Studio - -You build a driver the same way you build any project or solution in Visual Studio. When you create a new driver project using a Windows driver template, the template defines a default (active) project configuration and a default (active) solution build configuration. When you create a project from existing driver sources or convert existing driver code that was built with previous versions of the WDK, the conversion process preserves the target version information (operating systems and platform). - -The default Solution build configuration is Visual Studio Debug and Win32. - -1. Open the driver project or solution in Visual Studio (find *samplename*.sln or *samplename*.vcxproj). - -1. Right-click the solution in the **Solutions Explorer** and select **Configuration Manager**. - -1. From the **Configuration Manager**, select the **Active Solution Configuration** (for example, Debug or Release) and the **Active Solution Platform** (for example, Win32) that correspond to the type of build you are interested in. - -1. From the Build menu, click **Build Solution** (Ctrl+Shift+B). - -## Building a Driver Using the Command Line (MSBuild) - -You can build a driver from the command line using the Visual Studio Command Prompt window and the Microsoft Build Engine (MSBuild.exe) Previous versions of the WDK used the Windows Build utility (Build.exe) and provided separate build environment windows for each of the supported build configurations. You can now use the Visual Studio Command Prompt window for all build configurations. - -1. Open a Visual Studio Command Prompt window at the **Start** screen. From this window you can use MsBuild.exe to build any Visual Studio project by specifying the project (.VcxProj) or solutions (.Sln) file. - -1. Navigate to the project directory and enter the **MSbuild** command for your target. For example, to perform a clean build of a Visual Studio driver project called *filtername*.vcxproj, navigate to the project directory and enter the following MSBuild command: - - `msbuild /t:clean /t:build .\.vcxproj` - -## Installation and Operation - -The in-box CD ROM driver is protected by the system, and thus a normal device driver update attempt through the Device Manager will fail. Users are not encouraged to replace the in-box CD ROM driver. The following work-around is provided in case there is a need, but the users are warned that this may harm the system. - -1. Locate the "cdrom.inf" file in the binary output directory, and update the file by replacing all "cdrom.sys" occurrences with "mycdrom.sys". - -1. Rename the "cdrom.inf" file to "mycdrom.inf". - -1. Copy "mycdrom.sys" and "mycdrom.inf" from the binary output directory to the test machine, if applicable. - -1. Launch the Device Manager - -1. Select the appropriate device under the "DVD/CD-ROM drives" category. - -1. On the right-click menu, select "Update Driver Software...". - -1. Select "Browse my computer for driver software". - -1. Select "Let me pick from a list of device drivers on my computer". - -1. Click "Have Disk...", and point to the directory that contains "mycdrom.inf" and "mycdrom.sys". - -1. Click "Next". If you get a warning dialog about installing unsigned driver, click "Yes". - -1. Click "Next" to complete the driver upgrade. - -1. After installation completes successfully, "mycdrom.sys" will be the effective driver for the device, "cdrom.sys" will no longer be used. - -For more information, see [CD-ROM Drivers](https://docs.microsoft.com/windows-hardware/drivers/storage/cd-rom-drivers) in the storage technologies design guide. diff --git a/storage/class/cdrom/cdrom.sln b/storage/class/cdrom/cdrom.sln deleted file mode 100644 index 4516f3dcc..000000000 --- a/storage/class/cdrom/cdrom.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cdrom", "src\cdrom.vcxproj", "{9DB6E759-C294-4E18-9013-82FD8F3DD5E6}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Debug|Win32.ActiveCfg = Debug|Win32 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Debug|Win32.Build.0 = Debug|Win32 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Release|Win32.ActiveCfg = Release|Win32 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Release|Win32.Build.0 = Release|Win32 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Debug|x64.ActiveCfg = Debug|x64 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Debug|x64.Build.0 = Debug|x64 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Release|x64.ActiveCfg = Release|x64 - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/storage/class/cdrom/src/aacs.c b/storage/class/cdrom/src/aacs.c deleted file mode 100644 index 191ba6b07..000000000 --- a/storage/class/cdrom/src/aacs.c +++ /dev/null @@ -1,1481 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - aacs.c - -Abstract: - - The CDROM class driver implementation of handling AACS IOCTLs. - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "ioctl.h" -#include "scratch.h" - -#ifdef DEBUG_USE_WPP -#include "aacs.tmh" -#endif - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceHandleAacsReadMediaKeyBlock) -#pragma alloc_text(PAGE, DeviceHandleAacsStartSession) -#pragma alloc_text(PAGE, DeviceHandleAacsEndSession) -#pragma alloc_text(PAGE, DeviceHandleAacsSendCertificate) -#pragma alloc_text(PAGE, DeviceHandleAacsGetCertificate) -#pragma alloc_text(PAGE, DeviceHandleAacsGetChallengeKey) -#pragma alloc_text(PAGE, DeviceHandleAacsReadSerialNumber) -#pragma alloc_text(PAGE, DeviceHandleAacsReadMediaId) -#pragma alloc_text(PAGE, DeviceHandleAacsReadBindingNonce) -#pragma alloc_text(PAGE, DeviceHandleAacsGenerateBindingNonce) -#pragma alloc_text(PAGE, DeviceHandleReadVolumeId) -#pragma alloc_text(PAGE, DeviceHandleSendChallengeKey) - -#endif - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadMediaKeyBlock( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTLs: - IOCTL_AACS_READ_MEDIA_KEY_BLOCK_SIZE - IOCTL_AACS_READ_MEDIA_KEY_BLOCK -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PAACS_LAYER_NUMBER layerNumber = NULL; - PVOID outputBuffer = NULL; - ULONG transferSize = sizeof(READ_DVD_STRUCTURES_HEADER); - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&layerNumber, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_AACS_READ_MEDIA_KEY_BLOCK) - { - // maximum size for this transfer is one pack + header - transferSize += AACS_MKB_PACK_SIZE; - } - - if (transferSize > DeviceExtension->ScratchContext.ScratchBufferSize) - { - // rare case. normally the size of scratch buffer is 64k. - status = STATUS_INTERNAL_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - UCHAR rmdBlockNumber = 0; - BOOLEAN sendChangedCommand = TRUE; - BOOLEAN shouldRetry = TRUE; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE; - // cdb->AsByte[1] = 0x01; // AACS sub-command not required for this - - cdb.READ_DVD_STRUCTURE.LayerNumber = (UCHAR)(*layerNumber); - cdb.READ_DVD_STRUCTURE.Format = 0x83; // MKB - cdb.READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(transferSize >> (8*1)); - cdb.READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(transferSize >> (8*0)); - - while (sendChangedCommand) - { - // RMDBlockNumber is set to zero.... - // RMDBlockNumber[3] maybe changed for other blocks. - cdb.READ_DVD_STRUCTURE.RMDBlockNumber[3] = rmdBlockNumber; - - if (shouldRetry) - { - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, TRUE, &cdb, 12); - } - - #ifdef ENABLE_AACS_TESTING - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_AACS_READ_MEDIA_KEY_BLOCK_SIZE) - { - static const UCHAR results[] = { 0x80, 0x02, 0x00, 0x02 }; - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; - } - else if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_AACS_READ_MEDIA_KEY_BLOCK) - { - static const UCHAR results[] = { 0x80, 0x02, 0x00, 0x02 }; - static const UCHAR defaultFill = 0x30; // '0' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x8004, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; - } - #endif //ENABLE_AACS_TESTING - - if (NT_SUCCESS(status)) - { - // command succeeded, process data... - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - UCHAR thisPackNumber = cdb.READ_DVD_STRUCTURE.RMDBlockNumber[3]; - UCHAR otherPacks = header->Reserved[1]; - - // validate and zero-base the otherPacks - if (otherPacks == 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "AACS: Device is reporting zero total packs (invalid)\n")); - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - else - { - otherPacks--; - - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_AACS_READ_MEDIA_KEY_BLOCK_SIZE) - { - // if not already requested last pack, do so now - if (otherPacks != thisPackNumber) - { - // re-send the command for the other pack number. - // this is safe here because NT_SUCCESS() is TRUE, - // and all the rest of this routine does is SetHardError() - // and release of resources we're still about to use. - - // re-zero the output buffer - RtlZeroMemory(DeviceExtension->ScratchContext.ScratchBuffer, sizeof(READ_DVD_STRUCTURES_HEADER)); - - // modify the CDB to get the very last pack of the MKB - rmdBlockNumber = otherPacks; - - transferSize = sizeof(READ_DVD_STRUCTURES_HEADER); - - // keep items clean - ScratchBuffer_ResetItems(DeviceExtension, TRUE); - - // make sure the loop will be executed for modified command. - sendChangedCommand = TRUE; - shouldRetry = TRUE; - } - else - { - // this request already got the last pack - // so just interpret the data - REVERSE_SHORT(&header->Length); - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - else - { - ULONG totalSize = header->Length; - // subtract out any remaining bytes in the header - // to get the number of usable bytes in this pack - totalSize -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - totalSize += otherPacks * AACS_MKB_PACK_SIZE; - - // save the result and complete the request - *((PULONG)outputBuffer) = totalSize; - *DataLength = sizeof(ULONG); - status = STATUS_SUCCESS; - } - // This will exit the loop of sendChangedCommand - sendChangedCommand = FALSE; - shouldRetry = FALSE; - } - } - else if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_AACS_READ_MEDIA_KEY_BLOCK) - { - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - else - { - // success, how many bytes to copy for this pack? - ULONG totalSize = header->Length; - size_t originalBufferSize; - - // subtract out any remaining bytes in the header - // to get the number of usable bytes in this pack - totalSize -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // if not the final pack, this should be a full transfer per spec - NT_ASSERT( (totalSize == AACS_MKB_PACK_SIZE) || (thisPackNumber == otherPacks) ); - - // validate the user's buffer is large enough to accept the full data - originalBufferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - - if (originalBufferSize < (totalSize + (AACS_MKB_PACK_SIZE*thisPackNumber))) - { - // just return a slightly bigger-than-normal size - *DataLength = (otherPacks + 1)*AACS_MKB_PACK_SIZE; - status = STATUS_BUFFER_TOO_SMALL; - } - else - { - PUCHAR whereToCopy; - // determine where to copy to the user's memory - whereToCopy = outputBuffer; - whereToCopy += AACS_MKB_PACK_SIZE * thisPackNumber; - - RtlCopyMemory(whereToCopy, header->Data, totalSize); - - // update the Information field here because we already - // have calculated the size of the block - *DataLength = totalSize + (AACS_MKB_PACK_SIZE * thisPackNumber); - status = STATUS_SUCCESS; - - // if there are more packs to get from the device, send it again.... - if (thisPackNumber != otherPacks) - { - // re-send the command for the next pack number. - // this is safe here because NT_SUCCESS() is TRUE, - // and all the rest of this routine does is SetHardError() - // and release of resources we're still about to use. - - // re-zero the output buffer - RtlZeroMemory(DeviceExtension->ScratchContext.ScratchBuffer, sizeof(READ_DVD_STRUCTURES_HEADER)); - - // modify the CDB to get the next pack of the MKB - rmdBlockNumber = cdb.READ_DVD_STRUCTURE.RMDBlockNumber[3]++; - - // modify the SRB to be resent - // - transferSize = AACS_MKB_PACK_SIZE + sizeof(READ_DVD_STRUCTURES_HEADER); - - // keep items clean - ScratchBuffer_ResetItems(DeviceExtension, FALSE); - - // make sure the loop will be executed for modified command. - sendChangedCommand = TRUE; - shouldRetry = TRUE; - } - else - { - // else, that was the end of the transfer, so just complete the request - sendChangedCommand = FALSE; - } - } - } - - } // end of IOCTL_AACS_READ_MEDIA_KEY_BLOCK - } - } // end of NT_SUCCESS(status) - - if (!NT_SUCCESS(status)) - { - // command failed. - sendChangedCommand = FALSE; - } - } //end of while (sendChangedCommand) - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_START_SESSION -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsGetAgid - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID sessionId = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&sessionId, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(CDVD_REPORT_AGID_DATA); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.REPORT_KEY.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.REPORT_KEY.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.REPORT_KEY.KeyFormat = 0x00; // DVD_REPORT_AGID? - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0 }; - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PCDVD_KEY_HEADER keyHeader = DeviceExtension->ScratchContext.ScratchBuffer; - PCDVD_REPORT_AGID_DATA keyData = (PCDVD_REPORT_AGID_DATA)keyHeader->Data; - - *sessionId = (DVD_SESSION_ID)(keyData->AGID); - *DataLength = sizeof(DVD_SESSION_ID); - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_END_SESSION -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsReleaseAgid - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID sessionId = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&sessionId, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - DVD_SESSION_ID currentSession = 0; - DVD_SESSION_ID limitSession = 0; - - if(*sessionId == DVD_END_ALL_SESSIONS) - { - currentSession = 0; - limitSession = MAX_COPY_PROTECT_AGID - 1; - } - else - { - currentSession = *sessionId; - limitSession = *sessionId; - } - - ScratchBuffer_BeginUse(DeviceExtension); - - do - { - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SEND_KEY.OperationCode = SCSIOP_SEND_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.SEND_KEY.AGID = (UCHAR)(currentSession); - cdb.SEND_KEY.KeyFormat = DVD_INVALIDATE_AGID; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 12); - - currentSession++; - } while ((currentSession <= limitSession) && NT_SUCCESS(status)); - -#ifdef ENABLE_AACS_TESTING - status = STATUS_SUCCESS; -#endif - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsSendCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_SEND_CERTIFICATE -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsSendHostCertificate - - NTSTATUS status = STATUS_SUCCESS; - PAACS_SEND_CERTIFICATE input = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_CERTIFICATE); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - // copy the input buffer to the data buffer for the transfer - { - PCDVD_KEY_HEADER header = (PCDVD_KEY_HEADER)DeviceExtension->ScratchContext.ScratchBuffer; - ULONG tmp = dataTransferLength; - - tmp -= RTL_SIZEOF_THROUGH_FIELD(CDVD_KEY_HEADER, DataLength); - - header->DataLength[0] = (UCHAR)(tmp >> (8*1)); - header->DataLength[1] = (UCHAR)(tmp >> (8*0)); - RtlCopyMemory(header->Data, &(input->Certificate), sizeof(AACS_CERTIFICATE)); - } - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SEND_KEY.OperationCode = SCSIOP_SEND_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.SEND_KEY.ParameterListLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.SEND_KEY.ParameterListLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.SEND_KEY.AGID = (UCHAR)( input->SessionId ); - cdb.SEND_KEY.KeyFormat = 0x01; // Send Host Challenge Certificate - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, FALSE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - *DataLength = 0; - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGetCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_GET_CERTIFICATE -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsGetDriveCertificate - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_CERTIFICATE); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.REPORT_KEY.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.REPORT_KEY.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.REPORT_KEY.AGID = (UCHAR)(*input); - cdb.REPORT_KEY.KeyFormat = 0x01; // Return a drive certificate challenge - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x72, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x31; // '1' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0074, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_CERTIFICATE); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < (sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length))) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGetChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_GET_CHALLENGE_KEY -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsGetChallengeKey - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_CHALLENGE_KEY); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.REPORT_KEY.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.REPORT_KEY.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.REPORT_KEY.AGID = (UCHAR)(*input); - cdb.REPORT_KEY.KeyFormat = 0x02; // Return a drive certificate challenge - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x52, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x32; // '2' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0054, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_CHALLENGE_KEY); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSendChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_SEND_CHALLENGE_KEY -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsSendChallengeKey - - NTSTATUS status = STATUS_SUCCESS; - PAACS_SEND_CHALLENGE_KEY input = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_CHALLENGE_KEY); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - // copy the input buffer to the data buffer for the transfer - { - PCDVD_KEY_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG tmp = dataTransferLength; - tmp -= RTL_SIZEOF_THROUGH_FIELD(CDVD_KEY_HEADER, DataLength); - - header->DataLength[0] = (UCHAR)(tmp >> (8*1)); - header->DataLength[1] = (UCHAR)(tmp >> (8*0)); - RtlCopyMemory(header->Data, &(input->ChallengeKey), sizeof(AACS_CHALLENGE_KEY)); - } - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SEND_KEY.OperationCode = SCSIOP_SEND_KEY; - cdb.AsByte[7] = 0x02; // AACS key class - cdb.SEND_KEY.ParameterListLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.SEND_KEY.ParameterListLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.SEND_KEY.AGID = (UCHAR)( input->SessionId ); - cdb.SEND_KEY.KeyFormat = 0x02; // Send Host Challenge Certificate - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, FALSE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - *DataLength = 0; - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadVolumeId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_READ_VOLUME_ID -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsReadVolumeID - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_VOLUME_ID); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE; - cdb.READ_DVD_STRUCTURE.Format = 0x80; // Return the AACS volumeID - cdb.READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.READ_DVD_STRUCTURE.AGID = (UCHAR)(*input); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x22, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x33; // '3' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0024, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_VOLUME_ID); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadSerialNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_READ_SERIAL_NUMBER -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsReadSerialNumber - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_SERIAL_NUMBER); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE; - cdb.READ_DVD_STRUCTURE.Format = 0x81; // Return the AACS volumeID - cdb.READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.READ_DVD_STRUCTURE.AGID = (UCHAR)(*input); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x22, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x34; // '4' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0024, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_SERIAL_NUMBER); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadMediaId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_READ_MEDIA_ID -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsReadMediaID - - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_MEDIA_ID); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE; - cdb.READ_DVD_STRUCTURE.Format = 0x82; // Return the AACS volumeID - cdb.READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.READ_DVD_STRUCTURE.AGID = (UCHAR)(*input); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x22, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x35; // '5' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0024, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_MEDIA_ID); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_READ_BINDING_NONCE -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsReadBindingNonce - - NTSTATUS status = STATUS_SUCCESS; - PAACS_READ_BINDING_NONCE input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_BINDING_NONCE); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY; - cdb.REPORT_KEY.LogicalBlockAddress[0] = (UCHAR)( input->StartLba >> (3*8) ); - cdb.REPORT_KEY.LogicalBlockAddress[1] = (UCHAR)( input->StartLba >> (2*8) ); - cdb.REPORT_KEY.LogicalBlockAddress[2] = (UCHAR)( input->StartLba >> (1*8) ); - cdb.REPORT_KEY.LogicalBlockAddress[3] = (UCHAR)( input->StartLba >> (0*8) ); - cdb.AsByte[6] = (UCHAR)( input->NumberOfSectors ); - cdb.AsByte[7] = 0x02; // AACS key class - cdb.REPORT_KEY.AllocationLength[0] = (UCHAR)(dataTransferLength >> (8*1)); - cdb.REPORT_KEY.AllocationLength[1] = (UCHAR)(dataTransferLength >> (8*0)); - cdb.REPORT_KEY.AGID = (UCHAR)( input->SessionId ); - cdb.REPORT_KEY.KeyFormat = 0x21; // Return an existing binding nonce - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x22, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x36; // '6' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0024, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_BINDING_NONCE); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGenerateBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - This routine is used to process IOCTL: - IOCTL_AACS_GENERATE_BINDING_NONCE -Arguments: - DeviceExtension - device context - - Request - the request that will be formatted - - RequestParameters - request parameter structur - - DataLength - data transferred length - -Return Value: - NTSTATUS - - --*/ -{ - //AacsGenerateBindingNonce - - NTSTATUS status = STATUS_SUCCESS; - PAACS_READ_BINDING_NONCE input = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&input, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - ULONG dataTransferLength = sizeof(CDVD_KEY_HEADER) + sizeof(AACS_BINDING_NONCE); - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, dataTransferLength, TRUE, &cdb, 12); - -#ifdef ENABLE_AACS_TESTING - static const UCHAR results[] = { 0x00, 0x22, 0x00, 0x00 }; - static const UCHAR defaultFill = 0x37; // '7' - RtlFillMemory(DeviceExtension->ScratchContext.ScratchBuffer, 0x0024, defaultFill); - RtlCopyMemory(DeviceExtension->ScratchContext.ScratchBuffer, results, SIZEOF_ARRAY(results)); - status = STATUS_SUCCESS; -#endif - if (NT_SUCCESS(status)) - { - PDVD_DESCRIPTOR_HEADER header = DeviceExtension->ScratchContext.ScratchBuffer; - ULONG dataLengthToCopy = sizeof(AACS_BINDING_NONCE); - - // make length field native byte ordering - REVERSE_SHORT(&header->Length); - - // exit if getting invalid data from the drive - if (header->Length < sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length)) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - - if (NT_SUCCESS(status)) - { - // adjust data length to reflect only the addition data - header->Length -= sizeof(DVD_DESCRIPTOR_HEADER) - RTL_SIZEOF_THROUGH_FIELD(DVD_DESCRIPTOR_HEADER, Length); - - // exit if the drive is returning an unexpected data size - if (header->Length != dataLengthToCopy) - { - *DataLength = 0; - status = STATUS_IO_DEVICE_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // else copy the data to the user's buffer - RtlCopyMemory(outputBuffer, header->Data, dataLengthToCopy); - *DataLength = dataLengthToCopy; - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - diff --git a/storage/class/cdrom/src/autorun.c b/storage/class/cdrom/src/autorun.c deleted file mode 100644 index 57bacec58..000000000 --- a/storage/class/cdrom/src/autorun.c +++ /dev/null @@ -1,3072 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - autorun.c - -Abstract: - - Code for support of media change detection in the cd/dvd driver - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "mmc.h" -#include "ioctl.h" - -#include "ntstrsafe.h" - -#ifdef DEBUG_USE_WPP -#include "autorun.tmh" -#endif - -#define GESN_TIMEOUT_VALUE (0x4) -#define GESN_BUFFER_SIZE (0x8) -#define GESN_DEVICE_BUSY_LOWER_THRESHOLD_100_MS (2) - -#define MAXIMUM_IMMEDIATE_MCN_RETRIES (0x20) -#define MCN_REG_SUBKEY_NAME (L"MediaChangeNotification") -#define MCN_REG_AUTORUN_DISABLE_INSTANCE_NAME (L"AlwaysDisableMCN") -#define MCN_REG_AUTORUN_ENABLE_INSTANCE_NAME (L"AlwaysEnableMCN") - -// -// Only send polling irp when device is fully powered up and a -// power down irp is not in progress. -// -// NOTE: This helps close a window in time where a polling irp could cause -// a drive to spin up right after it has powered down. The problem is -// that SCSIPORT, ATAPI and SBP2 will be in the process of powering -// down (which may take a few seconds), but won't know that. It would -// then get a polling irp which will be put into its queue since it -// the disk isn't powered down yet. Once the disk is powered down it -// will find the polling irp in the queue and then power up the -// device to do the poll. They do not want to check if the polling -// irp has the SRB_NO_KEEP_AWAKE flag here since it is in a critical -// path and would slow down all I/Os. A better way to fix this -// would be to serialize the polling and power down irps so that -// only one of them is sent to the device at a time. -// - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceIsMediaChangeDisabledDueToHardwareLimitation( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceIsMediaChangeDisabledForClass( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceMediaChangeDeviceInstanceOverride( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN Enabled - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeMcn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN AllowDriveToSleep - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeGesn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -GesnDataInterpret( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PNOTIFICATION_EVENT_STATUS_HEADER Header, - _Out_ PBOOLEAN ResendImmediately - ); - -RTL_QUERY_REGISTRY_ROUTINE DeviceMediaChangeRegistryCallBack; - -EVT_WDF_WORKITEM DeviceDisableGesn; - -#if ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceInitializeMediaChangeDetection) -#pragma alloc_text(PAGE, DeviceEnableMediaChangeDetection) -#pragma alloc_text(PAGE, DeviceDisableMediaChangeDetection) -#pragma alloc_text(PAGE, DeviceSendDelayedMediaChangeNotifications) -#pragma alloc_text(PAGE, DeviceReleaseMcnResources) -#pragma alloc_text(PAGE, DeviceMediaChangeRegistryCallBack) -#pragma alloc_text(PAGE, DeviceInitializeMcn) -#pragma alloc_text(PAGE, DeviceDisableGesn) - -#pragma alloc_text(PAGE, DeviceIsMediaChangeDisabledDueToHardwareLimitation) -#pragma alloc_text(PAGE, DeviceMediaChangeDeviceInstanceOverride) -#pragma alloc_text(PAGE, DeviceIsMediaChangeDisabledForClass) - -#pragma alloc_text(PAGE, DeviceDisableMainTimer) - -#pragma alloc_text(PAGE, GesnDataInterpret) - -#pragma alloc_text(PAGE, RequestSetupMcnRequest) -#pragma alloc_text(PAGE, RequestPostWorkMcnRequest) -#pragma alloc_text(PAGE, RequestSendMcnRequest) - -// -// DeviceEnableMainTimer is called by EvtDeviceD0Entry which can't be made pageable -// so neither is DeviceEnableMainTimer -// -//#pragma alloc_text(PAGE, DeviceEnableMainTimer) - -#pragma alloc_text(PAGE, DeviceInitializeGesn) - -#pragma alloc_text(PAGE, RequestHandleMcnControl) - -#endif - -#pragma warning(push) -#pragma warning(disable:4152) // nonstandard extension, function/data pointer conversion in expression - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -GesnDataInterpret( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PNOTIFICATION_EVENT_STATUS_HEADER Header, - _Out_ PBOOLEAN ResendImmediately - ) -/*++ - -Routine Description: - - This routine will interpret the data returned for a GESN command, and - (if appropriate) set the media change event, and broadcast the - appropriate events to user mode for applications who care. - -Arguments: - - DeviceExtension - the device extension - - Header - the resulting data from a GESN event. - requires at least EIGHT valid bytes (header == 4, data == 4) - - ResendImmediately - whether or not to immediately resend the request. - this should be FALSE if there was no event, FALSE if the reported - event was of the DEVICE BUSY class, else true. - -Return Value: - - STATUS_SUCCESS if successful, an error code otherwise - -Notes: - - DataBuffer must be at least four bytes of valid data (header == 4 bytes), - and have at least eight bytes of allocated memory (all events == 4 bytes). - - The call to StartNextPacket may occur before this routine is completed. - the operational change notifications are informational in nature, and - while useful, are not neccessary to ensure proper operation. For example, - if the device morphs to no longer supporting WRITE commands, all further - write commands will fail. There exists a small timing window wherein - IOCTL_IS_DISK_WRITABLE may be called and get an incorrect response. If - a device supports software write protect, it is expected that the - application can handle such a case. - - NOTE: perhaps setting the updaterequired byte to one should be done here. - if so, it relies upon the setting of a 32-byte value to be an atomic - operation. unfortunately, there is no simple way to notify a class driver - which wants to know that the device behavior requires updating. - - Not ready events may be sent every second. For example, if we were - to minimize the number of asynchronous notifications, an application may - register just after a large busy time was reported. This would then - prevent the application from knowing the device was busy until some - arbitrarily chosen timeout has occurred. Also, the GESN request would - have to still occur, since it checks for non-busy events (such as user - keybutton presses and media change events) as well. The specification - states that the lower-numered events get reported first, so busy events, - while repeating, will only be reported when all other events have been - cleared from the device. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - LONG dataLength = 0; - LONG requiredLength = 0; - BOOLEAN inHomePosition = FALSE; - - PAGED_CODE(); - - // note: don't allocate anything in this routine so that we can - // always just 'return'. - *ResendImmediately = FALSE; - - if (Header->NEA) - { - return status; - } - if (Header->NotificationClass == NOTIFICATION_NO_CLASS_EVENTS) - { - return status; - } - - // HACKHACK - REF #0001 - // This loop is only taken initially, due to the inability to reliably - // auto-detect drives that report events correctly at boot. When we - // detect this behavior during the normal course of running, we will - // disable the hack, allowing more efficient use of the system. This - // should occur "nearly" instantly, as the drive should have multiple - // events queue'd (ie. power, morphing, media). - if (info->Gesn.HackEventMask) - { - // all events use the low four bytes of zero to indicate - // that there was no change in status. - UCHAR thisEvent = Header->ClassEventData[0] & 0xf; - UCHAR lowestSetBit; - UCHAR thisEventBit = (1 << Header->NotificationClass); - - if (!TEST_FLAG(info->Gesn.EventMask, thisEventBit)) - { - // The drive is reporting an event that wasn't requested - return STATUS_DEVICE_PROTOCOL_ERROR; - } - - // some bit magic here... this results in the lowest set bit only - lowestSetBit = info->Gesn.EventMask; - lowestSetBit &= (info->Gesn.EventMask - 1); - lowestSetBit ^= (info->Gesn.EventMask); - - if (thisEventBit != lowestSetBit) - { - // HACKHACK - REF #0001 - // the first time we ever see an event set that is not the lowest - // set bit in the request (iow, highest priority), we know that the - // hack is no longer required, as the device is ignoring "no change" - // events when a real event is waiting in the other requested queues. - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::NONE: Compliant drive found, " - "removing GESN hack (%x, %x)\n", - thisEventBit, info->Gesn.EventMask)); - - info->Gesn.HackEventMask = FALSE; - } - else if (thisEvent == 0) // NOTIFICATION_*_EVENT_NO_CHANGE - { - // HACKHACK - REF #0001 - // note: this hack prevents poorly implemented firmware from constantly - // returning "No Event". we do this by cycling through the - // supported list of events here. - SET_FLAG(info->Gesn.NoChangeEventMask, thisEventBit); - CLEAR_FLAG(info->Gesn.EventMask, thisEventBit); - - // if we have cycled through all supported event types, then - // we need to reset the events we are asking about. else we - // want to resend this request immediately in case there was - // another event pending. - if (info->Gesn.EventMask == 0) - { - info->Gesn.EventMask = info->Gesn.NoChangeEventMask; - info->Gesn.NoChangeEventMask = 0; - } - else - { - *ResendImmediately = TRUE; - } - return status; - } - - } // end if (info->Gesn.HackEventMask) - - dataLength = (Header->EventDataLength[0] << 8) | - (Header->EventDataLength[1] & 0xff); - dataLength -= 2; - requiredLength = 4; // all events are four bytes - - if (dataLength < requiredLength) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "error - GESN returned only %x bytes data for fdo %p\n", - dataLength, DeviceExtension->DeviceObject)); - - return STATUS_DEVICE_PROTOCOL_ERROR; - } - - if (dataLength > requiredLength) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "error - GESN returned too many (%x) bytes data for fdo %p\n", - dataLength, DeviceExtension->DeviceObject)); - } - - if ((Header->ClassEventData[0] & 0xf) == 0) - { - // a zero event is a "no change event, so do not retry - return status; - } - - // because a event other than "no change" occurred, - // we should immediately resend this request. - *ResendImmediately = TRUE; - - switch (Header->NotificationClass) - { - - case NOTIFICATION_OPERATIONAL_CHANGE_CLASS_EVENTS: // 0x01 - { - PNOTIFICATION_OPERATIONAL_STATUS opChangeInfo = - (PNOTIFICATION_OPERATIONAL_STATUS)(Header->ClassEventData); - ULONG event; - - if (opChangeInfo->OperationalEvent == NOTIFICATION_OPERATIONAL_EVENT_CHANGE_REQUESTED) - { - break; - } - - event = (opChangeInfo->Operation[0] << 8) | - (opChangeInfo->Operation[1] ) ; - - // Workaround some hardware that is buggy but prevalent in the market - // This hardware has the property that it will report OpChange events repeatedly, - // causing us to retry immediately so quickly that we will eventually disable - // GESN to prevent an infinite loop. - // (only one valid OpChange event type now, only two ever defined) - if (info->MediaChangeRetryCount >= 4) - { - // - // HACKHACK - REF #0002 - // Some drives incorrectly report OpChange/Change (001b/0001h) events - // continuously when the tray has been ejected. This causes this routine - // to set ResendImmediately to "TRUE", and that results in our cycling - // 32 times immediately resending. At that point, we give up detecting - // the infinite retry loop, and disable GESN on these drives. This - // prevents Media Eject Request (from eject button) from being reported. - // Thus, instead we should attempt to workaround this issue by detecting - // this behavior. - // - - static UCHAR const OpChangeMask = 0x02; - - // At least one device reports "temporarily busy" (which is useless) on eject - // At least one device reports "OpChange" repeatedly when re-inserting media - // All seem to work well using this workaround - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_MCN, - "GESN OpChange events are broken. Working around this problem in software (for WDFDEVICE %p)\n", - DeviceExtension->Device)); - - // OpChange is not the only bit set -- Media class is required.... - NT_ASSERT(CountOfSetBitsUChar(info->Gesn.EventMask) != 1); - - // Force the use of the hackhack (ref #0001) to workaround the - // issue noted this hackhack (ref #0002). - SET_FLAG(info->Gesn.NoChangeEventMask, OpChangeMask); - CLEAR_FLAG(info->Gesn.EventMask, OpChangeMask); - info->Gesn.HackEventMask = TRUE; - - // don't request the opChange event again. use the method - // defined by hackhack (ref #0001) as the workaround. - if (info->Gesn.EventMask == 0) - { - info->Gesn.EventMask = info->Gesn.NoChangeEventMask; - info->Gesn.NoChangeEventMask = 0; - *ResendImmediately = FALSE; - } - else - { - *ResendImmediately = TRUE; - } - - break; - } - - - if ((event == NOTIFICATION_OPERATIONAL_OPCODE_FEATURE_ADDED) | - (event == NOTIFICATION_OPERATIONAL_OPCODE_FEATURE_CHANGE)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN says features added/changed for WDFDEVICE %p\n", - DeviceExtension->Device)); - - // don't notify that new media arrived, just set the - // DO_VERIFY to force a FS reload. - - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - } - - // Call error handler with - // a "fake" media change error in case it needs to update - // internal structures as though a media change occurred. - { - SCSI_REQUEST_BLOCK srb = {0}; - SENSE_DATA sense = {0}; - NTSTATUS tempStatus; - BOOLEAN retry; - - tempStatus = STATUS_MEDIA_CHANGED; - retry = FALSE; - - srb.CdbLength = 6; - srb.Length = sizeof(SCSI_REQUEST_BLOCK); - srb.SrbStatus = SRB_STATUS_AUTOSENSE_VALID | SRB_STATUS_ERROR; - srb.SenseInfoBuffer = &sense; - srb.SenseInfoBufferLength = sizeof(SENSE_DATA); - - sense.AdditionalSenseLength = sizeof(SENSE_DATA) - - RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength); - - sense.SenseKey = SCSI_SENSE_UNIT_ATTENTION; - sense.AdditionalSenseCode = SCSI_ADSENSE_MEDIUM_CHANGED; - - if (DeviceExtension->DeviceAdditionalData.ErrorHandler) - { - DeviceExtension->DeviceAdditionalData.ErrorHandler(DeviceExtension, - &srb, - &tempStatus, - &retry); - } - } // end error handler - - } - break; - } - - case NOTIFICATION_EXTERNAL_REQUEST_CLASS_EVENTS: // 0x3 - { - PNOTIFICATION_EXTERNAL_STATUS externalInfo = - (PNOTIFICATION_EXTERNAL_STATUS)(Header->ClassEventData); - DEVICE_EVENT_EXTERNAL_REQUEST externalData = {0}; - - // unfortunately, due to time constraints, we will only notify - // about keys being pressed, and not released. this makes keys - // single-function, but simplifies the code significantly. - if (externalInfo->ExternalEvent != NOTIFICATION_EXTERNAL_EVENT_BUTTON_DOWN) - { - break; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::EXTERNAL: Event: %x Status %x Req %x\n", - externalInfo->ExternalEvent, externalInfo->ExternalStatus, - (externalInfo->Request[0] << 8) | externalInfo->Request[1] - )); - - externalData.Version = 1; - externalData.DeviceClass = 0; - externalData.ButtonStatus = externalInfo->ExternalEvent; - externalData.Request = (externalInfo->Request[0] << 8) | - (externalInfo->Request[1] & 0xff); - KeQuerySystemTime(&(externalData.SystemTime)); - externalData.SystemTime.QuadPart *= (LONGLONG)KeQueryTimeIncrement(); - - DeviceSendNotification(DeviceExtension, - &GUID_IO_DEVICE_EXTERNAL_REQUEST, - sizeof(DEVICE_EVENT_EXTERNAL_REQUEST), - &externalData); - - return status; - } - - case NOTIFICATION_MEDIA_STATUS_CLASS_EVENTS: // 0x4 - { - PNOTIFICATION_MEDIA_STATUS mediaInfo = - (PNOTIFICATION_MEDIA_STATUS)(Header->ClassEventData); - - if ((mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_NEW_MEDIA) || - (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_MEDIA_CHANGE)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::MEDIA ARRIVAL, Status %x\n", - mediaInfo->MediaStatus)); - - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - } - DeviceSetMediaChangeStateEx(DeviceExtension, - MediaPresent, - NULL); - - // If media is inserted into slot loading type, mark the device active - // to not power off. - if ((DeviceExtension->ZeroPowerODDInfo != NULL) && - (DeviceExtension->ZeroPowerODDInfo->LoadingMechanism == LOADING_MECHANISM_CADDY) && - (DeviceExtension->ZeroPowerODDInfo->Load == 0)) // Slot - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "GesnDataInterpret: MediaArrival event detected, device marked as active\n")); - - DeviceMarkActive(DeviceExtension, TRUE, FALSE); - } - } - else if (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_MEDIA_REMOVAL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::MEDIA REMOVAL, Status %x\n", - mediaInfo->MediaStatus)); - - DeviceSetMediaChangeStateEx(DeviceExtension, - MediaNotPresent, - NULL); - - // If media is removed from slot loading type, start powering off the device - // if it is ZPODD capable. - if ((DeviceExtension->ZeroPowerODDInfo != NULL) && - (DeviceExtension->ZeroPowerODDInfo->LoadingMechanism == LOADING_MECHANISM_CADDY) && - (DeviceExtension->ZeroPowerODDInfo->Load == 0)) // Slot - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "GesnDataInterpret: MediaRemoval event detected, device marked as idle\n")); - - DeviceMarkActive(DeviceExtension, FALSE, FALSE); - } - } - else if (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_EJECT_REQUEST) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::MEDIA EJECTION, Status %x\n", - mediaInfo->MediaStatus)); - - DeviceSendNotification(DeviceExtension, - &GUID_IO_MEDIA_EJECT_REQUEST, - 0, - NULL); - } - - break; - } - - case NOTIFICATION_DEVICE_BUSY_CLASS_EVENTS: // lowest priority events... - { - PNOTIFICATION_BUSY_STATUS busyInfo = - (PNOTIFICATION_BUSY_STATUS)(Header->ClassEventData); - DEVICE_EVENT_BECOMING_READY busyData = {0}; - - // else we want to report the approximated time till it's ready. - busyData.Version = 1; - busyData.Reason = busyInfo->DeviceBusyStatus; - busyData.Estimated100msToReady = (busyInfo->Time[0] << 8) | - (busyInfo->Time[1] & 0xff); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN::BUSY: Event: %x Status %x Time %x\n", - busyInfo->DeviceBusyEvent, busyInfo->DeviceBusyStatus, - busyData.Estimated100msToReady - )); - - // Ignore the notification if the time is small - if (busyData.Estimated100msToReady >= GESN_DEVICE_BUSY_LOWER_THRESHOLD_100_MS) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GesnDataInterpret: media BECOMING_READY\n")); - - DeviceSendNotification(DeviceExtension, - &GUID_IO_DEVICE_BECOMING_READY, - sizeof(DEVICE_EVENT_BECOMING_READY), - &busyData); - } - - // If manual loading operation is observed for slot loading type, start powering off the device - // if it is ZPODD capable. - if ((DeviceExtension->ZeroPowerODDInfo != NULL) && - (DeviceExtension->ZeroPowerODDInfo->LoadingMechanism == LOADING_MECHANISM_TRAY) && - (DeviceExtension->ZeroPowerODDInfo->Load == 0) && // Drawer - (busyInfo->DeviceBusyEvent == NOTIFICATION_BUSY_EVENT_LO_CHANGE) && - (busyInfo->DeviceBusyStatus == NOTIFICATION_BUSY_STATUS_NO_EVENT)) - { - inHomePosition = DeviceZPODDIsInHomePosition(DeviceExtension); - - if (inHomePosition == FALSE) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "GesnDataInterpret: LoChange event detected, device marked as active\n")); - - DeviceMarkActive(DeviceExtension, TRUE, FALSE); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "GesnDataInterpret: LoChange event detected, device marked as idle\n")); - - DeviceMarkActive(DeviceExtension, FALSE, FALSE); - } - } - - break; - } - - default: - { - break; - } - - } // end switch on notification class - - return status; -} - - -VOID -DeviceInternalSetMediaChangeState( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ MEDIA_CHANGE_DETECTION_STATE NewState, - _Inout_opt_ PMEDIA_CHANGE_DETECTION_STATE OldState - ) -/*++ - -Routine Description: - - This routine will (if appropriate) set the media change event for the - device. The event will be set if the media state is changed and - media change events are enabled. Otherwise the media state will be - tracked but the event will not be set. - - This routine will lock out the other media change routines if possible - but if not a media change notification may be lost after the enable has - been completed. - -Arguments: - - DeviceExtension - the device extension - - NewState - new state for setting - - OldState - optional storage for the old state - -Return Value: - - none - ---*/ -{ -#if DBG - LPCSTR states[] = {"Unknown", "Present", "Not Present", "Unavailable"}; -#endif - MEDIA_CHANGE_DETECTION_STATE oldMediaState; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - CLASS_MEDIA_CHANGE_CONTEXT mcnContext; - - if (!((NewState >= MediaUnknown) && (NewState <= MediaUnavailable))) - { - return; - } - - if (info == NULL) - { - return; - } - - oldMediaState = info->LastKnownMediaDetectionState; - if (OldState) - { - *OldState = oldMediaState; - } - - info->LastKnownMediaDetectionState = NewState; - - // Increment MediaChangeCount on transition to MediaPresent - if (NewState == MediaPresent && oldMediaState != NewState) - { - InterlockedIncrement((PLONG)&DeviceExtension->MediaChangeCount); - } - - if (info->MediaChangeDetectionDisableCount != 0) - { -#if DBG - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInternalSetMediaChangeState: MCN not enabled, state " - "changed from %s to %s\n", - states[oldMediaState], states[NewState])); -#endif - return; - } -#if DBG - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInternalSetMediaChangeState: State change from %s to %s\n", - states[oldMediaState], states[NewState])); -#endif - - if (info->LastReportedMediaDetectionState == info->LastKnownMediaDetectionState) - { - // Media is in the same state as we reported last time, no need to report again. - return; - } - - // make the data useful -- it used to always be zero. - mcnContext.MediaChangeCount = DeviceExtension->MediaChangeCount; - mcnContext.NewState = NewState; - - if (NewState == MediaPresent) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInternalSetMediaChangeState: Reporting media ARRIVAL\n")); - - DeviceSendNotification(DeviceExtension, - &GUID_IO_MEDIA_ARRIVAL, - sizeof(CLASS_MEDIA_CHANGE_CONTEXT), - &mcnContext); - } - else if ((NewState == MediaNotPresent) || (NewState == MediaUnavailable)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInternalSetMediaChangeState: Reporting media REMOVAL\n")); - DeviceSendNotification(DeviceExtension, - &GUID_IO_MEDIA_REMOVAL, - sizeof(CLASS_MEDIA_CHANGE_CONTEXT), - &mcnContext); - } - else - { - // Don't notify of changed going to unknown. - return; - } - - info->LastReportedMediaDetectionState = info->LastKnownMediaDetectionState; - - return; -} // end DeviceInternalSetMediaChangeState() - - -VOID -DeviceSetMediaChangeStateEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ MEDIA_CHANGE_DETECTION_STATE NewState, - _Inout_opt_ PMEDIA_CHANGE_DETECTION_STATE OldState - ) -/*++ - -Routine Description: - - This routine will (if appropriate) set the media change event for the - device. The event will be set if the media state is changed and - media change events are enabled. Otherwise the media state will be - tracked but the event will not be set. - -Arguments: - - DeviceExtension - the device extension - - NewState - new state for setting - - OldState - optional storage for the old state - -Return Value: - - none - ---*/ -{ - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - LARGE_INTEGER zero; - NTSTATUS status; - - // timeout value must be 0, as this function can be called at DISPATCH_LEVEL. - zero.QuadPart = 0; - - if (info == NULL) - { - return; - } - - status = KeWaitForMutexObject(&info->MediaChangeMutex, - Executive, - KernelMode, - FALSE, - &zero); - - if (status == STATUS_TIMEOUT) - { - // Someone else is in the process of setting the media state. - return; - } - - // Change the media present state and signal an event, if applicable - DeviceInternalSetMediaChangeState(DeviceExtension, NewState, OldState); - - KeReleaseMutex(&info->MediaChangeMutex, FALSE); - - return; -} // end DeviceSetMediaChangeStateEx() - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceSendDelayedMediaChangeNotifications( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine sends the so-called delayed media change notifications. - These notifications get accumulated while the MCN mechanism is disabled - and need to be sent to the application on MCN enabling, if MCN enabling - happens as a part of exclusive access unlock and the application has not - requested us explicitly to not send the delayed notifications. - -Arguments: - - DeviceExtension - the device extension - -Return Value: - - none - ---*/ -{ - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - LARGE_INTEGER zero; - NTSTATUS status; - - PAGED_CODE(); - - zero.QuadPart = 0; - - if (info == NULL) - { - return; - } - - status = KeWaitForMutexObject(&info->MediaChangeMutex, - Executive, - KernelMode, - FALSE, - &zero); - - if (status == STATUS_TIMEOUT) - { - // Someone else is in the process of setting the media state. - // That's totally okay, we'll send delayed notifications later. - return; - } - - // If the last reported state and the last known state are different and - // MCN is enabled, generate a notification based on the last known state. - if ((info->LastKnownMediaDetectionState != info->LastReportedMediaDetectionState) && - (info->MediaChangeDetectionDisableCount == 0)) - { - DeviceInternalSetMediaChangeState(DeviceExtension, info->LastKnownMediaDetectionState, NULL); - } - - KeReleaseMutex(&info->MediaChangeMutex, FALSE); - - return; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestSetupMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN UseGesn -) -/*++ - -Routine Description: - - This routine sets up the fields of the request for MCN - -Arguments: - DeviceExtension - device context - - UseGesn - If TRUE, the device supports GESN and it's currently the mechanism for MCN - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSCSI_REQUEST_BLOCK srb; - PIRP irp; - PIO_STACK_LOCATION nextIrpStack; - PCDB cdb; - PVOID buffer; - WDF_REQUEST_REUSE_PARAMS params; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - - PAGED_CODE(); - - irp = WdfRequestWdmGetIrp(info->MediaChangeRequest); - NT_ASSERT(irp != NULL); - - // deassign the MdlAddress, this is the value we assign explicitly. - // this is to prevent WdfRequestReuse to release the Mdl unexpectly. - if (irp->MdlAddress) - { - irp->MdlAddress = NULL; - } - - if (NT_SUCCESS(status)) - { - // Setup the IRP to perform a test unit ready. - WDF_REQUEST_REUSE_PARAMS_INIT(¶ms, - WDF_REQUEST_REUSE_NO_FLAGS, - STATUS_NOT_SUPPORTED); - - status = WdfRequestReuse(info->MediaChangeRequest, ¶ms); - } - - if (NT_SUCCESS(status)) - { - // Format the request. - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - info->MediaChangeRequest, - IOCTL_SCSI_EXECUTE_IN, - NULL, NULL, - NULL, NULL, - NULL, NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "RequestSetupMcnRequest: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n", - status)); - } - } - - if (NT_SUCCESS(status)) - { - RequestClearSendTime(info->MediaChangeRequest); - - nextIrpStack = IoGetNextIrpStackLocation(irp); - - nextIrpStack->Flags = SL_OVERRIDE_VERIFY_VOLUME; - nextIrpStack->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; - nextIrpStack->Parameters.Scsi.Srb = &(info->MediaChangeSrb); - - // Prepare the SRB for execution. - srb = nextIrpStack->Parameters.Scsi.Srb; - buffer = info->SenseBuffer; - RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK)); - RtlZeroMemory(buffer, SENSE_BUFFER_SIZE); - - srb->QueueTag = SP_UNTAGGED; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - srb->Length = sizeof(SCSI_REQUEST_BLOCK); - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->SenseInfoBuffer = buffer; - srb->SrbStatus = 0; - srb->ScsiStatus = 0; - srb->OriginalRequest = irp; - srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE; - - srb->SrbFlags = DeviceExtension->SrbFlags; - SET_FLAG(srb->SrbFlags, info->SrbFlags); - - if (!UseGesn) - { - srb->TimeOutValue = CDROM_TEST_UNIT_READY_TIMEOUT; - srb->CdbLength = 6; - srb->DataTransferLength = 0; - SET_FLAG(srb->SrbFlags, SRB_FLAGS_NO_DATA_TRANSFER); - nextIrpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_NONE; - srb->DataBuffer = NULL; - srb->DataTransferLength = 0; - irp->MdlAddress = NULL; - - cdb = (PCDB) &srb->Cdb[0]; - cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY; - } - else - { - NT_ASSERT(info->Gesn.Buffer); - - srb->TimeOutValue = GESN_TIMEOUT_VALUE; // much shorter timeout for GESN - - srb->CdbLength = 10; - SET_FLAG(srb->SrbFlags, SRB_FLAGS_DATA_IN); - nextIrpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_IN; - srb->DataBuffer = info->Gesn.Buffer; - srb->DataTransferLength = info->Gesn.BufferSize; - irp->MdlAddress = info->Gesn.Mdl; - - cdb = (PCDB) &srb->Cdb[0]; - cdb->GET_EVENT_STATUS_NOTIFICATION.OperationCode = SCSIOP_GET_EVENT_STATUS; - cdb->GET_EVENT_STATUS_NOTIFICATION.Immediate = 1; - cdb->GET_EVENT_STATUS_NOTIFICATION.EventListLength[0] = (UCHAR)((info->Gesn.BufferSize) >> 8); - cdb->GET_EVENT_STATUS_NOTIFICATION.EventListLength[1] = (UCHAR)((info->Gesn.BufferSize) & 0xff); - cdb->GET_EVENT_STATUS_NOTIFICATION.NotificationClassRequest = info->Gesn.EventMask; - } - } - - return status; -} - - -VOID -DeviceDisableGesn( - _In_ WDFWORKITEM WorkItem - ) -/*++ - -Routine Description: - - Work item routine to set the hack flag in the registry to disable GESN - This routine is invoked when the device reports TOO many events that affects system - -Arguments: - WorkItem - the work item be perfromed. - -Return Value: - None - ---*/ -{ - WDFDEVICE device = WdfWorkItemGetParentObject(WorkItem); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - - PAGED_CODE(); - - // - // Set the hack flag in the registry - // - DeviceSetParameter(deviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - CdromDetectionUnsupported); - - WdfObjectDelete(WorkItem); - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -RequestPostWorkMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine handles the completion of the test unit ready irps used to - determine if the media has changed. If the media has changed, this code - signals the named event to wake up other system services that react to - media change (aka AutoPlay). - -Arguments: - - DeviceExtension - the device context - -Return Value: - - BOOLEAN - TRUE (needs retry); FALSE (shoule not retry) - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - PIRP irp; - BOOLEAN retryImmediately = FALSE; - - PAGED_CODE(); - - NT_ASSERT(info->MediaChangeRequest != NULL); - irp = WdfRequestWdmGetIrp(info->MediaChangeRequest); - - NT_ASSERT(!TEST_FLAG(info->MediaChangeSrb.SrbStatus, SRB_STATUS_QUEUE_FROZEN)); - - // use InterpretSenseInfo routine to check for media state, and also - // to call ClassError() with correct parameters. - if (SRB_STATUS(info->MediaChangeSrb.SrbStatus) != SRB_STATUS_SUCCESS) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, "MCN request - failed - srb status=%x, sense=%x/%x/%x.\n", - info->MediaChangeSrb.SrbStatus, - ((PSENSE_DATA)(info->MediaChangeSrb.SenseInfoBuffer))->SenseKey, - ((PSENSE_DATA)(info->MediaChangeSrb.SenseInfoBuffer))->AdditionalSenseCode, - ((PSENSE_DATA)(info->MediaChangeSrb.SenseInfoBuffer))->AdditionalSenseCodeQualifier)); - - if (SRB_STATUS(info->MediaChangeSrb.SrbStatus) != SRB_STATUS_NOT_POWERED) - { - // Release the queue if it is frozen. - if (info->MediaChangeSrb.SrbStatus & SRB_STATUS_QUEUE_FROZEN) - { - DeviceReleaseQueue(DeviceExtension->Device); - } - - RequestSenseInfoInterpret(DeviceExtension, - info->MediaChangeRequest, - &info->MediaChangeSrb, - 0, - &status, - NULL); - } - } - else - { - DeviceExtension->PrivateFdoData->LoggedTURFailureSinceLastIO = FALSE; - - if (!info->Gesn.Supported) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "MCN request - succeeded (GESN NOT supported, setting MediaPresent).\n")); - - // success != media for GESN case - DeviceSetMediaChangeStateEx(DeviceExtension, - MediaPresent, - NULL); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "MCN request - succeeded (GESN supported).\n")); - } - } - - if (info->Gesn.Supported) - { - if (status == STATUS_DATA_OVERRUN) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, "MCN Request - Data Overrun\n")); - status = STATUS_SUCCESS; - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, "MCN Request: GESN failed with status %x\n", status)); - } - else - { - // for GESN, need to interpret the results of the data. - // this may also require an immediate retry - if (irp->IoStatus.Information == 8 ) - { - GesnDataInterpret(DeviceExtension, - (PVOID)info->Gesn.Buffer, - &retryImmediately); - } - - } // end of NT_SUCCESS(status) - - } // end of Info->Gesn.Supported - - // free port-allocated sense buffer, if any. - if (PORT_ALLOCATED_SENSE(DeviceExtension, &info->MediaChangeSrb)) - { - FREE_PORT_ALLOCATED_SENSE_BUFFER(DeviceExtension, &info->MediaChangeSrb); - } - - // Remember the IRP and SRB for use the next time. - NT_ASSERT(IoGetNextIrpStackLocation(irp)); - IoGetNextIrpStackLocation(irp)->Parameters.Scsi.Srb = &info->MediaChangeSrb; - - // run a sanity check to make sure we're not recursing continuously - if (retryImmediately) - { - info->MediaChangeRetryCount++; - - if (info->MediaChangeRetryCount > MAXIMUM_IMMEDIATE_MCN_RETRIES) - { - // Disable GESN on this device. - // Create a work item to set the value in the registry - WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; - WDFWORKITEM workItem; - - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = DeviceExtension->Device; - - WDF_WORKITEM_CONFIG_INIT(&workitemConfig, DeviceDisableGesn); - workitemConfig.AutomaticSerialization = FALSE; - - status = WdfWorkItemCreate(&workitemConfig, - &attributes, - &workItem); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, "MCN Request: Disabling GESN for WDFDEVICE %p\n", DeviceExtension->Device)); - - if (NT_SUCCESS(status)) - { - WdfWorkItemEnqueue(workItem); - } - - info->Gesn.Supported = FALSE; - info->Gesn.EventMask = 0; - info->Gesn.BufferSize = 0; - info->MediaChangeRetryCount = 0; - retryImmediately = FALSE; - // should we log an error in event log? - } - } - else - { - info->MediaChangeRetryCount = 0; - } - - return retryImmediately; -} - - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -RequestSendMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine sends the formatted MCN request sychronizely to lower driver. - -Arguments: - - DeviceExtension - the device context - -Return Value: - BOOLEAN - TRUE (requst successfully sent); FALSE (request failed to send) - ---*/ -{ - BOOLEAN requestSent = FALSE; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - - PAGED_CODE(); - - RequestSend(DeviceExtension, - info->MediaChangeRequest, - DeviceExtension->IoTarget, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - &requestSent); - - return requestSent; -} // end RequestSendMcnRequest() - - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeMcn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN AllowDriveToSleep - ) -/*++ - -Routine Description: - - This routine initialize the contents of MCN structure. - -Arguments: - - DeviceExtension - the device extension - - AllowDriveToSleep - for CDROM, this parameter should be always FALSE - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMEDIA_CHANGE_DETECTION_INFO mediaChangeInfo = NULL; - PIRP irp = NULL; - PVOID senseBuffer = NULL; - WDF_OBJECT_ATTRIBUTES attributes; - - PAGED_CODE(); - - if (DeviceExtension->MediaChangeDetectionInfo != NULL) - { - //Already initialized. - return STATUS_SUCCESS; - } - - DeviceExtension->KernelModeMcnContext.FileObject = (PVOID)-1; - DeviceExtension->KernelModeMcnContext.DeviceObject = (PVOID)-1; - DeviceExtension->KernelModeMcnContext.LockCount = 0; - DeviceExtension->KernelModeMcnContext.McnDisableCount = 0; - - mediaChangeInfo = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(MEDIA_CHANGE_DETECTION_INFO), - CDROM_TAG_MEDIA_CHANGE_DETECTION); - - if (mediaChangeInfo == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - - if (NT_SUCCESS(status)) - { - if ((DeviceExtension->PowerDescriptor != NULL) && - (DeviceExtension->PowerDescriptor->AsynchronousNotificationSupported != FALSE) && - (!TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_NO_ASYNCHRONOUS_NOTIFICATION))) - { - mediaChangeInfo->AsynchronousNotificationSupported = TRUE; - } - } - - // Allocate an IRP to carry the IOCTL_MCN_SYNC_FAKE_IOCTL. - if (NT_SUCCESS(status)) - { - irp = IoAllocateIrp(DeviceExtension->DeviceObject->StackSize, FALSE); - - if (irp == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - attributes.ParentObject = DeviceExtension->Device; - status = WdfRequestCreate(&attributes, - DeviceExtension->IoTarget, - &mediaChangeInfo->MediaChangeRequest); - } - - if (NT_SUCCESS(status)) - { - // Preformat the media change request. With this being done, we never need to worry about - // WdfIoTargetFormatRequestForInternalIoctlOthers ever failing later. - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - mediaChangeInfo->MediaChangeRequest, - IOCTL_SCSI_EXECUTE_IN, - NULL, NULL, - NULL, NULL, - NULL, NULL); - } - - if (NT_SUCCESS(status)) - { - senseBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - SENSE_BUFFER_SIZE, - CDROM_TAG_MEDIA_CHANGE_DETECTION); - if (senseBuffer == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - mediaChangeInfo->MediaChangeSyncIrp = irp; - mediaChangeInfo->SenseBuffer = senseBuffer; - - // Set default values for the media change notification - // configuration. - mediaChangeInfo->MediaChangeDetectionDisableCount = 0; - - // Assume that there is initially no media in the device - // only notify upper layers if there is something there - mediaChangeInfo->LastKnownMediaDetectionState = MediaUnknown; - mediaChangeInfo->LastReportedMediaDetectionState = MediaUnknown; - - // setup all extra flags we'll be setting for this irp - mediaChangeInfo->SrbFlags = 0; - - SET_FLAG(mediaChangeInfo->SrbFlags, SRB_CLASS_FLAGS_LOW_PRIORITY); - SET_FLAG(mediaChangeInfo->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); - SET_FLAG(mediaChangeInfo->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER); - - if (AllowDriveToSleep) //FALSE for CD/DVD devices - { - SET_FLAG(mediaChangeInfo->SrbFlags, SRB_FLAGS_NO_KEEP_AWAKE); - } - - KeInitializeMutex(&mediaChangeInfo->MediaChangeMutex, 0x100); - - // It is ok to support media change events on this device. - DeviceExtension->MediaChangeDetectionInfo = mediaChangeInfo; - - // check the device supports GESN or not, initialize GESN structure if it supports. - { - // This is only valid for type5 devices. - NTSTATUS tempStatus = STATUS_SUCCESS; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMcn: Testing for GESN\n")); - tempStatus = DeviceInitializeGesn(DeviceExtension); - - if (NT_SUCCESS(tempStatus)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMcn: GESN available for %p\n", - DeviceExtension->DeviceObject)); - NT_ASSERT(mediaChangeInfo->Gesn.Supported ); - NT_ASSERT(mediaChangeInfo->Gesn.Buffer != NULL); - NT_ASSERT(mediaChangeInfo->Gesn.BufferSize != 0); - NT_ASSERT(mediaChangeInfo->Gesn.EventMask != 0); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMcn: GESN *NOT* available for %p\n", - DeviceExtension->DeviceObject)); - NT_ASSERT(!mediaChangeInfo->Gesn.Supported); - NT_ASSERT(mediaChangeInfo->Gesn.Buffer == NULL); - NT_ASSERT(mediaChangeInfo->Gesn.BufferSize == 0); - NT_ASSERT(mediaChangeInfo->Gesn.EventMask == 0); - mediaChangeInfo->Gesn.Supported = FALSE; // just in case.... - } - } - } - - if (NT_SUCCESS(status)) - { - // Register for display state change on AOAC capable systems so we can put the - // device to low power state when not required. - if (mediaChangeInfo->DisplayStateCallbackHandle == NULL) - { - POWER_PLATFORM_INFORMATION PlatformInfo = {0}; - - status = ZwPowerInformation(PlatformInformation, - NULL, - 0, - &PlatformInfo, - sizeof(PlatformInfo)); - - if (NT_SUCCESS(status) && PlatformInfo.AoAc) - { - PoRegisterPowerSettingCallback(DeviceExtension->DeviceObject, - &GUID_CONSOLE_DISPLAY_STATE, - &DevicePowerSettingCallback, - DeviceExtension, - &mediaChangeInfo->DisplayStateCallbackHandle); - } - - // Ignore any failures above. - status = STATUS_SUCCESS; - } - } - - if (!NT_SUCCESS(status)) - { - if (irp != NULL) - { - IoFreeIrp(irp); - } - FREE_POOL(senseBuffer); - FREE_POOL(mediaChangeInfo); - } - - return status; - -} // end DeviceInitializeMcn() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeGesn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine initialize the contents of GESN structure. - -Arguments: - - DeviceExtension - the device extension - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PNOTIFICATION_EVENT_STATUS_HEADER header = NULL; - CDROM_DETECTION_STATE detectionState = CdromDetectionUnknown; - PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = DeviceExtension->DeviceDescriptor; - BOOLEAN retryImmediately = TRUE; - ULONG i = 0; - ULONG atapiResets = 0; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - - PAGED_CODE(); - - NT_ASSERT(info != NULL); - - // read if we already know the abilities of the device - DeviceGetParameter(DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - (PULONG)&detectionState); - - if (detectionState == CdromDetectionUnsupported) - { - status = STATUS_NOT_SUPPORTED; - } - - // check if the device has a hack flag saying never to try this. - if (NT_SUCCESS(status) && - (TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_GESN_IS_BAD)) ) - { - DeviceSetParameter(DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - CdromDetectionUnsupported); - status = STATUS_NOT_SUPPORTED; - } - - // else go through the process since we allocate buffers and - // get all sorts of device settings. - if (NT_SUCCESS(status)) - { - if (info->Gesn.Buffer == NULL) - { - info->Gesn.Buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - GESN_BUFFER_SIZE, - CDROM_TAG_GESN); - } - - if (info->Gesn.Buffer == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - if (info->Gesn.Mdl != NULL) - { - IoFreeMdl(info->Gesn.Mdl); - } - - info->Gesn.Mdl = IoAllocateMdl(info->Gesn.Buffer, - GESN_BUFFER_SIZE, - FALSE, - FALSE, - NULL); - if (info->Gesn.Mdl == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - MmBuildMdlForNonPagedPool(info->Gesn.Mdl); - info->Gesn.BufferSize = GESN_BUFFER_SIZE; - info->Gesn.EventMask = 0; - - // all items are prepared to use GESN (except the event mask, so don't - // optimize this part out!). - // - // now see if it really works. we have to loop through this because - // many SAMSUNG (and one COMPAQ) drives timeout when requesting - // NOT_READY events, even when the IMMEDIATE bit is set. :( - // - // using a drive list is cumbersome, so this might fix the problem. - for (i = 0; (i < 16) && retryImmediately; i++) - { - status = RequestSetupMcnRequest(DeviceExtension, TRUE); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "Setup Mcn request failed %x for WDFDEVICE %p\n", - status, DeviceExtension->Device)); - break; - } - - NT_ASSERT(TEST_FLAG(info->MediaChangeSrb.SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE)); - - status = DeviceSendRequestSynchronously(DeviceExtension->Device, info->MediaChangeRequest, TRUE); - - if (SRB_STATUS(info->MediaChangeSrb.SrbStatus) != SRB_STATUS_SUCCESS) - { - // Release the queue if it is frozen. - if (info->MediaChangeSrb.SrbStatus & SRB_STATUS_QUEUE_FROZEN) - { - DeviceReleaseQueue(DeviceExtension->Device); - } - - RequestSenseInfoInterpret(DeviceExtension, - info->MediaChangeRequest, - &(info->MediaChangeSrb), - 0, - &status, - NULL); - } - - if ((deviceDescriptor->BusType == BusTypeAtapi) && - (info->MediaChangeSrb.SrbStatus == SRB_STATUS_BUS_RESET)) - { - // - // ATAPI unfortunately returns SRB_STATUS_BUS_RESET instead - // of SRB_STATUS_TIMEOUT, so we cannot differentiate between - // the two. if we get this status four time consecutively, - // stop trying this command. it is too late to change ATAPI - // at this point, so special-case this here. (07/10/2001) - // NOTE: any value more than 4 may cause the device to be - // marked missing. - // - atapiResets++; - if (atapiResets >= 4) - { - status = STATUS_IO_DEVICE_ERROR; - break; - } - } - - if (status == STATUS_DATA_OVERRUN) - { - status = STATUS_SUCCESS; - } - - if ((status == STATUS_INVALID_DEVICE_REQUEST) || - (status == STATUS_TIMEOUT) || - (status == STATUS_IO_DEVICE_ERROR) || - (status == STATUS_IO_TIMEOUT)) - { - // with these error codes, we don't ever want to try this command - // again on this device, since it reacts poorly. - DeviceSetParameter( DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - CdromDetectionUnsupported); - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "GESN test failed %x for WDFDEVICE %p\n", - status, DeviceExtension->Device)); - break; - } - - if (!NT_SUCCESS(status)) - { - // this may be other errors that should not disable GESN - // for all future start_device calls. - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "GESN test failed %x for WDFDEVICE %p\n", - status, DeviceExtension->Device)); - break; - } - else if (i == 0) - { - // the first time, the request was just retrieving a mask of - // available bits. use this to mask future requests. - header = (PNOTIFICATION_EVENT_STATUS_HEADER)(info->Gesn.Buffer); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "WDFDEVICE %p supports event mask %x\n", - DeviceExtension->Device, header->SupportedEventClasses)); - - if (TEST_FLAG(header->SupportedEventClasses, - NOTIFICATION_MEDIA_STATUS_CLASS_MASK)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN supports MCN\n")); - } - if (TEST_FLAG(header->SupportedEventClasses, - NOTIFICATION_DEVICE_BUSY_CLASS_MASK)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN supports DeviceBusy\n")); - } - if (TEST_FLAG(header->SupportedEventClasses, - NOTIFICATION_OPERATIONAL_CHANGE_CLASS_MASK)) - { - if (TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, - FDO_HACK_GESN_IGNORE_OPCHANGE)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN supports OpChange, but must ignore these events for compatibility\n")); - CLEAR_FLAG(header->SupportedEventClasses, - NOTIFICATION_OPERATIONAL_CHANGE_CLASS_MASK); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN supports OpChange\n")); - } - } - info->Gesn.EventMask = header->SupportedEventClasses; - - // - // realistically, we are only considering the following events: - // EXTERNAL REQUEST - this is being tested for play/stop/etc. - // MEDIA STATUS - autorun and ejection requests. - // DEVICE BUSY - to allow us to predict when media will be ready. - // therefore, we should not bother querying for the other, - // unknown events. clear all but the above flags. - // - info->Gesn.EventMask &= NOTIFICATION_OPERATIONAL_CHANGE_CLASS_MASK | - NOTIFICATION_EXTERNAL_REQUEST_CLASS_MASK | - NOTIFICATION_MEDIA_STATUS_CLASS_MASK | - NOTIFICATION_DEVICE_BUSY_CLASS_MASK ; - - - // - // HACKHACK - REF #0001 - // Some devices will *never* report an event if we've also requested - // that it report lower-priority events. this is due to a - // misunderstanding in the specification wherein a "No Change" is - // interpreted to be a real event. what should occur is that the - // device should ignore "No Change" events when multiple event types - // are requested unless there are no other events waiting. this - // greatly reduces the number of requests that the host must send - // to determine if an event has occurred. Since we must work on all - // drives, default to enabling the hack until we find evidence of - // proper firmware. - // - if (info->Gesn.EventMask == 0) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN supported, but not mask we care about (%x) for FDO %p\n", - header->SupportedEventClasses, - DeviceExtension->DeviceObject)); - // NOTE: the status is still status_sucess. - break; - } - else if (CountOfSetBitsUChar(info->Gesn.EventMask) == 1) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN hack not required for FDO %p\n", - DeviceExtension->DeviceObject)); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN hack enabled for FDO %p\n", - DeviceExtension->DeviceObject)); - info->Gesn.HackEventMask = 1; - } - } - else - { - // i > 0; not the first time looping through, so interpret the results. - status = GesnDataInterpret(DeviceExtension, - (PVOID)info->Gesn.Buffer, - &retryImmediately); - - if (!NT_SUCCESS(status)) - { - // This drive does not support GESN correctly - DeviceSetParameter( DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - CdromDetectionUnsupported); - break; - } - } - } // end 'for' loop of GESN requests.... - } - - if (NT_SUCCESS(status)) - { - // - // we can only use this if it can be relied upon for media changes, - // since we are (by definition) no longer going to be polling via - // a TEST_UNIT_READY irp, and drives will not report UNIT ATTENTION - // for this command (although a filter driver, such as one for burning - // cd's, might still fake those errors). - // - // since we also rely upon NOT_READY events to change the cursor - // into a "wait" cursor; GESN is still more reliable than other - // methods, and includes eject button requests, so we'll use it - // without DEVICE_BUSY in Windows Vista. - // - - if (TEST_FLAG(info->Gesn.EventMask, NOTIFICATION_MEDIA_STATUS_CLASS_MASK)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "Enabling GESN support for WDFDEVICE %p\n", - DeviceExtension->Device)); - info->Gesn.Supported = TRUE; - - DeviceSetParameter( DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_MMC_DETECTION_VALUE_NAME, - CdromDetectionSupported); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "GESN available but not enabled for WDFDEVICE %p\n", - DeviceExtension->Device)); - status = STATUS_NOT_SUPPORTED; - } - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "GESN support detection failed for WDFDEVICE %p with status %08x\n", - DeviceExtension->Device, status)); - - if (info->Gesn.Mdl) - { - PIRP irp = WdfRequestWdmGetIrp(info->MediaChangeRequest); - - IoFreeMdl(info->Gesn.Mdl); - info->Gesn.Mdl = NULL; - irp->MdlAddress = NULL; - } - - FREE_POOL(info->Gesn.Buffer); - info->Gesn.Supported = FALSE; - info->Gesn.EventMask = 0; - info->Gesn.BufferSize = 0; - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine checks to see if it is safe to initialize MCN (the back end - to autorun) for a given device. It will then check the device-type wide - key "Autorun" in the service key (for legacy reasons), and then look in - the device-specific key to potentially override that setting. - - If MCN is to be enabled, all neccessary structures and memory are - allocated and initialized. - - This routine MUST be called only from the DeviceInit...() . - -Arguments: - - DeviceExtension - the device to initialize MCN for, if appropriate - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - BOOLEAN disabled = FALSE; - BOOLEAN instanceOverride; - - PAGED_CODE(); - - // NOTE: This assumes that DeviceInitializeMediaChangeDetection is always - // called in the context of the DeviceInitDevicePhase2. If called - // after then this check will have already been made and the - // once a second timer will not have been enabled. - - disabled = DeviceIsMediaChangeDisabledDueToHardwareLimitation(DeviceExtension); - - if (disabled) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMediaChangeDetection: Disabled due to hardware" - "limitations for this device\n")); - } - else - { - // autorun should now be enabled by default for all media types. - disabled = DeviceIsMediaChangeDisabledForClass(DeviceExtension); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMediaChangeDetection: MCN is %s\n", - (disabled ? "disabled" : "enabled"))); - - status = DeviceMediaChangeDeviceInstanceOverride(DeviceExtension, - &instanceOverride); // default value - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMediaChangeDetection: Instance using default\n")); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMediaChangeDetection: Instance override: %s MCN\n", - (instanceOverride ? "Enabling" : "Disabling"))); - disabled = !instanceOverride; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceInitializeMediaChangeDetection: Instance MCN is %s\n", - (disabled ? "disabled" : "enabled"))); - } - - if (!disabled) - { - // if the drive is not a CDROM, allow the drive to sleep - status = DeviceInitializeMcn(DeviceExtension, FALSE); - } - - return status; -} // end DeviceInitializeMediaChangeDetection() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceMediaChangeDeviceInstanceOverride( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN Enabled - ) -/*++ - -Routine Description: - - The user can override the global setting to enable or disable Autorun on a - specific cdrom device via the control panel. This routine checks and/or - sets this value. - -Arguments: - - DeviceExtension - the device to set/get the value for - - Enabled - TRUE (Autorun is enabled) - FALSE (Autorun is disabled) -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_UNSUCCESSFUL; - WDFKEY deviceKey = NULL; - WDFKEY subKey = NULL; - - UNICODE_STRING subkeyName; - UNICODE_STRING enableMcnValueName; - UNICODE_STRING disableMcnValueName; - ULONG alwaysEnable = 0; - ULONG alwaysDisable = 0; - - PAGED_CODE(); - - status = WdfDeviceOpenRegistryKey(DeviceExtension->Device, - PLUGPLAY_REGKEY_DEVICE, - KEY_ALL_ACCESS, - WDF_NO_OBJECT_ATTRIBUTES, - &deviceKey); - if (!NT_SUCCESS(status)) - { - // this can occur when a new device is added to the system - // this is due to cdrom.sys being an 'essential' driver - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: " - "Could not open device registry key [%lx]\n", status)); - } - else - { - RtlInitUnicodeString(&subkeyName, MCN_REG_SUBKEY_NAME); - - status = WdfRegistryOpenKey(deviceKey, - &subkeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &subKey); - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: " - "subkey could not be created. %lx\n", status)); - } - else - { - // Default to not changing autorun behavior, based upon setting - // registryValue to zero. - RtlInitUnicodeString(&enableMcnValueName, MCN_REG_AUTORUN_ENABLE_INSTANCE_NAME); - RtlInitUnicodeString(&disableMcnValueName, MCN_REG_AUTORUN_DISABLE_INSTANCE_NAME); - - // Ignore failures on reading of subkeys - (VOID) WdfRegistryQueryULong(subKey, - &enableMcnValueName, - &alwaysEnable); - (VOID) WdfRegistryQueryULong(subKey, - &disableMcnValueName, - &alwaysDisable); - } - - // set return value and cleanup - - if (subKey != NULL) - { - WdfRegistryClose(subKey); - } - - if (deviceKey != NULL) - { - WdfRegistryClose(deviceKey); - } - - if (alwaysEnable && alwaysDisable) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: %s selected\n", - "Both Enable and Disable set -- DISABLE")); - NT_ASSERT(NT_SUCCESS(status)); - status = STATUS_SUCCESS; - *Enabled = FALSE; - } - else if (alwaysDisable) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: %s selected\n", - "DISABLE")); - NT_ASSERT(NT_SUCCESS(status)); - status = STATUS_SUCCESS; - *Enabled = FALSE; - } - else if (alwaysEnable) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: %s selected\n", - "ENABLE")); - NT_ASSERT(NT_SUCCESS(status)); - status = STATUS_SUCCESS; - *Enabled = TRUE; - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeDeviceInstanceOverride: %s selected\n", - "DEFAULT")); - status = STATUS_UNSUCCESSFUL; - } - - return status; -} // end DeviceMediaChangeDeviceInstanceOverride() - - -NTSTATUS -DeviceMediaChangeRegistryCallBack( - _In_z_ PWSTR ValueName, - _In_ ULONG ValueType, - _In_reads_bytes_opt_(ValueLength) PVOID ValueData, - _In_ ULONG ValueLength, - _In_opt_ PVOID Context, - _In_opt_ PVOID EntryContext - ) -/*++ - -Routine Description: - - This callback for a registry SZ or MULTI_SZ is called once for each - SZ in the value. It will attempt to match the data with the - UNICODE_STRING passed in as Context, and modify EntryContext if a - match is found. Written for ClasspCheckRegistryForMediaChangeCompletion - -Arguments: - - ValueName - name of the key that was opened - ValueType - type of data stored in the value (REG_SZ for this routine) - ValueData - data in the registry, in this case a wide string - ValueLength - length of the data including the terminating null - Context - unicode string to compare against ValueData - EntryContext - should be initialized to 0, will be set to 1 if match found - -Return Value: - - STATUS_SUCCESS - EntryContext will be 1 if found - ---*/ -{ - PULONG valueFound; - PUNICODE_STRING deviceString; - PWSTR keyValue; - - PAGED_CODE(); - - UNREFERENCED_PARAMETER(ValueName); - - if ((Context == NULL) || (EntryContext == NULL)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "DeviceMediaChangeRegistryCallBack: NULL context should never be passed to registry call-back!\n")); - - return STATUS_SUCCESS; - } - - // if we have already set the value to true, exit - valueFound = EntryContext; - if ((*valueFound) != 0) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceMediaChangeRegistryCallBack: already set to true\n")); - return STATUS_SUCCESS; - } - - if (ValueLength == sizeof(WCHAR)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "DeviceMediaChangeRegistryCallBack: NULL string should never be passed to registry call-back!\n")); - return STATUS_SUCCESS; - } - - // if the data is not a terminated string, exit - if (ValueType != REG_SZ) - { - return STATUS_SUCCESS; - } - - deviceString = Context; - keyValue = ValueData; - ValueLength -= sizeof(WCHAR); // ignore the null character - - // do not compare more memory than is in deviceString - if (ValueLength > deviceString->Length) - { - ValueLength = deviceString->Length; - } - - if (keyValue == NULL) - { - return STATUS_SUCCESS; - } - - // if the strings match, disable autorun - if (RtlCompareMemory(deviceString->Buffer, keyValue, ValueLength) == ValueLength) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, "DeviceMediaChangeRegistryCallBack: Match found\n")); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, "DeviceMediaChangeRegistryCallBack: DeviceString at %p\n", - deviceString->Buffer)); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "DeviceMediaChangeRegistryCallBack: KeyValue at %p\n", - keyValue)); - (*valueFound) = TRUE; - } - - return STATUS_SUCCESS; -} // end DeviceMediaChangeRegistryCallBack() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceIsMediaChangeDisabledDueToHardwareLimitation( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - The key AutoRunAlwaysDisable contains a MULTI_SZ of hardware IDs for - which to never enable MediaChangeNotification. - - The user can override the global setting to enable or disable Autorun on a - specific cdrom device via the control panel. - - NOTE: It's intended that not use WdfRegistryQueryMultiString in this funciton, - as it's much more complicated.(needs WDFCOLLECTION, WDFSTRING other than - UNICODE_STRING) - -Arguments: - - FdoExtension - - RegistryPath - pointer to the unicode string inside - ...\CurrentControlSet\Services\Cdrom - -Return Value: - - TRUE - no autorun. - FALSE - Autorun may be enabled - ---*/ -{ - NTSTATUS status; - - PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = DeviceExtension->DeviceDescriptor; - WDFKEY wdfKey; - HANDLE serviceKey = NULL; - RTL_QUERY_REGISTRY_TABLE parameters[2] = {0}; - - UNICODE_STRING deviceUnicodeString = {0}; - ANSI_STRING deviceString = {0}; - ULONG mediaChangeNotificationDisabled = 0; - - PAGED_CODE(); - - // open the service key. - status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(), - KEY_ALL_ACCESS, - WDF_NO_OBJECT_ATTRIBUTES, - &wdfKey); - - if(!NT_SUCCESS(status)) - { - NT_ASSERT(FALSE); - - // always take the safe path. if we can't open the service key, disable autorun - return TRUE; - } - - if(NT_SUCCESS(status)) - { - // Determine if drive is in a list of those requiring - // autorun to be disabled. this is stored in a REG_MULTI_SZ - // named AutoRunAlwaysDisable. this is required as some autochangers - // must load the disc to reply to ChkVerify request, causing them - // to cycle discs continuously. - - PWSTR nullMultiSz; - PUCHAR vendorId = NULL; - PUCHAR productId = NULL; - PUCHAR revisionId = NULL; - size_t length; - size_t offset; - - deviceString.Buffer = NULL; - deviceUnicodeString.Buffer = NULL; - - serviceKey = WdfRegistryWdmGetHandle(wdfKey); - - // there may be nothing to check against - if ((deviceDescriptor->VendorIdOffset == 0) && - (deviceDescriptor->ProductIdOffset == 0)) - { - // no valid data in device extension. - status = STATUS_INTERNAL_ERROR; - } - - // build deviceString using VendorId, Model and Revision. - // this string will be used to checked if it's one of devices in registry disable list. - if (NT_SUCCESS(status)) - { - length = 0; - - if (deviceDescriptor->VendorIdOffset == 0) - { - vendorId = NULL; - } - else - { - vendorId = (PUCHAR) deviceDescriptor + deviceDescriptor->VendorIdOffset; - length = strlen((LPCSTR)vendorId); - } - - if ( deviceDescriptor->ProductIdOffset == 0 ) - { - productId = NULL; - } - else - { - productId = (PUCHAR) deviceDescriptor + deviceDescriptor->ProductIdOffset; - length += strlen((LPCSTR)productId); - } - - if ( deviceDescriptor->ProductRevisionOffset == 0 ) - { - revisionId = NULL; - } - else - { - revisionId = (PUCHAR) deviceDescriptor + deviceDescriptor->ProductRevisionOffset; - length += strlen((LPCSTR)revisionId); - } - - // allocate a buffer for the string - deviceString.Length = (USHORT)( length ); - deviceString.MaximumLength = deviceString.Length + 1; - deviceString.Buffer = (PCHAR)ExAllocatePool2(POOL_FLAG_NON_PAGED, - deviceString.MaximumLength, - CDROM_TAG_AUTORUN_DISABLE - ); - if (deviceString.Buffer == NULL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledDueToHardwareLimitation: Unable to alloc string buffer\n" )); - status = STATUS_INTERNAL_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // copy strings to the buffer - offset = 0; - - if (vendorId != NULL) - { - RtlCopyMemory(deviceString.Buffer + offset, - vendorId, - strlen((LPCSTR)vendorId)); - offset += strlen((LPCSTR)vendorId); - } - - if ( productId != NULL ) - { - RtlCopyMemory(deviceString.Buffer + offset, - productId, - strlen((LPCSTR)productId)); - offset += strlen((LPCSTR)productId); - } - if ( revisionId != NULL ) - { - RtlCopyMemory(deviceString.Buffer + offset, - revisionId, - strlen((LPCSTR)revisionId)); - offset += strlen((LPCSTR)revisionId); - } - - NT_ASSERT(offset == deviceString.Length); - - #pragma warning(suppress:6386) // Not an issue as deviceString.Buffer is of size deviceString.MaximumLength, which is equal to (deviceString.Length + 1) - deviceString.Buffer[deviceString.Length] = '\0'; // Null-terminated - - // convert to unicode as registry deals with unicode strings - status = RtlAnsiStringToUnicodeString( &deviceUnicodeString, - &deviceString, - TRUE - ); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledDueToHardwareLimitation: cannot convert " - "to unicode %lx\n", status)); - } - } - - if (NT_SUCCESS(status)) - { - // query the value, setting valueFound to true if found - nullMultiSz = L"\0"; - parameters[0].QueryRoutine = DeviceMediaChangeRegistryCallBack; - parameters[0].Flags = RTL_QUERY_REGISTRY_REQUIRED; - parameters[0].Name = L"AutoRunAlwaysDisable"; - parameters[0].EntryContext = &mediaChangeNotificationDisabled; - parameters[0].DefaultType = REG_MULTI_SZ; - parameters[0].DefaultData = nullMultiSz; - parameters[0].DefaultLength = 0; - - status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE, - serviceKey, - parameters, - &deviceUnicodeString, - NULL); - UNREFERENCED_PARAMETER(status); //defensive coding, avoid PREFAST warning. - } - } - - // Cleanup - { - - FREE_POOL( deviceString.Buffer ); - if (deviceUnicodeString.Buffer != NULL) - { - RtlFreeUnicodeString( &deviceUnicodeString ); - } - - // handle serviceKey will be closed by framework while it closes registry key. - WdfRegistryClose(wdfKey); - } - - if (mediaChangeNotificationDisabled > 0) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledDueToHardwareLimitation: Device is on MCN disable list\n")); - } - - return (mediaChangeNotificationDisabled > 0); - -} // end DeviceIsMediaChangeDisabledDueToHardwareLimitation() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceIsMediaChangeDisabledForClass( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - The user must specify that AutoPlay is to run on the platform - by setting the registry value HKEY_LOCAL_MACHINE\System\CurrentControlSet\ - Services\\Autorun:REG_DWORD:1. - - The user can override the global setting to enable or disable Autorun on a - specific cdrom device via the control panel. - -Arguments: - - DeviceExtension - device extension - -Return Value: - - TRUE - Autorun is disabled for this class - FALSE - Autorun is enabled for this class - ---*/ -{ - NTSTATUS status; - WDFKEY serviceKey = NULL; - WDFKEY parametersKey = NULL; - - UNICODE_STRING parameterKeyName; - UNICODE_STRING valueName; - - // Default to ENABLING MediaChangeNotification (!) - ULONG mcnRegistryValue = 1; - - PAGED_CODE(); - - // open the service key. - status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(), - KEY_ALL_ACCESS, - WDF_NO_OBJECT_ATTRIBUTES, - &serviceKey); - if(!NT_SUCCESS(status)) - { - // return the default value, which is the inverse of the registry setting default - // since this routine asks if it's disabled - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledForClass: Defaulting to %s\n", - (mcnRegistryValue ? "Enabled" : "Disabled"))); - return (BOOLEAN)(mcnRegistryValue == 0); - } - else - { - // Open the parameters key (if any) beneath the services key. - RtlInitUnicodeString(¶meterKeyName, L"Parameters"); - - status = WdfRegistryOpenKey(serviceKey, - ¶meterKeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - ¶metersKey); - } - - if (!NT_SUCCESS(status)) - { - parametersKey = NULL; - } - - RtlInitUnicodeString(&valueName, L"Autorun"); - // ignore failures - status = WdfRegistryQueryULong(serviceKey, - &valueName, - &mcnRegistryValue); - - if (NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledForClass: /Autorun flag = %d\n", - mcnRegistryValue)); - } - - if (parametersKey != NULL) - { - status = WdfRegistryQueryULong(parametersKey, - &valueName, - &mcnRegistryValue); - - if (NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledForClass: /Parameters/Autorun flag = %d\n", - mcnRegistryValue)); - } - - WdfRegistryClose(parametersKey); - } - - WdfRegistryClose(serviceKey); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceIsMediaChangeDisabledForClass: Autoplay for device %p is %s\n", - DeviceExtension->DeviceObject, - (mcnRegistryValue ? "on" : "off") - )); - - // return if it is _disabled_, which is the - // inverse of the registry setting - - return (BOOLEAN)(!mcnRegistryValue); -} // end DeviceIsMediaChangeDisabledForClass() - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceEnableMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Inout_ PFILE_OBJECT_CONTEXT FileObjectContext, - _In_ BOOLEAN IgnorePreviousMediaChanges - ) -/*++ - -Routine Description: - - When the disable count decrease to 0, enable the MCN - -Arguments: - - DeviceExtension - the device context - - FileObjectContext - the file object context - - IgnorePreviousMediaChanges - ignore all previous media changes - -Return Value: - None. - ---*/ -{ - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - LONG oldCount; - - PAGED_CODE(); - - if (FileObjectContext) - { - InterlockedDecrement((PLONG)&(FileObjectContext->McnDisableCount)); - } - - if (info == NULL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceEnableMediaChangeDetection: not initialized\n")); - return; - } - - (VOID) KeWaitForMutexObject(&info->MediaChangeMutex, - UserRequest, - KernelMode, - FALSE, - NULL); - - oldCount = --info->MediaChangeDetectionDisableCount; - - NT_ASSERT(oldCount >= 0); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "DeviceEnableMediaChangeDetection: Disable count reduced to %d - \n", - info->MediaChangeDetectionDisableCount)); - - if (oldCount == 0) - { - if (IgnorePreviousMediaChanges) - { - info->LastReportedMediaDetectionState = info->LastKnownMediaDetectionState; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, "MCN is enabled\n")); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, "MCD still disabled\n")); - } - - // Let something else run. - KeReleaseMutex(&info->MediaChangeMutex, FALSE); - - return; -} // end DeviceEnableMediaChangeDetection() - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceDisableMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Inout_ PFILE_OBJECT_CONTEXT FileObjectContext - ) -/*++ - -Routine Description: - - Increase the disable count. - -Arguments: - - DeviceExtension - the device context - - FileObjectContext - the file object context - -Return Value: - None. - ---*/ -{ - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - - PAGED_CODE(); - - if (FileObjectContext) - { - InterlockedIncrement((PLONG)&(FileObjectContext->McnDisableCount)); - } - - if (info == NULL) - { - return; - } - - (VOID) KeWaitForMutexObject(&info->MediaChangeMutex, - UserRequest, - KernelMode, - FALSE, - NULL); - - info->MediaChangeDetectionDisableCount++; - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "DisableMediaChangeDetection: disable count is %d\n", - info->MediaChangeDetectionDisableCount)); - - KeReleaseMutex(&info->MediaChangeMutex, FALSE); - - return; -} // end DeviceDisableMediaChangeDetection() - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceReleaseMcnResources( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine will cleanup any resources allocated for MCN. It is called - by classpnp during remove device, and therefore is not typically required - by external drivers. - -Arguments: - - DeviceExtension - the device context - -Return Value: - None. - ---*/ -{ - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - - PAGED_CODE() - - if(info == NULL) - { - return; - } - - if (info->Gesn.Mdl) - { - PIRP irp = WdfRequestWdmGetIrp(info->MediaChangeRequest); - IoFreeMdl(info->Gesn.Mdl); - irp->MdlAddress = NULL; - } - IoFreeIrp(info->MediaChangeSyncIrp); - FREE_POOL(info->Gesn.Buffer); - FREE_POOL(info->SenseBuffer); - - if (info->DisplayStateCallbackHandle) - { - PoUnregisterPowerSettingCallback(info->DisplayStateCallbackHandle); - info->DisplayStateCallbackHandle = NULL; - } - - FREE_POOL(info); - - DeviceExtension->MediaChangeDetectionInfo = NULL; - - return; -} // end DeviceReleaseMcnResources() - - -IO_COMPLETION_ROUTINE RequestMcnSyncIrpCompletion; - -NTSTATUS -RequestMcnSyncIrpCompletion( - _In_ PDEVICE_OBJECT DeviceObject, - _In_ PIRP Irp, - _In_reads_opt_(_Inexpressible_("varies")) PVOID Context - ) -/*++ - -Routine Description: - - The MCN work finishes, reset the fields to allow another MCN request - be scheduled. - -Arguments: - - DeviceObject - device that the completion routine fires on. - - Irp - The irp to be completed. - - Context - IRP context - -Return Value: - NTSTATUS - ---*/ -{ - PCDROM_DEVICE_EXTENSION DeviceExtension = NULL; - PMEDIA_CHANGE_DETECTION_INFO info = NULL; - - if (Context == NULL) - { - // this will never happen, but code must be there to prevent OACR warnings. - return STATUS_MORE_PROCESSING_REQUIRED; - } - - DeviceExtension = (PCDROM_DEVICE_EXTENSION) Context; - info = DeviceExtension->MediaChangeDetectionInfo; - -#ifndef DEBUG - UNREFERENCED_PARAMETER(Irp); -#endif - UNREFERENCED_PARAMETER(DeviceObject); - - NT_ASSERT(Irp == info->MediaChangeSyncIrp); - - IoReuseIrp(info->MediaChangeSyncIrp, STATUS_NOT_SUPPORTED); - - // reset the value to let timer routine be able to send the next request. - InterlockedCompareExchange((PLONG)&(info->MediaChangeRequestInUse), 0, 1); - - return STATUS_MORE_PROCESSING_REQUIRED; -} - - -VOID -RequestSetupMcnSyncIrp( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - setup the MCN synchronization irp. - -Arguments: - - DeviceExtension - the device context - -Return Value: - None - ---*/ -{ - PIRP irp = NULL; - PIO_STACK_LOCATION irpStack = NULL; - PIO_STACK_LOCATION nextIrpStack = NULL; - - irp = DeviceExtension->MediaChangeDetectionInfo->MediaChangeSyncIrp; - NT_ASSERT(irp != NULL); - - // - // For the driver that creates an IRP, there is no 'current' stack location. - // Step down one IRP stack location so that the extra top one - // becomes our 'current' one. - // - IoSetNextIrpStackLocation(irp); - - /* - * Cache our device object in the extra top IRP stack location - * so we have it in our completion routine. - */ - irpStack = IoGetCurrentIrpStackLocation(irp); - irpStack->DeviceObject = DeviceExtension->DeviceObject; - - // - // If the irp is sent down when the volume needs to be - // verified, CdRomUpdateGeometryCompletion won't complete - // it since it's not associated with a thread. Marking - // it to override the verify causes it always be sent - // to the port driver - // - nextIrpStack = IoGetNextIrpStackLocation(irp); - - SET_FLAG(nextIrpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME); - - nextIrpStack->MajorFunction = IRP_MJ_DEVICE_CONTROL; - // pick up this IOCTL code as it's not normaly seen for CD/DVD drive and does not require input. - // set other fields to make this IOCTL recognizable by CDROM.SYS - nextIrpStack->Parameters.Others.Argument1 = RequestSetupMcnSyncIrp; - nextIrpStack->Parameters.Others.Argument2 = RequestSetupMcnSyncIrp; - nextIrpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_MCN_SYNC_FAKE_IOCTL; //Argument3. - nextIrpStack->Parameters.Others.Argument4 = RequestSetupMcnSyncIrp; - - IoSetCompletionRoutine(irp, - RequestMcnSyncIrpCompletion, - DeviceExtension, - TRUE, - TRUE, - TRUE); - - return; -} - - -VOID -DeviceMainTimerTickHandler( - _In_ WDFTIMER Timer - ) -/*++ - -Routine Description: - - This routine setup a sync irp and send it to the serial queue. - Serial queue will process MCN when receive this sync irp. - -Arguments: - - Timer - the timer object that fires. - -Return Value: - None - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - size_t dataLength = 0; - - deviceExtension = WdfObjectGetTypedContext(WdfTimerGetParentObject(Timer), CDROM_DEVICE_EXTENSION); - - (void) RequestHandleEventNotification(deviceExtension, NULL, NULL, &dataLength); - - return; -} // end DeviceMainTimerTickHandler() - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceEnableMainTimer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine will allocate timer related resources on the first time call. - Start the timer. - -Arguments: - - DeviceExtension - the device context - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - if ((DeviceExtension->MediaChangeDetectionInfo == NULL) || - (DeviceExtension->MediaChangeDetectionInfo->AsynchronousNotificationSupported != FALSE)) - { - // Asynchronous Notification is enabled, timer not needed. - return status; - } - - if (DeviceExtension->MainTimer == NULL) - { - //create main timer object. - WDF_TIMER_CONFIG timerConfig; - WDF_OBJECT_ATTRIBUTES timerAttributes; - - WDF_TIMER_CONFIG_INIT(&timerConfig, DeviceMainTimerTickHandler); - - // Polling frequently on virtual optical devices created by Hyper-V will - // cause a significant perf / power hit. These devices need to be polled - // less frequently for device state changes. - if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_MSFT_VIRTUAL_ODD)) - { - timerConfig.Period = 2000; // 2 seconds, in milliseconds. - } - else - { - timerConfig.Period = 1000; // 1 second, in milliseconds. - } - - timerConfig.TolerableDelay = 500; // 0.5 seconds, in milliseconds - - //Set the autoSerialization to FALSE, as the parent device's - //execute level is WdfExecutionLevelPassive. - timerConfig.AutomaticSerialization = FALSE; - - WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes); - timerAttributes.ParentObject = DeviceExtension->Device; - timerAttributes.ExecutionLevel = WdfExecutionLevelInheritFromParent; - - status = WdfTimerCreate(&timerConfig, - &timerAttributes, - &DeviceExtension->MainTimer); - } - - if (NT_SUCCESS(status)) - { - WdfTimerStart(DeviceExtension->MainTimer,WDF_REL_TIMEOUT_IN_MS(100)); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceEnableMainTimer: Once a second timer enabled for WDFDEVICE %p\n", - DeviceExtension->Device)); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceEnableMainTimer: WDFDEVICE %p, Status %lx initializing timer\n", - DeviceExtension->Device, status)); - } - - return status; -} // end DeviceEnableMainTimer() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceDisableMainTimer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - stop the timer. - -Arguments: - - DeviceExtension - device context - -Return Value: - None - ---*/ -{ - PAGED_CODE(); - - if ((DeviceExtension->MediaChangeDetectionInfo == NULL) || - (DeviceExtension->MediaChangeDetectionInfo->AsynchronousNotificationSupported != FALSE)) - { - // Asynchronous Notification is enabled, timer not needed. - return; - } - - if (DeviceExtension->MainTimer != NULL) - { - // - // we are only going to stop the actual timer in remove device routine. - // it is the responsibility of the code within the timer routine to - // check if the device is removed and not processing io for the final - // call. - // this keeps the code clean and prevents lots of bugs. - // - WdfTimerStop(DeviceExtension->MainTimer,TRUE); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "DeviceDisableMainTimer: Once a second timer disabled for device %p\n", - DeviceExtension->Device)); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "DeviceDisableMainTimer: Timer never enabled\n")); - } - - return; -} // end DeviceDisableMainTimer() - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleMcnControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - This routine handles the process of IOCTL_STORAGE_MCN_CONTROL - -Arguments: - - DeviceExtension - device context - - Request - request object - - RequestParameters - request parameters - - DataLength - data transferred - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFFILEOBJECT fileObject = NULL; - PFILE_OBJECT_CONTEXT fileObjectContext = NULL; - PPREVENT_MEDIA_REMOVAL mediaRemoval = NULL; - - PAGED_CODE(); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(PREVENT_MEDIA_REMOVAL), - &mediaRemoval, - NULL); - - if (NT_SUCCESS(status)) - { - fileObject = WdfRequestGetFileObject(Request); - - // Check to make sure we have a file object extension to keep track of this - // request. If not we'll fail it before synchronizing. - if (fileObject != NULL) - { - fileObjectContext = FileObjectGetContext(fileObject); - } - - if ((fileObjectContext == NULL) && - (WdfRequestGetRequestorMode(Request) == KernelMode)) - { - fileObjectContext = &DeviceExtension->KernelModeMcnContext; - } - - if (fileObjectContext == NULL) - { - // This handle isn't setup correctly. We can't let the - // operation go. - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - if (mediaRemoval->PreventMediaRemoval) - { - // This is a lock command. Reissue the command in case bus or - // device was reset and the lock was cleared. - DeviceDisableMediaChangeDetection(DeviceExtension, fileObjectContext); - } - else - { - if (fileObjectContext->McnDisableCount == 0) - { - status = STATUS_INVALID_DEVICE_STATE; - } - else - { - DeviceEnableMediaChangeDetection(DeviceExtension, fileObjectContext, TRUE); - } - } - } - - return status; -} // end RequestHandleMcnControl() - -#pragma warning(pop) // un-sets any local warning changes - diff --git a/storage/class/cdrom/src/cdrom.c b/storage/class/cdrom/src/cdrom.c deleted file mode 100644 index fccf4a0e4..000000000 --- a/storage/class/cdrom/src/cdrom.c +++ /dev/null @@ -1,4225 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - cdrom.c - -Abstract: - - The CDROM class driver tranlates IRPs to SRBs with embedded CDBs - and sends them to its devices through the port driver. - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -// this definition is used to link _StorDebugPrint() function. -#define DEBUG_MAIN_SOURCE 1 - - -#include "ntddk.h" -#include "ntstrsafe.h" - -#include "ntddstor.h" -#include "ntddtape.h" -#include "wdfcore.h" -#include "devpkey.h" - -#include "cdrom.h" -#include "ioctl.h" -#include "mmc.h" -#include "scratch.h" - - -#ifdef DEBUG_USE_WPP -#include "cdrom.tmh" -#endif - -BOOLEAN -BootEnvironmentIsWinPE( - VOID - ); - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(INIT, DriverEntry) -#pragma alloc_text(INIT, BootEnvironmentIsWinPE) - -#pragma alloc_text(PAGE, DriverEvtCleanup) -#pragma alloc_text(PAGE, DriverEvtDeviceAdd) -#pragma alloc_text(PAGE, DeviceEvtCleanup) -#pragma alloc_text(PAGE, DeviceEvtSelfManagedIoCleanup) -#pragma alloc_text(PAGE, DeviceEvtD0Exit) -#pragma alloc_text(PAGE, CreateQueueEvtIoDefault) -#pragma alloc_text(PAGE, DeviceEvtFileClose) -#pragma alloc_text(PAGE, DeviceCleanupProtectedLocks) -#pragma alloc_text(PAGE, DeviceCleanupDisableMcn) -#pragma alloc_text(PAGE, RequestProcessSerializedIoctl) -#pragma alloc_text(PAGE, ReadWriteWorkItemRoutine) -#pragma alloc_text(PAGE, IoctlWorkItemRoutine) -#pragma alloc_text(PAGE, DeviceEvtSurpriseRemoval) - -#endif - -NTSTATUS -DriverEntry( - _In_ PDRIVER_OBJECT DriverObject, - _In_ PUNICODE_STRING RegistryPath - ) -/*++ - -Routine Description: - - Installable driver initialization entry point. - This entry point is called directly by the I/O system. - -Arguments: - - DriverObject - pointer to the driver object - - RegistryPath - pointer to a unicode string representing the path, - to driver-specific key in the registry. - -Return Value: - - STATUS_SUCCESS if successful, - STATUS_UNSUCCESSFUL otherwise. - ---*/ -{ - NTSTATUS status; - WDF_DRIVER_CONFIG config; - WDF_OBJECT_ATTRIBUTES attributes; - WDFDRIVER driverObject = NULL; - - PAGED_CODE(); - - // Initialize WPP Tracing - WPP_INIT_TRACING(DriverObject, RegistryPath); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "CDROM.SYS DriverObject %p loading\n", - DriverObject)); - - // Register DeviceAdd and DriverEvtCleanup callback. - // WPP_CLEANUP will be called in DriverEvtCleanup - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, CDROM_DRIVER_EXTENSION); - attributes.EvtCleanupCallback = DriverEvtCleanup; - - WDF_DRIVER_CONFIG_INIT(&config, DriverEvtDeviceAdd); - - status = WdfDriverCreate(DriverObject, - RegistryPath, - &attributes, - &config, - &driverObject); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_INIT, - "WdfDriverCreate failed. %x\n", - status)); - - // Cleanup tracing here because DriverUnload will not be called - // as we have failed to create WDFDRIVER object itself. - WPP_CLEANUP(DriverObject); - - } - else - { - PCDROM_DRIVER_EXTENSION driverExtension = DriverGetExtension(driverObject); - - // Copy the registry path into the driver extension so we can use it later - driverExtension->Version = 0x01; - driverExtension->DriverObject = DriverObject; - - if (BootEnvironmentIsWinPE()) { - - SET_FLAG(driverExtension->Flags, CDROM_FLAG_WINPE_MODE); - } - - } - - return status; -} - - -BOOLEAN -BootEnvironmentIsWinPE( - VOID - ) -/*++ - -Routine Description: - - This routine determines if the boot enviroment is WinPE - -Arguments: - - None - -Return Value: - - BOOLEAN - TRUE if the environment is WinPE; FALSE otherwise - ---*/ -{ - NTSTATUS status; - WDFKEY registryKey = NULL; - - DECLARE_CONST_UNICODE_STRING(registryKeyName, WINPE_REG_KEY_NAME); - - PAGED_CODE(); - - status = WdfRegistryOpenKey(NULL, - ®istryKeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - ®istryKey); - - if (!NT_SUCCESS(status)) - { - return FALSE; - } - - WdfRegistryClose(registryKey); - return TRUE; -} // end BootEnvironmentIsWinPE() - - -VOID -DriverEvtCleanup( - _In_ WDFOBJECT Driver - ) -/*++ -Routine Description: - - Free all the resources allocated in DriverEntry. - -Arguments: - - Driver - handle to a WDF Driver object. - -Return Value: - - VOID. - ---*/ -{ - WDFDRIVER driver = (WDFDRIVER)Driver; - - PAGED_CODE (); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "CDROM.SYS DriverObject %p cleanup. Will be unloaded soon\n", - driver)); - - // Stop WPP Tracing - WPP_CLEANUP( WdfDriverWdmGetDriverObject(driver) ); - - - return; -} - - -NTSTATUS -DriverEvtDeviceAdd( - _In_ WDFDRIVER Driver, - _Inout_ PWDFDEVICE_INIT DeviceInit - ) -/*++ - -Routine Description: - - EvtDeviceAdd is called by the framework in response to AddDevice - call from the PnP manager. - - -Arguments: - - Driver - Handle to a framework driver object created in DriverEntry - - DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DRIVER_EXTENSION driverExtension = NULL; - WDFDEVICE device = NULL; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - BOOLEAN deviceClaimed = FALSE; - - WDF_OBJECT_ATTRIBUTES attributes; - WDF_FILEOBJECT_CONFIG fileObjectConfig; - WDF_IO_TARGET_OPEN_PARAMS ioTargetOpenParams; - WDF_IO_QUEUE_CONFIG queueConfig; - WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; - WDF_REMOVE_LOCK_OPTIONS removeLockOptions; - PWCHAR wideDeviceName = NULL; - UNICODE_STRING unicodeDeviceName; - PDEVICE_OBJECT lowerPdo = NULL; - ULONG deviceNumber = 0; - ULONG devicePropertySessionId = INVALID_SESSION; - ULONG devicePropertySize = 0; - DEVPROPTYPE devicePropertyType = DEVPROP_TYPE_EMPTY; - - PAGED_CODE(); - - driverExtension = DriverGetExtension(Driver); - - // 0. Initialize the objects that we're going to use - RtlInitUnicodeString(&unicodeDeviceName, NULL); - - // 1. Register PnP&Power callbacks for any we are interested in. - // If a callback isn't set, Framework will take the default action by itself. - { - // Zero out the PnpPowerCallbacks structure. - WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); - - // Use this callback to init resources that are used by the device and only needs to be called once. - pnpPowerCallbacks.EvtDeviceSelfManagedIoInit = DeviceEvtSelfManagedIoInit; - - // Use this callback to prepare device for coming back from a lower power mode to D0. - pnpPowerCallbacks.EvtDeviceD0Entry = DeviceEvtD0Entry; - - // Use this callback to prepare device for entering into a lower power mode. - pnpPowerCallbacks.EvtDeviceD0Exit = DeviceEvtD0Exit; - - // Use this callback to free any resources used by device and will be called when the device is - // powered down. - pnpPowerCallbacks.EvtDeviceSelfManagedIoCleanup = DeviceEvtSelfManagedIoCleanup; - - pnpPowerCallbacks.EvtDeviceSurpriseRemoval = DeviceEvtSurpriseRemoval; - - // Register the PnP and power callbacks. - WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks); - } - - // 2. Register the EvtIoInCallerContext to deal with IOCTLs that need to stay in original context. - WdfDeviceInitSetIoInCallerContextCallback(DeviceInit, - DeviceEvtIoInCallerContext); - - // 3. Register PreprocessCallback for IRP_MJ_POWER, IRP_MJ_FLUSH_BUFFERS and IRP_MJ_SHUTDOWN - { - UCHAR minorFunctions[1]; - - minorFunctions[0] = IRP_MN_SET_POWER; - - status = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit, - RequestProcessSetPower, - IRP_MJ_POWER, - minorFunctions, - RTL_NUMBER_OF(minorFunctions)); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Assign IrpPreprocessCallback for IRP_MJ_POWER failed, " - "status: 0x%X\n", status)); - - goto Exit; - } - - status = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit, - RequestProcessShutdownFlush, - IRP_MJ_FLUSH_BUFFERS, - NULL, - 0); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Assign IrpPreprocessCallback for IRP_MJ_FLUSH_BUFFERS failed, " - "status: 0x%X\n", status)); - - goto Exit; - } - - status = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit, - RequestProcessShutdownFlush, - IRP_MJ_SHUTDOWN, - NULL, - 0); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Assign IrpPreprocessCallback for IRP_MJ_SHUTDOWN failed, " - "status: 0x%X\n", status)); - - goto Exit; - } - } - - // 4. Set attributes to create Request Context area. - { - //Reuse this structure. - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - attributes.EvtCleanupCallback = RequestEvtCleanup; - - WdfDeviceInitSetRequestAttributes(DeviceInit, - &attributes); - } - - // 5. Register FileObject related callbacks - { - // Add FILE_OBJECT_EXTENSION as the context to the file object. - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, FILE_OBJECT_CONTEXT); - - // Set Entry points for Create and Close.. - - // The framework doesn't sync the file create requests with pnp/power - // state. Re-direct all the file create requests to a dedicated - // queue, which will be purged manually during removal. - WDF_FILEOBJECT_CONFIG_INIT(&fileObjectConfig, - NULL, //CreateQueueEvtIoDefault, - DeviceEvtFileClose, - WDF_NO_EVENT_CALLBACK); // No callback for Cleanup - - fileObjectConfig.FileObjectClass = WdfFileObjectWdfCannotUseFsContexts; - - // Since we are registering file events and fowarding create request - // ourself, we must also set AutoForwardCleanupClose so that cleanup - // and close can also get forwarded. - fileObjectConfig.AutoForwardCleanupClose = WdfTrue; - attributes.SynchronizationScope = WdfSynchronizationScopeNone; - attributes.ExecutionLevel = WdfExecutionLevelPassive; - - // Indicate that file object is optional. - fileObjectConfig.FileObjectClass |= WdfFileObjectCanBeOptional; - - WdfDeviceInitSetFileObjectConfig(DeviceInit, - &fileObjectConfig, - &attributes); - } - - // 6. Initialize device-wide attributes - { - // Declare ourselves as NOT owning power policy. - // The power policy owner in storage stack is port driver. - WdfDeviceInitSetPowerPolicyOwnership(DeviceInit, FALSE); - - // Set other DeviceInit attributes. - WdfDeviceInitSetExclusive(DeviceInit, FALSE); - WdfDeviceInitSetDeviceType(DeviceInit, FILE_DEVICE_CD_ROM); - WdfDeviceInitSetCharacteristics(DeviceInit, FILE_REMOVABLE_MEDIA, FALSE); - WdfDeviceInitSetIoType(DeviceInit, WdfDeviceIoDirect); - WdfDeviceInitSetPowerPageable(DeviceInit); - - // We require the framework to acquire a remove lock before delivering all IRP types - WDF_REMOVE_LOCK_OPTIONS_INIT(&removeLockOptions, - WDF_REMOVE_LOCK_OPTION_ACQUIRE_FOR_IO); - - WdfDeviceInitSetRemoveLockOptions(DeviceInit, &removeLockOptions); - - // save the PDO for later reference - lowerPdo = WdfFdoInitWdmGetPhysicalDevice(DeviceInit); - - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_DEVICE_EXTENSION); - - // We have a parallel queue, so WdfSynchronizationScopeNone is our only choice. - attributes.SynchronizationScope = WdfSynchronizationScopeNone; - attributes.ExecutionLevel = WdfExecutionLevelDispatch; - - // Provide a cleanup callback which will release memory allocated with ExAllocatePool* - attributes.EvtCleanupCallback = DeviceEvtCleanup; - } - - // 7. Now, the device can be created. - { - wideDeviceName = ExAllocatePool2(POOL_FLAG_NON_PAGED, - 64 * sizeof(WCHAR), - CDROM_TAG_STRINGS); - - if (wideDeviceName == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - goto Exit; - } - - // Find the lowest device number currently available. - do { - status = RtlStringCchPrintfW((NTSTRSAFE_PWSTR)wideDeviceName, - 64, - L"\\Device\\CdRom%d", - deviceNumber); - - if (!NT_SUCCESS(status)) { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Format device name failed with error: 0x%X\n", status)); - - goto Exit; - } - - RtlInitUnicodeString(&unicodeDeviceName, wideDeviceName); - - status = WdfDeviceInitAssignName(DeviceInit, &unicodeDeviceName); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: WdfDeviceInitAssignName() failed with error: 0x%X\n", status)); - - goto Exit; - } - - status = WdfDeviceCreate(&DeviceInit, &attributes, &device); - - deviceNumber++; - - } while (status == STATUS_OBJECT_NAME_COLLISION); - - // When this loop exits the count is inflated by one - fix that. - deviceNumber--; - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Can not create a new device, status: 0x%X\n", - status)); - - goto Exit; - } - } - - // 8. Fill up basic Device Extension settings and create a remote I/O target for the next-lower driver. - // The reason why we do not use the local I/O target is because we want to be able to close the - // I/O target on surprise removal. - { - deviceExtension = DeviceGetExtension(device); - - deviceExtension->Version = 0x01; - deviceExtension->Size = sizeof(CDROM_DEVICE_EXTENSION); - - deviceExtension->DeviceObject = WdfDeviceWdmGetDeviceObject(device); - deviceExtension->Device = device; - deviceExtension->DriverExtension = driverExtension; - - deviceExtension->LowerPdo = lowerPdo; - - deviceExtension->DeviceType = FILE_DEVICE_CD_ROM; //Always a FILE_DEVICE_CD_ROM for all device it manages. - deviceExtension->DeviceName = unicodeDeviceName; - - deviceExtension->DeviceNumber = deviceNumber; - } - { - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = deviceExtension->Device; - - status = WdfIoTargetCreate(deviceExtension->Device, - &attributes, - &deviceExtension->IoTarget); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Can not create a remote I/O target object, status: 0x%X\n", - status)); - goto Exit; - } - - WDF_IO_TARGET_OPEN_PARAMS_INIT_EXISTING_DEVICE(&ioTargetOpenParams, - WdfDeviceWdmGetAttachedDevice(deviceExtension->Device)); - - status = WdfIoTargetOpen(deviceExtension->IoTarget, - &ioTargetOpenParams); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Can not open a remote I/O target for the next-lower device, status: 0x%X\n", - status)); - - WdfObjectDelete(deviceExtension->IoTarget); - deviceExtension->IoTarget = NULL; - - goto Exit; - } - } - - // 9. Claim the device, so that port driver will only accept the commands from CDROM.SYS for this device. - // NOTE: The I/O should be issued after the device is started. But we would like to claim - // the device as soon as possible, so this legacy behavior is kept. - status = DeviceClaimRelease(deviceExtension, FALSE); - - if (!NT_SUCCESS(status)) - { - // Someone already had this device - we're in trouble - goto Exit; - } - else - { - deviceClaimed = TRUE; - } - - // - // CDROM Queueing Structure - // - // a. EvtIoInCallerContext (prior to queueing): - // This event will be used ONLY to forward down IOCTLs that come in at PASSIVE LEVEL - // and need to be forwarded down the stack in the original context. - // - // b. Main input queue: serial queue for main dispatching - // This queue will be used to do all dispatching of requests to serialize - // access to the device. Any request that was previously completed in - // the Dispatch routines will be completed here. Anything requiring device - // I/O will be sent through the serial I/O queue. - // - // 10. Set up IO queues after device being created. - // - { - WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, - WdfIoQueueDispatchSequential); - - queueConfig.PowerManaged = WdfFalse; - -#pragma prefast(push) -#pragma prefast(disable: 28155, "a joint handler for read/write cannot be EVT_WDF_IO_QUEUE_IO_READ and EVT_WDF_IO_QUEUE_IO_WRITE simultaneously") -#pragma prefast(disable: 28023, "a joint handler for read/write cannot be EVT_WDF_IO_QUEUE_IO_READ and EVT_WDF_IO_QUEUE_IO_WRITE simultaneously") - queueConfig.EvtIoRead = SequentialQueueEvtIoReadWrite; - queueConfig.EvtIoWrite = SequentialQueueEvtIoReadWrite; -#pragma prefast(pop) - - queueConfig.EvtIoDeviceControl = SequentialQueueEvtIoDeviceControl; - queueConfig.EvtIoCanceledOnQueue = SequentialQueueEvtCanceledOnQueue; - - status = WdfIoQueueCreate(device, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &(deviceExtension->SerialIOQueue)); - if (!NT_SUCCESS(status)) - { - goto Exit; - } - - // this queue is dedicated for file create requests. - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchParallel); - - queueConfig.PowerManaged = WdfFalse; - queueConfig.EvtIoDefault = CreateQueueEvtIoDefault; - - //Reuse this structure. - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - - attributes.SynchronizationScope = WdfSynchronizationScopeNone; - attributes.ExecutionLevel = WdfExecutionLevelPassive; - - status = WdfIoQueueCreate(device, - &queueConfig, - &attributes, - &(deviceExtension->CreateQueue)); - - if (!NT_SUCCESS(status)) - { - goto Exit; - } - - // Configure the device to use driver created queue for dispatching create. - status = WdfDeviceConfigureRequestDispatching(device, - deviceExtension->CreateQueue, - WdfRequestTypeCreate); - - if (!NT_SUCCESS(status)) - { - goto Exit; - } - } - - // 11. Set the alignment requirements for the device based on the host adapter requirements. - // - // NOTE: this should have been set when device is attached on device stack, - // by keeping this legacy code, we could avoid issue that this value was not correctly set at that time. - if (deviceExtension->LowerPdo->AlignmentRequirement > deviceExtension->DeviceObject->AlignmentRequirement) - { - WdfDeviceSetAlignmentRequirement(deviceExtension->Device, - deviceExtension->LowerPdo->AlignmentRequirement); - } - - // 12. Initialization of miscellaneous internal properties - - // CDROMs are not partitionable so starting offset is 0. - deviceExtension->StartingOffset.LowPart = 0; - deviceExtension->StartingOffset.HighPart = 0; - - // Set the default geometry for the cdrom to match what NT 4 used. - // these values will be used to compute the cylinder count rather - // than using it's NT 5.0 defaults. - deviceExtension->DiskGeometry.MediaType = RemovableMedia; - deviceExtension->DiskGeometry.TracksPerCylinder = 0x40; - deviceExtension->DiskGeometry.SectorsPerTrack = 0x20; - - deviceExtension->DeviceAdditionalData.ReadWriteRetryDelay100nsUnits = WRITE_RETRY_DELAY_DVD_1x; - - // Clear the SrbFlags and disable synchronous transfers - deviceExtension->SrbFlags = SRB_FLAGS_DISABLE_SYNCH_TRANSFER; - - // Set timeout value in seconds. - deviceExtension->TimeOutValue = DeviceGetTimeOutValueFromRegistry(); - if ((deviceExtension->TimeOutValue > 30 * 60) || // longer than 30 minutes - (deviceExtension->TimeOutValue == 0)) - { - deviceExtension->TimeOutValue = SCSI_CDROM_TIMEOUT; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DriverEvtDeviceAdd: device timeout is set to %x seconds", - deviceExtension->TimeOutValue - )); - -#if (NTDDI_VERSION >= NTDDI_WIN8) - deviceExtension->IsVolumeOnlinePending = TRUE; - - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchManual); - - queueConfig.PowerManaged = WdfFalse; - - status = WdfIoQueueCreate(device, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &deviceExtension->ManualVolumeReadyQueue); - - if (!NT_SUCCESS(status)) - { - goto Exit; - } -#endif - - // 13. Initialize the stuff related to media locking - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = deviceExtension->Device; - status = WdfWaitLockCreate(&attributes, - &deviceExtension->EjectSynchronizationLock); - - deviceExtension->LockCount = 0; - - // 14. Initialize context structures needed for asynchronous release queue and power requests - - if (NT_SUCCESS(status)) - { - status = DeviceInitReleaseQueueContext(deviceExtension); - } - - if (NT_SUCCESS(status)) - { - status = DeviceInitPowerContext(deviceExtension); - } - - // 15. Create external access points other than device name. - if (NT_SUCCESS(status)) - { - status = DeviceCreateWellKnownName(deviceExtension); - } - - // 16. Query session id from the PDO. - if (NT_SUCCESS(status)) - { - status = IoGetDevicePropertyData(deviceExtension->LowerPdo, - &DEVPKEY_Device_SessionId, - 0, - 0, - sizeof(devicePropertySessionId), - &devicePropertySessionId, - &devicePropertySize, - &devicePropertyType); - - if (!NT_SUCCESS(status)) - { - // The device is global. - devicePropertySessionId = INVALID_SESSION; - status = STATUS_SUCCESS; - } - } - - // 17. Register interfaces for this device. - if (NT_SUCCESS(status)) - { - status = DeviceRegisterInterface(deviceExtension, CdRomDeviceInterface); - } - - if (NT_SUCCESS(status)) - { - // If this is a per-session DO, don't register for mount interface so that - // mountmgr will not automatically assign a drive letter. - if (devicePropertySessionId == INVALID_SESSION) - { - status = DeviceRegisterInterface(deviceExtension, MountedDeviceInterface); - } - } - - // 18. Initialize the shutdown/flush lock - if (NT_SUCCESS(status)) - { - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = deviceExtension->Device; - - status = WdfWaitLockCreate(&attributes, &deviceExtension->ShutdownFlushWaitLock); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DriverEvtDeviceAdd: Cannot create shutdown/flush waitlock, status: 0x%X\n", - status)); - } - } - - // 19. Initialize the work item that is used to initiate asynchronous reads/writes - if (NT_SUCCESS(status)) - { - WDF_WORKITEM_CONFIG workItemConfig; - WDF_OBJECT_ATTRIBUTES workItemAttributes; - - WDF_WORKITEM_CONFIG_INIT(&workItemConfig, - ReadWriteWorkItemRoutine - ); - - WDF_OBJECT_ATTRIBUTES_INIT(&workItemAttributes); - workItemAttributes.ParentObject = deviceExtension->Device; - - status = WdfWorkItemCreate(&workItemConfig, - &workItemAttributes, - &deviceExtension->ReadWriteWorkItem - ); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_INIT, - "DriverEvtDeviceAdd: Cannot create read/write work item, status: 0x%X\n", - status)); - } - } - - // 20. Initialize the work item that is used to process most IOCTLs at PASSIVE_LEVEL. - if (NT_SUCCESS(status)) - { - WDF_WORKITEM_CONFIG workItemConfig; - WDF_OBJECT_ATTRIBUTES workItemAttributes; - - WDF_WORKITEM_CONFIG_INIT(&workItemConfig, - IoctlWorkItemRoutine - ); - - WDF_OBJECT_ATTRIBUTES_INIT(&workItemAttributes); - workItemAttributes.ParentObject = deviceExtension->Device; - - status = WdfWorkItemCreate(&workItemConfig, - &workItemAttributes, - &deviceExtension->IoctlWorkItem - ); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_INIT, - "DriverEvtDeviceAdd: Cannot create ioctl work item, status: 0x%X\n", - status)); - } - } - - -Exit: - - if (!NT_SUCCESS(status)) - { - FREE_POOL(wideDeviceName); - - if (deviceExtension != NULL) - { - RtlInitUnicodeString(&deviceExtension->DeviceName, NULL); - } - - // Release the device with the port driver, if it was claimed - if ((deviceExtension != NULL) && deviceClaimed) - { - DeviceClaimRelease(deviceExtension, TRUE); - } - deviceClaimed = FALSE; - } - - return status; -} - - -VOID -DeviceEvtCleanup( - _In_ WDFOBJECT Device - ) -/*++ -Routine Description: - - Free all the resources allocated in DriverEvtDeviceAdd. - -Arguments: - - Device - handle to a WDF Device object. - -Return Value: - - VOID. - ---*/ -{ - WDFDEVICE device = (WDFDEVICE)Device; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - - PAGED_CODE (); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "WDFDEVICE %p cleanup: The device is about to be destroyed.\n", - device)); - - deviceExtension = DeviceGetExtension(device); - - FREE_POOL(deviceExtension->DeviceName.Buffer); - RtlInitUnicodeString(&deviceExtension->DeviceName, NULL); - - if (deviceExtension->DeviceAdditionalData.WellKnownName.Buffer != NULL) - { - IoDeleteSymbolicLink(&deviceExtension->DeviceAdditionalData.WellKnownName); - } - - FREE_POOL(deviceExtension->DeviceAdditionalData.WellKnownName.Buffer); - RtlInitUnicodeString(&deviceExtension->DeviceAdditionalData.WellKnownName, NULL); - - return; -} - - -VOID -DeviceEvtSelfManagedIoCleanup( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - this function is called when the device is removed. - release the ownership of the device, release allocated resources. - -Arguments: - - Device - Handle to device object - -Return Value: - - None. - ---*/ -{ - NTSTATUS status; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - - PAGED_CODE (); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_PNP, - "DeviceEvtSelfManagedIoCleanup: WDFDEVICE %p is being stopped.\n", - Device)); - - // extract the device and driver extensions - deviceExtension = DeviceGetExtension(Device); - - // Purge unprocessed requests, stop the IO queues. - // Incoming request will be completed with STATUS_INVALID_DEVICE_STATE status. - WdfIoQueuePurge(deviceExtension->SerialIOQueue, WDF_NO_EVENT_CALLBACK, WDF_NO_CONTEXT); - WdfIoQueuePurge(deviceExtension->CreateQueue, WDF_NO_EVENT_CALLBACK, WDF_NO_CONTEXT); - - // Close the IoTarget so that we are sure there are no outstanding I/Os in the stack. - if (deviceExtension->IoTarget) - { - WdfIoTargetClose(deviceExtension->IoTarget); - } - - // Release the device - if (!deviceExtension->SurpriseRemoved) - { - status = DeviceClaimRelease(deviceExtension, TRUE); //status is mainly for debugging. we don't really care. - UNREFERENCED_PARAMETER(status); //defensive coding, avoid PREFAST warning. - } - - // Be sure to flush the DPCs as the READ/WRITE timer routine may still be running - // during device removal. This call may take a while to complete. - KeFlushQueuedDpcs(); - - // Release all the memory that we have allocated. - - DeviceDeallocateMmcResources(Device); - ScratchBuffer_Deallocate(deviceExtension); - RtlZeroMemory(&(deviceExtension->DeviceAdditionalData.Mmc), sizeof(CDROM_MMC_EXTENSION)); - - FREE_POOL(deviceExtension->DeviceDescriptor); - FREE_POOL(deviceExtension->AdapterDescriptor); - FREE_POOL(deviceExtension->PowerDescriptor); - FREE_POOL(deviceExtension->SenseData); - - if (deviceExtension->DeviceAdditionalData.CachedInquiryData != NULL) - { - FREE_POOL(deviceExtension->DeviceAdditionalData.CachedInquiryData); - deviceExtension->DeviceAdditionalData.CachedInquiryDataByteCount = 0; - } - - FREE_POOL(deviceExtension->PrivateFdoData); - - DeviceReleaseMcnResources(deviceExtension); - - DeviceReleaseZPODDResources(deviceExtension); - - // Keep the system-wide CDROM count accurate, as programs use this info to - // know when they have found all the cdroms in a system. - IoGetConfigurationInformation()->CdRomCount--; - - deviceExtension->PartitionLength.QuadPart = 0; - - // All WDF objects related to Device will be automatically released - // when the root object is deleted. No need to release them manually. - - return; -} - -NTSTATUS -DeviceEvtD0Entry( - _In_ WDFDEVICE Device, - _In_ WDF_POWER_DEVICE_STATE PreviousState - ) -/*++ - -Routine Description: - - This function is called when the device is coming back from a lower power state to D0. - This function cannot be placed in a pageable section. - -Arguments: - - Device - Handle to device object - PreviousState - Power state the device was in. - -Return Value: - - NTSTATUS: alway STATUS_SUCCESS - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension; - NTSTATUS status = STATUS_SUCCESS; - PZERO_POWER_ODD_INFO zpoddInfo = NULL; - STORAGE_IDLE_POWERUP_REASON powerupReason = {0}; - - UNREFERENCED_PARAMETER(PreviousState); - deviceExtension = DeviceGetExtension(Device); - - // Make certain not to do anything before properly initialized - if (deviceExtension->IsInitialized) - { - zpoddInfo = deviceExtension->ZeroPowerODDInfo; - - if (zpoddInfo != NULL) - { - if (zpoddInfo->InZeroPowerState != FALSE) - { - // We just woke up from Zero Power state - zpoddInfo->InZeroPowerState = FALSE; - zpoddInfo->RetryFirstCommand = TRUE; - zpoddInfo->BecomingReadyRetryCount = BECOMING_READY_RETRY_COUNT; - - status = DeviceZPODDGetPowerupReason(deviceExtension, &powerupReason); - - if (NT_SUCCESS(status) && - (powerupReason.PowerupReason == StoragePowerupDeviceAttention)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceEvtD0Entry: Device has left zero power state due to eject button pressed\n" - )); - - // This wake-up is caused by user pressing the eject button. - // In case of drawer type, we need to soft eject the tray to emulate the effect. - // Note that the first command to the device after power resumed will - // be terminated with CHECK CONDITION status with sense code 6/29/00, - // but we already have a retry logic to handle this. - if ((zpoddInfo->LoadingMechanism == LOADING_MECHANISM_TRAY) && (zpoddInfo->Load == 0)) // Drawer - { - DeviceSendIoctlAsynchronously(deviceExtension, IOCTL_STORAGE_EJECT_MEDIA, deviceExtension->DeviceObject); - } - } - else - { - // This wake-up is caused by non-cached CDB received or a 3rd-party driver - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceEvtD0Entry: Device has left zero power state due to IO received\n" - )); - - } - } - } - - DeviceEnableMainTimer(deviceExtension); - } - - return STATUS_SUCCESS; -} - -NTSTATUS -DeviceEvtD0Exit( - _In_ WDFDEVICE Device, - _In_ WDF_POWER_DEVICE_STATE TargetState - ) -/*++ - -Routine Description: - - This function is called when the device is entering lower powe state from D0 or it's removed. - We only care about the case of device entering D3. - The purpose of this function is to send SYNC CACHE command and STOP UNIT command if it's necessary. - -Arguments: - - Device - Handle to device object - TargetState - Power state the device is entering. - -Return Value: - - NTSTATUS: alway STATUS_SUCCESS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - PZERO_POWER_ODD_INFO zpoddInfo = NULL; - - PAGED_CODE (); - - deviceExtension = DeviceGetExtension(Device); - zpoddInfo = deviceExtension->ZeroPowerODDInfo; - - // we only process the situation that the device is going into D3. - if ((TargetState != WdfPowerDeviceD3) && - (TargetState != WdfPowerDeviceD3Final)) - { - return STATUS_SUCCESS; - } - - // Stop the main timer - DeviceDisableMainTimer(deviceExtension); - - // note: do not stop CreateQueue as the create request can be handled by port driver even the device is in D3 status. - - // If initialization was not finished or the device was removed, we cannot interact - // with it device, so we have to exit - if ((!deviceExtension->IsInitialized) || deviceExtension->SurpriseRemoved) - { - return STATUS_SUCCESS; - } - - -#ifdef DBG - #if (WINVER >= 0x0601) - // this API is introduced in Windows7 - { - ULONG secondsRemaining = 0; - BOOLEAN watchdogTimeSupported = FALSE; - - watchdogTimeSupported = PoQueryWatchdogTime(deviceExtension->LowerPdo, &secondsRemaining); - UNREFERENCED_PARAMETER(watchdogTimeSupported); - } - #endif -#endif - - deviceExtension->PowerDownInProgress = TRUE; - - status = PowerContextBeginUse(deviceExtension); - - deviceExtension->PowerContext.Options.PowerDown = TRUE; - - // Step 1. LOCK QUEUE - if (NT_SUCCESS(status) && - (TargetState != WdfPowerDeviceD3Final)) - { - status = DeviceSendPowerDownProcessRequest(deviceExtension, NULL, NULL); - - if (NT_SUCCESS(status)) - { - deviceExtension->PowerContext.Options.LockQueue = TRUE; - } - - // Ignore failure. - status = STATUS_SUCCESS; - } - - deviceExtension->PowerContext.PowerChangeState.PowerDown++; - - // Step 2. QUIESCE QUEUE - if (NT_SUCCESS(status) && - (TargetState != WdfPowerDeviceD3Final)) - { - status = DeviceSendPowerDownProcessRequest(deviceExtension, NULL, NULL); - UNREFERENCED_PARAMETER(status); - // We don't care about the status. - status = STATUS_SUCCESS; - } - - deviceExtension->PowerContext.PowerChangeState.PowerDown++; - - // Step 3. SYNC CACHE command should be sent to drive if the media is currently writable. - if (NT_SUCCESS(status) && - deviceExtension->DeviceAdditionalData.Mmc.WriteAllowed) - { - status = DeviceSendPowerDownProcessRequest(deviceExtension, NULL, NULL); - UNREFERENCED_PARAMETER(status); - status = STATUS_SUCCESS; - } - - deviceExtension->PowerContext.PowerChangeState.PowerDown++; - - // Step 4. STOP UNIT - if (NT_SUCCESS(status) && - !TEST_FLAG(deviceExtension->ScanForSpecialFlags, CDROM_SPECIAL_DISABLE_SPIN_DOWN)) - { - status = DeviceSendPowerDownProcessRequest(deviceExtension, NULL, NULL); - UNREFERENCED_PARAMETER(status); - status = STATUS_SUCCESS; - } - - if (TargetState == WdfPowerDeviceD3Final) - { - // We're done with the power context. - PowerContextEndUse(deviceExtension); - } - - // Bumping the media change count will force the file system to verify the volume when we resume - SET_FLAG(deviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - InterlockedIncrement((PLONG)&deviceExtension->MediaChangeCount); - - // If this power down is caused by Zero Power ODD, we should mark the device as in ZPODD mode. - if (zpoddInfo != NULL) - { - zpoddInfo->InZeroPowerState = TRUE; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "Device has entered zero power state\n" - )); - } - - deviceExtension->PowerDownInProgress = FALSE; - - return STATUS_SUCCESS; -} - - -VOID -DeviceEvtSurpriseRemoval( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - this function is called when the device is surprisely removed. - Stop all IO queues so that there will be no more request being sent down. - -Arguments: - - Device - Handle to device object - -Return Value: - - None. - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - - PAGED_CODE(); - - deviceExtension = DeviceGetExtension(Device); - - deviceExtension->SurpriseRemoved = TRUE; - - // Stop the main timer - DeviceDisableMainTimer(deviceExtension); - - // legacy behavior to set partition length to be 0. - deviceExtension->PartitionLength.QuadPart = 0; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Surprisely remove a WDFDEVICE %p\n", Device)); - - return; -} - - -VOID -CreateQueueEvtIoDefault( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - this function is called when CREATE irp comes. - setup FileObject context fields, so it can be used to track MCN or exclusive lock/unlock. - -Arguments: - - Queue - Handle to device queue - - Request - the creation request - -Return Value: - - None - ---*/ -{ - WDFFILEOBJECT fileObject = WdfRequestGetFileObject(Request); - WDFDEVICE device = WdfIoQueueGetDevice(Queue); - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - PFILE_OBJECT_CONTEXT fileObjectContext = NULL; - - PAGED_CODE(); - - if (fileObject == NULL) { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_QUEUE, - "Error: received a file create request with file object set to NULL\n")); - - RequestCompletion(deviceExtension, Request, STATUS_INTERNAL_ERROR, 0); - return; - } - - fileObjectContext = FileObjectGetContext(fileObject); - - // Initialize this WDFFILEOBJECT's context - fileObjectContext->DeviceObject = device; - fileObjectContext->FileObject = fileObject; - fileObjectContext->LockCount = 0; - fileObjectContext->McnDisableCount = 0; - fileObjectContext->EnforceStreamingRead = FALSE; - fileObjectContext->EnforceStreamingWrite = FALSE; - - // send down the create synchronously - status = DeviceSendRequestSynchronously(device, Request, FALSE); - - // Need to complete the request in this routine. - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - - return; -} - -VOID -DeviceEvtFileClose( - _In_ WDFFILEOBJECT FileObject - ) -/*++ - -Routine Description: - - this function is called when CLOSE irp comes. - clean up MCN / Lock if necessary - -Arguments: - - FileObject - WDF file object created for the irp. - -Return Value: - - None - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - if (FileObject != NULL) - { - WDFDEVICE device = WdfFileObjectGetDevice(FileObject); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - PFILE_OBJECT_CONTEXT fileObjectContext = FileObjectGetContext(FileObject); - - // cleanup locked media tray - status = DeviceCleanupProtectedLocks(deviceExtension, fileObjectContext); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Failed to cleanup protected locks for WDFDEVICE %p, %!STATUS!\n", device, status)); - } - - // cleanup disabled MCN - status = DeviceCleanupDisableMcn(deviceExtension, fileObjectContext); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Failed to disable MCN for WDFDEVICE %p, %!STATUS!\n", device, status)); - } - - // cleanup exclusive access - if (EXCLUSIVE_MODE(cdData) && EXCLUSIVE_OWNER(cdData, FileObject)) - { - status = DeviceUnlockExclusive(deviceExtension, FileObject, FALSE); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Failed to release exclusive lock for WDFDEVICE %p, %!STATUS!\n", device, status)); - } - } - } - - return; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceCleanupProtectedLocks( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PFILE_OBJECT_CONTEXT FileObjectContext - ) -/*++ - -Routine Description: - - this function removes protected locks for the handle - -Arguments: - - DeviceExtension - device context - - FileObject - WDF file object created for the irp. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "CleanupProtectedLocks called for WDFDEVICE %p, WDFFILEOBJECT %p, locked %d times.\n", - DeviceExtension->Device, FileObjectContext->FileObject, FileObjectContext->LockCount)); - - // Synchronize with ejection and ejection control requests. - WdfWaitLockAcquire(DeviceExtension->EjectSynchronizationLock, NULL); - - // For each secure lock on this handle decrement the secured lock count - // for the FDO. Keep track of the new value. - if (FileObjectContext->LockCount != 0) - { - DeviceExtension->ProtectedLockCount -= FileObjectContext->LockCount; - FileObjectContext->LockCount = 0; - - // If the new lock count has been dropped to zero then issue a lock - // command to the device. - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "FDO secured lock count = %d " - "lock count = %d\n", - DeviceExtension->ProtectedLockCount, - DeviceExtension->LockCount)); - - if ((DeviceExtension->ProtectedLockCount == 0) && (DeviceExtension->LockCount == 0)) - { - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb = (PCDB) &(srb.Cdb); - - srb.CdbLength = 6; - - cdb->MEDIA_REMOVAL.OperationCode = SCSIOP_MEDIUM_REMOVAL; - - // TRUE - prevent media removal. - // FALSE - allow media removal. - cdb->MEDIA_REMOVAL.Prevent = FALSE; - - // Set timeout value. - srb.TimeOutValue = DeviceExtension->TimeOutValue; - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - NULL, - 0, - FALSE, - NULL); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Allow media removal (unlock) request to drive returned %!STATUS!\n", - status)); - } - } - - WdfWaitLockRelease(DeviceExtension->EjectSynchronizationLock); - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceCleanupDisableMcn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PFILE_OBJECT_CONTEXT FileObjectContext - ) -/*++ - -Routine Description: - - cleanup the MCN disable count for the handle - -Arguments: - - DeviceExtension - device context - - FileObject - WDF file object created for the irp. - -Return Value: - - NTSTATUS - ---*/ -{ - PAGED_CODE(); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CleanupDisableMcn called for WDFDEVICE %p, WDFFILEOBJECT %p, locked %d times.\n", - DeviceExtension->Device, FileObjectContext->FileObject, FileObjectContext->McnDisableCount)); - - // For each secure lock on this handle decrement the secured lock count - // for the FDO. Keep track of the new value. - while (FileObjectContext->McnDisableCount != 0) - { - DeviceEnableMediaChangeDetection(DeviceExtension, FileObjectContext, TRUE); - } - - return STATUS_SUCCESS; -} - -VOID -NormalizeIoctl( - _Inout_ PWDF_REQUEST_PARAMETERS requestParameters - ) -{ - ULONG ioctlCode; - ULONG baseCode; - ULONG functionCode; - - // if this is a class driver ioctl then we need to change the base code - // to IOCTL_STORAGE_BASE so that the switch statement can handle it. - // - // WARNING - currently the scsi class ioctl function codes are between - // 0x200 & 0x300. this routine depends on that fact - ioctlCode = requestParameters->Parameters.DeviceIoControl.IoControlCode; - baseCode = DEVICE_TYPE_FROM_CTL_CODE(ioctlCode); - functionCode = (ioctlCode & (~0xffffc003)) >> 2; - - if ((baseCode == IOCTL_SCSI_BASE) || - (baseCode == IOCTL_DISK_BASE) || - (baseCode == IOCTL_TAPE_BASE) || - (baseCode == IOCTL_DVD_BASE) || - (baseCode == IOCTL_CDROM_BASE)) - //IOCTL_STORAGE_BASE does not need to be converted. - { - if((functionCode >= 0x200) && (functionCode <= 0x300)) - { - ioctlCode = (ioctlCode & 0x0000ffff) | CTL_CODE(IOCTL_STORAGE_BASE, 0, 0, 0); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "IOCTL code recalibrate, New ioctl code is %lx\n", - ioctlCode)); - - // Set the code into request parameters, then "requestParameters" needs to be used for dispatch functions. - requestParameters->Parameters.DeviceIoControl.IoControlCode = ioctlCode; - } - } -} - -VOID -DeviceEvtIoInCallerContext( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ -Routine Description: - - Responds to EvtIoInCallerContext events from KMDF - It calls different functions to process different type of IOCTLs. - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - -Return Value: - - VOID. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - WDF_REQUEST_PARAMETERS requestParameters; - - requestContext->DeviceExtension = deviceExtension; - - // set the received time - RequestSetReceivedTime(Request); - - // get the request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - if (requestParameters.Type == WdfRequestTypeDeviceControl) - { - BOOLEAN processed = FALSE; - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - PMEDIA_CHANGE_DETECTION_INFO info = deviceExtension->MediaChangeDetectionInfo; - - if (requestParameters.Parameters.DeviceIoControl.IoControlCode != IOCTL_MCN_SYNC_FAKE_IOCTL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "Receiving IOCTL: %lx\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "Receiving IOCTL: %lx\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - } - - // If the device is in exclusive mode, check whether the request is from - // the handle that locked the device. - if (EXCLUSIVE_MODE(cdData) && !EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) - { - BOOLEAN isBlocked = FALSE; - - status = RequestIsIoctlBlockedByExclusiveAccess(Request, &isBlocked); - UNREFERENCED_PARAMETER(status); //defensive coding, avoid PREFAST warning. - - if (isBlocked) - { - if ((requestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_STORAGE_EVENT_NOTIFICATION) && - (info != NULL) && (info->AsynchronousNotificationSupported != FALSE)) - { - // If AN is supported and we receive a signal but we can't send down GESN - // due to exclusive lock, we should save it and fire a GESN when it's unlocked. - // We just need true/false here and don't need count because we will keep sending - // GESN until we deplete all events. - info->ANSignalPendingDueToExclusiveLock = TRUE; - } - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "Access Denied! Device in exclusive mode.Failing Ioctl %lx\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - RequestCompletion(deviceExtension, Request, STATUS_ACCESS_DENIED, 0); - - return; - } - } - - NormalizeIoctl(&requestParameters); - - // 1. All requests that don't need to access device can be processed immediately - if (!processed) - { - processed = RequestDispatchProcessDirectly(Device, Request, requestParameters); - } - - // 2. Requests that should be put in sequential queue. - if (!processed) - { - processed = RequestDispatchToSequentialQueue(Device, Request, requestParameters); - } - - // 3. Requests that need to be processed sequentially and in caller's context. - if (!processed) - { - processed = RequestDispatchSyncWithSequentialQueue(Device, Request, requestParameters); - } - - // 4. Special requests that needs different process in different cases. - if (!processed) - { - processed = RequestDispatchSpecialIoctls(Device, Request, requestParameters); - } - - // 5. This is default behavior for unknown IOCTLs. To pass it to lower level. - if (!processed) - { - processed = RequestDispatchUnknownRequests(Device, Request, requestParameters); - } - - // All requests should be processed already. - NT_ASSERT(processed); - UNREFERENCED_PARAMETER(processed); //defensive coding, avoid PREFAST warning. - } - else if (requestParameters.Type == WdfRequestTypeDeviceControlInternal) - { - RequestProcessInternalDeviceControl(Request, deviceExtension); - } - else - { - // Requests other than IOCTLs will be forwarded to default queue. - status = WdfDeviceEnqueueRequest(Device, Request); - if (!NT_SUCCESS(status)) - { - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - } - } - - return; -} - - -BOOLEAN -RequestDispatchProcessDirectly( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ -Routine Description: - - These requests can be processed in a non-serialized manner, most of them don't need to access device. - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - - RequestParameters - request parameters - -Return Value: - - BOOLEAN - TRUE (request processed); FALSE (request is not processed in this function). - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - BOOLEAN processed = FALSE; - size_t dataLength = 0; - - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - - switch (ioctlCode) - { - - case IOCTL_CDROM_GET_INQUIRY_DATA: - { - status = RequestHandleGetInquiryData(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_GET_MEDIA_TYPES_EX: - { - status = RequestHandleGetMediaTypeEx(deviceExtension, Request, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: - { - status = RequestHandleMountQueryUniqueId(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: - { - status = RequestHandleMountQueryDeviceName(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: - { - status = RequestHandleMountQuerySuggestedLinkName(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_GET_DEVICE_NUMBER: - { - status = RequestHandleGetDeviceNumber(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_GET_HOTPLUG_INFO: - { - status = RequestHandleGetHotPlugInfo(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_SET_HOTPLUG_INFO: - { - status = RequestHandleSetHotPlugInfo(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_EVENT_NOTIFICATION: - { - status = RequestHandleEventNotification(deviceExtension, Request, &RequestParameters, &dataLength); - - processed = TRUE; - break; // complete the irp - } - -#if (NTDDI_VERSION >= NTDDI_WIN8) - case IOCTL_VOLUME_ONLINE: - { - // - // Mount manager and volume manager will - // follow this online with a post online - // but other callers may not. In those - // cases, we process this request right - // away. We approximate that these other - // callers are from user mode - // - - if (WdfRequestGetRequestorMode(Request) == KernelMode) - { - processed = TRUE; - } - break; - } -#endif - - default: - { - processed = FALSE; - break; - } - - } //end of switch (ioctlCode) - - if (processed) - { - UCHAR currentStackLocationFlags = 0; - currentStackLocationFlags = RequestGetCurrentStackLocationFlags(Request); - - if ((status == STATUS_VERIFY_REQUIRED) && - (currentStackLocationFlags & SL_OVERRIDE_VERIFY_VOLUME)) - { - // If the status is verified required and this request - // should bypass verify required then retry the request. - status = STATUS_IO_DEVICE_ERROR; - UNREFERENCED_PARAMETER(status); // disables prefast warning; defensive coding... - - processed = RequestDispatchProcessDirectly(Device, Request, RequestParameters); - } - else - { - // Complete the request after processing it. - RequestCompletion(deviceExtension, Request, status, dataLength); - } - } - - return processed; -} - - -BOOLEAN -RequestDispatchToSequentialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ -Routine Description: - - These requests can be processed in a non-serialized manner, most of them don't need to access device. - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - - RequestParameters - request parameters - -Return Value: - - BOOLEAN - TRUE (request processed); FALSE (request is not processed in this function). - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - BOOLEAN processed = FALSE; - size_t dataLength = 0; - BOOLEAN inZeroPowerState = FALSE; - - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - PZERO_POWER_ODD_INFO zpoddInfo = deviceExtension->ZeroPowerODDInfo; - - if ((zpoddInfo != NULL) && - (zpoddInfo->InZeroPowerState != FALSE)) - { - inZeroPowerState = TRUE; - } - - switch (ioctlCode) - { - - case IOCTL_CDROM_RAW_READ: - { - status = RequestValidateRawRead(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get drive geometryEx\n")); - if ( RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - (ULONG)FIELD_OFFSET(DISK_GEOMETRY_EX, Data)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = FIELD_OFFSET(DISK_GEOMETRY_EX, Data); - } - else if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_DRIVE_GEOMETRY: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get drive geometry\n")); - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(DISK_GEOMETRY)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(DISK_GEOMETRY); - } - else if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_READ_TOC_EX: - { - status = RequestValidateReadTocEx(deviceExtension, Request, RequestParameters, &dataLength); - - if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_READ_TOC: - { - status = RequestValidateReadToc(deviceExtension, RequestParameters, &dataLength); - - if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_GET_LAST_SESSION: - { - status = RequestValidateGetLastSession(deviceExtension, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_PLAY_AUDIO_MSF: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Play audio MSF\n")); - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_PLAY_AUDIO_MSF)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_SEEK_AUDIO_MSF: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Seek audio MSF\n")); - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_SEEK_AUDIO_MSF)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_PAUSE_AUDIO: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Pause audio\n")); - - status = STATUS_SUCCESS; - processed = TRUE; - break; - } - - case IOCTL_CDROM_RESUME_AUDIO: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Resume audio\n")); - - status = STATUS_SUCCESS; - processed = TRUE; - break; - } - - case IOCTL_CDROM_READ_Q_CHANNEL: - { - status = RequestValidateReadQChannel(Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_GET_VOLUME: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get volume control\n")); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(VOLUME_CONTROL)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(VOLUME_CONTROL); - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_SET_VOLUME: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Set volume control\n")); - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(VOLUME_CONTROL)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_STOP_AUDIO: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Stop audio\n")); - - status = STATUS_SUCCESS; - processed = TRUE; - break; - } - - case IOCTL_STORAGE_CHECK_VERIFY: - case IOCTL_STORAGE_CHECK_VERIFY2: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] Check Verify\n", Request)); - - // Following check will let the condition "OutputBufferLength == 0" pass. - // Since it's legacy behavior in classpnp, we need to keep it. - if ((RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > 0) && - (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(ULONG))) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(ULONG); - } - else if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DVD_GET_REGION: - { - // validation will be done when process it. - status = STATUS_SUCCESS; - processed = TRUE; - break; - } - - case IOCTL_DVD_READ_STRUCTURE: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_DVD_READ_STRUCTURE\n", Request)); - - status = RequestValidateDvdReadStructure(deviceExtension, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_DVD_READ_KEY: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_DVD_READ_KEY\n", Request)); - - status = RequestValidateDvdReadKey(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_DVD_START_SESSION: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_DVD_START_SESSION\n", Request)); - - status = RequestValidateDvdStartSession(deviceExtension, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_DVD_SEND_KEY: - case IOCTL_DVD_SEND_KEY2: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_DVD_SEND_KEY\n", Request)); - - status = RequestValidateDvdSendKey(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_STORAGE_SET_READ_AHEAD: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] SetReadAhead\n", Request)); - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(STORAGE_SET_READ_AHEAD)) - { - status = STATUS_INVALID_PARAMETER; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_IS_WRITABLE: - { - status = STATUS_SUCCESS; - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_DRIVE_LAYOUT: - { - ULONG requiredSize = 0; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get drive layout\n")); - - requiredSize = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION, PartitionEntry[1]); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - requiredSize) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = requiredSize; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_DRIVE_LAYOUT_EX: - { - ULONG requiredSize = 0; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get drive layoutEx\n")); - - requiredSize = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION_EX, PartitionEntry[1]); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - requiredSize) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = requiredSize; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_PARTITION_INFO: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get Partition Info\n")); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(PARTITION_INFORMATION)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(PARTITION_INFORMATION); - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_PARTITION_INFO_EX: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Get Partition InfoEx\n")); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(PARTITION_INFORMATION_EX)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(PARTITION_INFORMATION_EX); - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_VERIFY: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: IOCTL_DISK_VERIFY to device %p through request %p\n", - Device, - Request)); - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(VERIFY_INFORMATION)) - { - status = STATUS_INVALID_PARAMETER; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_DISK_GET_LENGTH_INFO: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: Disk Get Length InfoEx\n")); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(GET_LENGTH_INFORMATION)) - { - status = STATUS_BUFFER_TOO_SMALL; - dataLength = sizeof(GET_LENGTH_INFORMATION); - } - else if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; - } - - case IOCTL_CDROM_GET_CONFIGURATION: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_CDROM_GET_CONFIGURATION\n", Request)); - - status = RequestValidateGetConfiguration(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_SET_SPEED: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_CDROM_SET_SPEED\n", Request)); - - status = RequestValidateSetSpeed(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_DVD_END_SESSION: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_DVD_END_SESSION\n", Request)); - - status = RequestValidateDvdEndSession(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_END_SESSION: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_AACS_END_SESSION\n", Request)); - - status = RequestValidateAacsEndSession(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_READ_MEDIA_KEY_BLOCK: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Querying full MKB with bufferSize of %x bytes\n", - (int)RequestParameters.Parameters.DeviceIoControl.OutputBufferLength - )); - - status = RequestValidateAacsReadMediaKeyBlock(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_START_SESSION: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Requesting AGID\n" - )); - - status = RequestValidateAacsStartSession(deviceExtension, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_SEND_CERTIFICATE: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Sending host certificate to drive\n" - )); - - status = RequestValidateAacsSendCertificate(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_GET_CERTIFICATE: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Querying drive certificate\n" - )); - - status = RequestValidateAacsGetCertificate(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_GET_CHALLENGE_KEY: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Querying drive challenge key\n" - )); - - status = RequestValidateAacsGetChallengeKey(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_SEND_CHALLENGE_KEY: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Sending drive challenge key\n" - )); - - status = RequestValidateAacsSendChallengeKey(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_READ_VOLUME_ID: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Reading volume ID\n" - )); - - status = RequestValidateAacsReadVolumeId(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_READ_SERIAL_NUMBER: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Reading Serial Number\n" - )); - - status = RequestValidateAacsReadSerialNumber(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_READ_MEDIA_ID: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Reading media ID\n" - )); - - status = RequestValidateAacsReadMediaId(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_AACS_READ_BINDING_NONCE: - case IOCTL_AACS_GENERATE_BINDING_NONCE: - { - if (ioctlCode == IOCTL_AACS_GENERATE_BINDING_NONCE) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Generating new binding nonce\n" - )); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "AACS: Reading existing binding nonce\n" - )); - } - - status = RequestValidateAacsBindingNonce(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_ENABLE_STREAMING: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_CDROM_ENABLE_STREAMING\n", Request)); - - status = RequestValidateEnableStreaming(Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_SEND_OPC_INFORMATION: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_CDROM_SEND_OPC_INFORMATION\n", Request)); - - status = RequestValidateSendOpcInformation(Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_CDROM_GET_PERFORMANCE: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestDispatchToSequentialQueue: [%p] IOCTL_CDROM_GET_PERFORMANCE\n", Request)); - - status = RequestValidateGetPerformance(Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_STORAGE_MEDIA_REMOVAL: - case IOCTL_STORAGE_EJECTION_CONTROL: - { - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(PREVENT_MEDIA_REMOVAL)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_MCN_CONTROL: - { - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(PREVENT_MEDIA_REMOVAL)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_RESERVE: - case IOCTL_STORAGE_RELEASE: - { - // there is no validate check currently. - status = STATUS_SUCCESS; - processed = TRUE; - break; - } - - case IOCTL_STORAGE_PERSISTENT_RESERVE_IN: - case IOCTL_STORAGE_PERSISTENT_RESERVE_OUT: - { - status = RequestValidatePersistentReserve(deviceExtension, Request, RequestParameters, &dataLength); - - processed = TRUE; - break; - } - - case IOCTL_STORAGE_EJECT_MEDIA: - case IOCTL_STORAGE_LOAD_MEDIA: - case IOCTL_STORAGE_LOAD_MEDIA2: - { - status = STATUS_SUCCESS; - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_FIND_NEW_DEVICES: - { - // process it. - IoInvalidateDeviceRelations(deviceExtension->LowerPdo, BusRelations); - - status = STATUS_SUCCESS; - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_READ_CAPACITY: - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_READ_CAPACITY)) - { - dataLength = sizeof(STORAGE_READ_CAPACITY); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (inZeroPowerState != FALSE) - { - status = STATUS_NO_MEDIA_IN_DEVICE; - } - else - { - status = STATUS_SUCCESS; - } - - processed = TRUE; - break; // complete the irp - } - - case IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT: - { - // for disk.sys only in original classpnp - status = STATUS_NOT_SUPPORTED; - - processed = TRUE; - break; // complete the irp - } - -#if (NTDDI_VERSION >= NTDDI_WIN8) - case IOCTL_DISK_ARE_VOLUMES_READY: - { - // this request doesn't access device at all, so seemingly it can be processed - // directly; however, in case volume online is not received, we will need to - // park these requests in a queue, and the only way a request can be queued is - // if the request came out of another queue. - status = STATUS_SUCCESS; - - processed = TRUE; - break; - } - - case IOCTL_VOLUME_ONLINE: - case IOCTL_VOLUME_POST_ONLINE: - { - status = STATUS_SUCCESS; - - processed = TRUE; - break; - } -#endif - - default: - { - processed = FALSE; - break; - } - } //end of switch (ioctlCode) - - if (processed) - { - UCHAR currentStackLocationFlags = 0; - currentStackLocationFlags = RequestGetCurrentStackLocationFlags(Request); - - if ((status == STATUS_VERIFY_REQUIRED) && - (currentStackLocationFlags & SL_OVERRIDE_VERIFY_VOLUME)) - { - // If the status is verified required and this request - // should bypass verify required then retry the request. - status = STATUS_IO_DEVICE_ERROR; - UNREFERENCED_PARAMETER(status); // disables prefast warning; defensive coding... - - processed = RequestDispatchToSequentialQueue(Device, Request, RequestParameters); - } - else - { - if (NT_SUCCESS(status)) - { - // Forward the request to serialized queue. - status = WdfDeviceEnqueueRequest(Device, Request); - } - - if (!NT_SUCCESS(status)) - { - // Validation failed / forward failed, complete the request. - RequestCompletion(deviceExtension, Request, status, dataLength); - } - } - } - - return processed; -} - - -BOOLEAN -RequestDispatchSyncWithSequentialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ -Routine Description: - - These requests need to stay in caller's context and be processed in serialized manner. - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - - RequestParameters - request parameters - -Return Value: - - BOOLEAN - TRUE (request processed); FALSE (request is not processed in this function). - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - BOOLEAN processed = FALSE; - size_t dataLength = 0; - - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - - switch (ioctlCode) - { - - case IOCTL_CDROM_EXCLUSIVE_ACCESS: - { - //1. Validate - status = RequestValidateExclusiveAccess(Request, RequestParameters, &dataLength); - - //2. keep the request in serialized manner and stay in user's context. - if (NT_SUCCESS(status)) - { - PCDROM_EXCLUSIVE_ACCESS exclusiveAccess = NULL; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &exclusiveAccess, - NULL); - - if (NT_SUCCESS(status)) - { - // do not need to check "status" as it passed validation and cannot fail in WdfRequestRetrieveInputBuffer() - switch (exclusiveAccess->RequestType) - { - - case ExclusiveAccessQueryState: - { - status = RequestSetContextFields(Request, RequestHandleExclusiveAccessQueryLockState); - break; - } - - case ExclusiveAccessLockDevice: - { - status = RequestSetContextFields(Request, RequestHandleExclusiveAccessLockDevice); - break; - } - - case ExclusiveAccessUnlockDevice: - { - status = RequestSetContextFields(Request, RequestHandleExclusiveAccessUnlockDevice); - break; - } - default: - { - // already valicated in RequestValidateExclusiveAccess() - NT_ASSERT(FALSE); - break; - } - } - } - - if (NT_SUCCESS(status)) - { - // now, put the special synchronization information into the context - status = RequestSynchronizeProcessWithSerialQueue(Device, Request); - - // "status" is used for debugging in above statement, reset to success to avoid further work in this function. - status = STATUS_SUCCESS; - } - } - - processed = TRUE; - break; // complete the irp - } - - default: - { - processed = FALSE; - break; - } - } //end of switch (ioctlCode) - - // Following process is only valid if the request is not really processed. (failed in validation) - if (processed && !NT_SUCCESS(status)) - { - UCHAR currentStackLocationFlags = 0; - currentStackLocationFlags = RequestGetCurrentStackLocationFlags(Request); - - if ((status == STATUS_VERIFY_REQUIRED) && - (currentStackLocationFlags & SL_OVERRIDE_VERIFY_VOLUME)) - { - // - // If the status is verified required and this request - // should bypass verify required then retry the request. - // - status = STATUS_IO_DEVICE_ERROR; - UNREFERENCED_PARAMETER(status); // disables prefast warning; defensive coding... - - processed = RequestDispatchSyncWithSequentialQueue(Device, Request, RequestParameters); - } - else - { - // Validation failed / forward failed, complete the request. - RequestCompletion(deviceExtension, Request, status, dataLength); - } - } - - return processed; -} - - -BOOLEAN -RequestDispatchSpecialIoctls( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ -Routine Description: - - These requests need to be processed in different manner according to input parameters - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - - RequestParameters - request parameters - -Return Value: - - BOOLEAN - TRUE (request processed); FALSE (request is not processed in this function). - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - BOOLEAN processed = FALSE; - size_t dataLength = 0; - BOOLEAN requestCompleted = FALSE; - - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - - switch (ioctlCode) - { - case IOCTL_SCSI_PASS_THROUGH: - case IOCTL_SCSI_PASS_THROUGH_DIRECT: - case IOCTL_SCSI_PASS_THROUGH_EX: - case IOCTL_SCSI_PASS_THROUGH_DIRECT_EX: - { - // SPTI is considered special case as we need to set the MinorFunction before pass to low level. - -#if defined (_WIN64) - if (WdfRequestIsFrom32BitProcess(Request)) - { - if ((ioctlCode == IOCTL_SCSI_PASS_THROUGH) || (ioctlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT)) - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(SCSI_PASS_THROUGH32)) - { - status = STATUS_INVALID_PARAMETER; - } - } - else - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(SCSI_PASS_THROUGH32_EX)) - { - status = STATUS_INVALID_PARAMETER; - } - } - } - else -#endif - { - if ((ioctlCode == IOCTL_SCSI_PASS_THROUGH) || (ioctlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT)) - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(SCSI_PASS_THROUGH)) - { - status = STATUS_INVALID_PARAMETER; - } - } - else - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(SCSI_PASS_THROUGH_EX)) - { - status = STATUS_INVALID_PARAMETER; - } - } - } - - if (!NT_SUCCESS(status)) - { - // validation failed. - RequestCompletion(deviceExtension, Request, status, dataLength); - } - else - { - // keep the request in serialized manner and stay in user's context. - status = RequestSetContextFields(Request, RequestHandleScsiPassThrough); - - if (NT_SUCCESS(status)) - { - status = RequestSynchronizeProcessWithSerialQueue(Device, Request); - } - else - { - RequestCompletion(deviceExtension, Request, status, 0); - } - } - - requestCompleted = TRUE; - processed = TRUE; - break; - } - - case IOCTL_STORAGE_QUERY_PROPERTY: - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_PROPERTY_QUERY)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - PSTORAGE_PROPERTY_QUERY inputBuffer = NULL; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - if (!EXCLUSIVE_MODE(cdData) || // not locked - EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request)) || // request is from lock owner - (inputBuffer->QueryType == PropertyExistsQuery)) // request not access device - { - if (inputBuffer->PropertyId == StorageDeviceUniqueIdProperty) - { - // previously handled in classpnp - // keep the request in serialized manner and stay in user's context. - status = RequestSetContextFields(Request, RequestHandleQueryPropertyDeviceUniqueId); - - if (NT_SUCCESS(status)) - { - status = RequestSynchronizeProcessWithSerialQueue(Device, Request); - // remeber that the request has been completed. - requestCompleted = TRUE; - } - } - else if (inputBuffer->PropertyId == StorageDeviceWriteCacheProperty) - { - // previously handled in classpnp - // keep the request in serialized manner and stay in user's context. - status = RequestSetContextFields(Request, RequestHandleQueryPropertyWriteCache); - - if (NT_SUCCESS(status)) - { - status = RequestSynchronizeProcessWithSerialQueue(Device, Request); - // remeber that the request has been completed. - requestCompleted = TRUE; - } - } - else - { - // Pass to port driver for handling - RequestDispatchUnknownRequests(Device, Request, RequestParameters); - - // remeber that the request has been completed. - requestCompleted = TRUE; - } - } - else - { - // If cached data exists, return cached data. Otherwise, fail the request. - if ((inputBuffer->QueryType == PropertyStandardQuery) && - ((inputBuffer->PropertyId == StorageDeviceProperty) || (inputBuffer->PropertyId == StorageAdapterProperty)) ) - { - status = RequestHandleQueryPropertyRetrieveCachedData(deviceExtension, Request, RequestParameters, &dataLength); - } - else - { - status = STATUS_ACCESS_DENIED; - } - } - } - } - - processed = TRUE; - break; - } - - // this IOCTL is a fake one, used for MCN process sync-ed with serial queue. - case IOCTL_MCN_SYNC_FAKE_IOCTL: - { - PIRP irp = WdfRequestWdmGetIrp(Request); - - if ((deviceExtension->MediaChangeDetectionInfo != NULL) && - (irp == deviceExtension->MediaChangeDetectionInfo->MediaChangeSyncIrp) && - (WdfRequestGetRequestorMode(Request) == KernelMode) && - (RequestParameters.Parameters.Others.Arg1 == RequestSetupMcnSyncIrp) && - (RequestParameters.Parameters.Others.Arg2 == RequestSetupMcnSyncIrp) && - (RequestParameters.Parameters.Others.Arg4 == RequestSetupMcnSyncIrp)) - { - // This is the requset we use to sync Media Change Detection with sequential queue. - status = WdfDeviceEnqueueRequest(Device, Request); - - if (!NT_SUCCESS(status)) - { - RequestCompletion(deviceExtension, Request, status, dataLength); - } - - requestCompleted = TRUE; - processed = TRUE; - } - else - { - // process as an unknown request. - processed = FALSE; - } - break; - } - - default: - { - processed = FALSE; - break; - } - } //end of switch (ioctlCode) - - if (processed && !requestCompleted) - { - UCHAR currentStackLocationFlags = 0; - currentStackLocationFlags = RequestGetCurrentStackLocationFlags(Request); - - if ((status == STATUS_VERIFY_REQUIRED) && - (currentStackLocationFlags & SL_OVERRIDE_VERIFY_VOLUME)) - { - // If the status is verified required and this request - // should bypass verify required then retry the request. - status = STATUS_IO_DEVICE_ERROR; - UNREFERENCED_PARAMETER(status); // disables prefast warning; defensive coding... - - processed = RequestDispatchSpecialIoctls(Device, Request, RequestParameters); - } - else - { - RequestCompletion(deviceExtension, Request, status, dataLength); - } - } - - return processed; -} - - -BOOLEAN -RequestDispatchUnknownRequests( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ -Routine Description: - - All unknown requests will be pass to lower level driver. - If IRQL is PASSIVE_LEVEL, the request will be serialized; - Otherwise, it'll be sent and forget. - -Arguments: - - Device - handle to a WDF Device object - - Request - handle to the incoming WDF Request object - - RequestParameters - request parameters - -Return Value: - - BOOLEAN - TRUE (request processed); FALSE (request is not processed in this function). - ---*/ -{ - NTSTATUS status = STATUS_UNSUCCESSFUL; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - - ULONG baseCode = DEVICE_TYPE_FROM_CTL_CODE(RequestParameters.Parameters.DeviceIoControl.IoControlCode); - - if ((KeGetCurrentIrql() != PASSIVE_LEVEL) || - (baseCode == FILE_DEVICE_ACPI)) - { - // 1. When IRQL is higher than PASSIVE_LEVEL, - // 2. ataport sends IOCTL_ACPI_ASYNC_EVAL_METHOD before queue starts, - // send request directly to lower driver. - status = RequestHandleUnknownIoctl(Device, Request); - } - else - { - // keep the request in serialized manner and stay in user's context. - status = RequestSetContextFields(Request, RequestHandleUnknownIoctl); - - if (NT_SUCCESS(status)) - { - status = RequestSynchronizeProcessWithSerialQueue(Device, Request); - } - else - { - RequestCompletion(deviceExtension, Request, status, 0); - } - } - - UNREFERENCED_PARAMETER(status); //defensive coding, avoid PREFAST warning. - - // All unknown IOCTLs are processed in this function. - return TRUE; //processed -} - -VOID -RequestProcessInternalDeviceControl( - _In_ WDFREQUEST Request, - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ -Routine Description: - - all internal IOCTL will be send to lower driver asynchronously. - -Arguments: - - Request - handle to the incoming WDF Request object - DeviceExtension - device extension structure - -Return Value: - - None - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PIRP irp = NULL; - PIO_STACK_LOCATION irpStack = NULL; - PIO_STACK_LOCATION nextStack = NULL; - BOOLEAN requestSent = FALSE; - - irp = WdfRequestWdmGetIrp(Request); - irpStack = IoGetCurrentIrpStackLocation(irp); - nextStack = IoGetNextIrpStackLocation(irp); - - // Set the parameters in the next stack location. - nextStack->Parameters.Scsi.Srb = irpStack->Parameters.Scsi.Srb; - nextStack->MajorFunction = IRP_MJ_SCSI; - nextStack->MinorFunction = IRP_MN_SCSI_CLASS; - - WdfRequestSetCompletionRoutine(Request, RequestDummyCompletionRoutine, NULL); - - status = RequestSend(DeviceExtension, - Request, - DeviceExtension->IoTarget, - 0, - &requestSent); - - // send the request straight down (asynchronously) - if (!requestSent) - { - // fail the request - RequestCompletion(DeviceExtension, Request, status, WdfRequestGetInformation(Request)); - } - - return; -} - - - -// -// Serial I/O Queue Event callbacks -// - -VOID -SequentialQueueEvtIoReadWrite( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t Length - ) -/*++ -Routine Description: - - validate and process read/write request. - -Arguments: - - Queue - parallel queue itself - - Request - handle to the incoming WDF Request object - - Length - read / write lenght - -Return Value: - - None - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFDEVICE device = WdfIoQueueGetDevice(Queue); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - WDF_REQUEST_PARAMETERS requestParameters; - PIRP wdmIrp = WdfRequestWdmGetIrp(Request); - PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(wdmIrp); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - - // Get the request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - if (requestParameters.Type == WdfRequestTypeRead) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "Receiving READ, Length %Ix\n", (ULONG) Length)); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "Receiving WRITE, Length %Ix\n", (ULONG) Length)); - } - - // Check if a verify is required before a READ/WRITE - if (TEST_FLAG(deviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME) && - (requestParameters.MinorFunction != CDROM_VOLUME_VERIFY_CHECKED) && - !TEST_FLAG(currentIrpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME)) - { - // DO_VERIFY_VOLUME is set for the device object, - // but this request is not itself a verify request. - // So fail this request. - RequestCompletion(deviceExtension, Request, STATUS_VERIFY_REQUIRED, 0); - } - else - { - // Since we've bypassed the verify-required tests we don't need to repeat - // them with this IRP - in particular we don't want to worry about - // hitting them at the partition 0 level if the request has come through - // a non-zero partition. - currentIrpStack->MinorFunction = CDROM_VOLUME_VERIFY_CHECKED; - - // Fail READ/WRITE requests when music is playing - if (deviceExtension->DeviceAdditionalData.PlayActive) - { - RequestCompletion(deviceExtension, Request, STATUS_DEVICE_BUSY, 0); - - return; - } - - // Fail READ/WRITE requests from non-owners if the drive is locked - if (EXCLUSIVE_MODE(cdData) && !EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) - { - RequestCompletion(deviceExtension, Request, STATUS_ACCESS_DENIED, 0); - - return; - } - - // Succeed READ/WRITE requests of length 0 - if (Length == 0) - { - // Several parts of the code turn 0 into 0xffffffff, - // so don't process a zero-length request any further. - RequestCompletion(deviceExtension, Request, STATUS_SUCCESS, Length); - - return; - } - - // If there is an unexpected write request, we want to rediscover MMC capabilities - if (!deviceExtension->DeviceAdditionalData.Mmc.WriteAllowed && - (requestParameters.Type == WdfRequestTypeWrite)) - { - // Schedule MMC capabilities update now, but perform it later in a work item - deviceExtension->DeviceAdditionalData.Mmc.UpdateState = CdromMmcUpdateRequired; - } - - // If MMC capabilities update is required, we create a separate work item to avoid blocking - // the current thread; otherwise, we initiate an async read/write in the current thread. - if (DeviceIsMmcUpdateRequired(deviceExtension->Device)) - { - deviceExtension->ReadWriteWorkItemContext.OriginalRequest = Request; - WdfWorkItemEnqueue(deviceExtension->ReadWriteWorkItem); - - status = STATUS_SUCCESS; - } - else - { - status = RequestValidateReadWrite(deviceExtension, Request, requestParameters); - - if (NT_SUCCESS(status)) - { - status = RequestHandleReadWrite(deviceExtension, Request, requestParameters); - } - } - - if (!NT_SUCCESS(status)) - { - RequestCompletion(deviceExtension, Request, status, 0); - } - } - - return; -} - - -VOID -ReadWriteWorkItemRoutine( - _In_ WDFWORKITEM WorkItem - ) -/*++ - -Routine Description: - - Work item routine for validating and initiating read and write requests. - The reason why we do that from a work item is because we may need to update MMC - capabilities before validating a read/write request and that is a sync operation. - -Arguments: - - WorkItem - WDF work item - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - WDFREQUEST readWriteRequest = NULL; - WDF_REQUEST_PARAMETERS readWriteRequestParameters; - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - deviceExtension = WdfObjectGetTypedContext(WdfWorkItemGetParentObject(WorkItem), CDROM_DEVICE_EXTENSION); - readWriteRequest = deviceExtension->ReadWriteWorkItemContext.OriginalRequest; - deviceExtension->ReadWriteWorkItemContext.OriginalRequest = NULL; - - WDF_REQUEST_PARAMETERS_INIT(&readWriteRequestParameters); - WdfRequestGetParameters(readWriteRequest, &readWriteRequestParameters); - - if (DeviceIsMmcUpdateRequired(deviceExtension->Device)) - { - // Issue command to update the drive capabilities. - // The failure of MMC update is not considered critical, so we'll - // continue to process the request even if MMC update fails. - (VOID) DeviceUpdateMmcCapabilities(deviceExtension->Device); - } - - // Now verify and process the request - if (NT_SUCCESS(status)) - { - status = RequestValidateReadWrite(deviceExtension, readWriteRequest, readWriteRequestParameters); - } - if (NT_SUCCESS(status)) - { - status = RequestHandleReadWrite(deviceExtension, readWriteRequest, readWriteRequestParameters); - } - - // Complete the request immediately on failure - if (!NT_SUCCESS(status)) - { - RequestCompletion(deviceExtension, readWriteRequest, status, 0); - } -} - - -VOID -SequentialQueueEvtIoDeviceControl( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t OutputBufferLength, - _In_ size_t InputBufferLength, - _In_ ULONG IoControlCode - ) -/*++ -Routine Description: - - validate and process IOCTL request. - -Arguments: - - Queue - sequential queue - - Request - handle to the incoming WDF Request object - -Return Value: - - None - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFDEVICE device = WdfIoQueueGetDevice(Queue); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - WDF_REQUEST_PARAMETERS requestParameters; - - UNREFERENCED_PARAMETER(OutputBufferLength); - UNREFERENCED_PARAMETER(InputBufferLength); - UNREFERENCED_PARAMETER(IoControlCode); - - // get the request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - // If the device is in exclusive mode, check whether the request is from - // the handle that locked the device - if (EXCLUSIVE_MODE(cdData) && !EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) - { - BOOLEAN isBlocked = FALSE; - - status = RequestIsIoctlBlockedByExclusiveAccess(Request, &isBlocked); - if (NT_SUCCESS(status) && isBlocked) - { - if (requestContext->SyncRequired) - { - // set the following event, so RequestSynchronizeProcessWithSerialQueue() can contintue run to process the real request. - // this function will wait for the request process finishes. - KeSetEvent(requestContext->SyncEvent, IO_CD_ROM_INCREMENT, FALSE); - } - else - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DeviceEvtIoInCallerContext: Access Denied! Device in exclusive mode.Failing Ioctl %lx\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - RequestCompletion(deviceExtension, Request, STATUS_ACCESS_DENIED, 0); - } - - return; - } - } - - if (!cdData->Mmc.WriteAllowed && - ((requestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_DISK_IS_WRITABLE) || - (requestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_DISK_VERIFY))) - { - cdData->Mmc.UpdateState = CdromMmcUpdateRequired; - } - - // check if this is a synchronized ioctl - if (requestContext->SyncRequired) - { - // set the following event, so RequestSynchronizeProcessWithSerialQueue() can contintue run to process the real request. - // this function will wait for the request process finishes. - KeSetEvent(requestContext->SyncEvent, IO_CD_ROM_INCREMENT, FALSE); - } - else - { - deviceExtension->IoctlWorkItemContext.OriginalRequest = Request; - - // all other IOCTL processing is currently processed via a - // work item running at PASSIVE_LEVEL. - WdfWorkItemEnqueue(deviceExtension->IoctlWorkItem); - } - - return; -} - - -VOID -IoctlWorkItemRoutine( - _In_ WDFWORKITEM WorkItem - ) -/*++ - -Routine Description: - - Work item routine for processing ioctl requests. - This is needed because event callbacks are called at DISPATCH_LEVEL and ioctl - requests are currently processed synchronously and not asynchronously. - -Arguments: - - WorkItem - WDF work item - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - - PAGED_CODE (); - - deviceExtension = WdfObjectGetTypedContext(WdfWorkItemGetParentObject(WorkItem), CDROM_DEVICE_EXTENSION); - - if (DeviceIsMmcUpdateRequired(deviceExtension->Device)) - { - // Issue command to update the drive capabilities. - // The failure of MMC update is not considered critical, - // so that we'll continue to process I/O even MMC update fails. - DeviceUpdateMmcCapabilities(deviceExtension->Device); - } - - RequestProcessSerializedIoctl(deviceExtension, deviceExtension->IoctlWorkItemContext.OriginalRequest); -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestProcessSerializedIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request - ) -/*++ -Routine Description: - - a dispatch routine for all functions to process IOCTLs. - -Arguments: - - DeviceExtension - device context - - Request - handle to the incoming WDF Request object - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - size_t information = 0; - WDF_REQUEST_PARAMETERS requestParameters; - BOOLEAN completeRequest = TRUE; - - PAGED_CODE (); - - // Get the Request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - NormalizeIoctl(&requestParameters); - - // process IOCTLs - switch (requestParameters.Parameters.DeviceIoControl.IoControlCode) - { - case IOCTL_CDROM_READ_TOC: - case IOCTL_CDROM_GET_LAST_SESSION: - status = RequestHandleReadTOC(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_READ_TOC_EX: - status = RequestHandleReadTocEx(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_GET_CONFIGURATION: - status = RequestHandleGetConfiguration(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_RAW_READ: - status = DeviceHandleRawRead(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DISK_GET_LENGTH_INFO: - case IOCTL_DISK_GET_DRIVE_GEOMETRY: - case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX: - case IOCTL_STORAGE_READ_CAPACITY: - status = RequestHandleGetDriveGeometry(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DISK_VERIFY: - status = RequestHandleDiskVerify(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_STORAGE_CHECK_VERIFY: - // IOCTL_STORAGE_CHECK_VERIFY2 was processed including send a Test Unit Read - // with srb flag SRB_CLASS_FLAGS_LOW_PRIORITY to port driver asynchronizelly. - // The original request was completed after TUR finishes. - // As CDROM.SYS serializes IOs need accessing device, it's not a big difference from above behavior to - // just process it in serialized manner. So I put it here and treat it as same as IOCTL_STORAGE_CHECK_VERIFY. - case IOCTL_STORAGE_CHECK_VERIFY2: - status = RequestHandleCheckVerify(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DISK_GET_DRIVE_LAYOUT: - case IOCTL_DISK_GET_DRIVE_LAYOUT_EX: - case IOCTL_DISK_GET_PARTITION_INFO: - case IOCTL_DISK_GET_PARTITION_INFO_EX: - status = RequestHandleFakePartitionInfo(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DISK_IS_WRITABLE: - // - // Even though this media is writable, the requester of this IOCTL really - // wants to know if thw media behaves like any other disk or not. This is - // so if FeatureDefectManagement and FeatureRandomWritable are current on - // the drive-represented by the FeatureDefectManagement validation schema - // - if (DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed && - (DeviceExtension->DeviceAdditionalData.Mmc.ValidationSchema == FeatureDefectManagement)) - { - status = STATUS_SUCCESS; - } - else - { - status = STATUS_MEDIA_WRITE_PROTECTED; - } - information = 0; - break; - - case IOCTL_CDROM_PLAY_AUDIO_MSF: - status = DeviceHandlePlayAudioMsf(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_READ_Q_CHANNEL: - status = DeviceHandleReadQChannel(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_PAUSE_AUDIO: - status = DeviceHandlePauseAudio(DeviceExtension, Request, &information); - break; - - case IOCTL_CDROM_RESUME_AUDIO: - status = DeviceHandleResumeAudio(DeviceExtension, Request, &information); - break; - - case IOCTL_CDROM_SEEK_AUDIO_MSF: - status = DeviceHandleSeekAudioMsf(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_STOP_AUDIO: - status = DeviceHandleStopAudio(DeviceExtension, Request, &information); - break; - - case IOCTL_CDROM_GET_VOLUME: - case IOCTL_CDROM_SET_VOLUME: - status = DeviceHandleGetSetVolume(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DVD_GET_REGION: - status = RequestHandleGetDvdRegion(DeviceExtension, Request, &information); - break; - - case IOCTL_DVD_READ_STRUCTURE: - status = DeviceHandleReadDvdStructure(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DVD_END_SESSION: - status = DeviceHandleDvdEndSession(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DVD_START_SESSION: - case IOCTL_DVD_READ_KEY: - status = DeviceHandleDvdStartSessionReadKey(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_DVD_SEND_KEY: - case IOCTL_DVD_SEND_KEY2: - status = DeviceHandleDvdSendKey(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_STORAGE_SET_READ_AHEAD: - status = DeviceHandleSetReadAhead(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_SET_SPEED: - status = DeviceHandleSetSpeed(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_READ_MEDIA_KEY_BLOCK_SIZE: - case IOCTL_AACS_READ_MEDIA_KEY_BLOCK: - status = DeviceHandleAacsReadMediaKeyBlock(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_START_SESSION: - status = DeviceHandleAacsStartSession(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_END_SESSION: - status = DeviceHandleAacsEndSession(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_SEND_CERTIFICATE: - status = DeviceHandleAacsSendCertificate(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_GET_CERTIFICATE: - status = DeviceHandleAacsGetCertificate(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_GET_CHALLENGE_KEY: - status = DeviceHandleAacsGetChallengeKey(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_SEND_CHALLENGE_KEY: - status = DeviceHandleSendChallengeKey(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_READ_VOLUME_ID: - status = DeviceHandleReadVolumeId(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_READ_SERIAL_NUMBER: - status = DeviceHandleAacsReadSerialNumber(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_READ_MEDIA_ID: - status = DeviceHandleAacsReadMediaId(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_READ_BINDING_NONCE: - status = DeviceHandleAacsReadBindingNonce(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_AACS_GENERATE_BINDING_NONCE: - status = DeviceHandleAacsGenerateBindingNonce(DeviceExtension, Request, requestParameters, &information); - break; - - case IOCTL_CDROM_ENABLE_STREAMING: - status = RequestHandleEnableStreaming(DeviceExtension, Request, &information); - break; - - case IOCTL_CDROM_SEND_OPC_INFORMATION: - status = RequestHandleSendOpcInformation(DeviceExtension, Request, &information); - break; - - case IOCTL_CDROM_GET_PERFORMANCE: - status = RequestHandleGetPerformance(DeviceExtension, Request, requestParameters, &information); - break; - - // This IOCTL is a fake one, used for MCN process sync-ed with serial queue. - case IOCTL_MCN_SYNC_FAKE_IOCTL: - status = RequestHandleMcnSyncFakeIoctl(DeviceExtension, &information); - break; - - case IOCTL_STORAGE_MEDIA_REMOVAL: - case IOCTL_STORAGE_EJECTION_CONTROL: - { - status = RequestHandleEjectionControl(DeviceExtension, Request, requestParameters, &information); - - break; - } - - case IOCTL_STORAGE_EJECT_MEDIA: - case IOCTL_STORAGE_LOAD_MEDIA: - case IOCTL_STORAGE_LOAD_MEDIA2: - { - status = RequestHandleLoadEjectMedia(DeviceExtension, Request, requestParameters, &information); - - break; - } - - case IOCTL_STORAGE_MCN_CONTROL: - { - status = RequestHandleMcnControl(DeviceExtension, Request, &information); - - break; - } - - case IOCTL_STORAGE_RESERVE: - case IOCTL_STORAGE_RELEASE: - { - status = RequestHandleReserveRelease(DeviceExtension, Request, requestParameters, &information); - - break; - } - - case IOCTL_STORAGE_PERSISTENT_RESERVE_IN: - case IOCTL_STORAGE_PERSISTENT_RESERVE_OUT: - { - status = RequestHandlePersistentReserve(DeviceExtension, Request, requestParameters, &information); - - break; - } - -#if (NTDDI_VERSION >= NTDDI_WIN8) - case IOCTL_DISK_ARE_VOLUMES_READY: - { - status = RequestHandleAreVolumesReady(DeviceExtension, Request, requestParameters, &information); - - completeRequest = FALSE; - - break; - } - - case IOCTL_VOLUME_ONLINE: - case IOCTL_VOLUME_POST_ONLINE: - { - status = RequestHandleVolumeOnline(DeviceExtension, Request, requestParameters, &information); - - break; - } -#endif - - default: - { - status = STATUS_ACCESS_DENIED; - break; - } - } // end of switch(ioctl) - - if (completeRequest) - { - RequestCompletion(DeviceExtension, Request, status, information); - } - - return status; -} - -VOID -SequentialQueueEvtCanceledOnQueue( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request - ) -/*++ -Routine Description: - - Perform cancellation when request is still in queue. - - If request is sych-ed in another thread, signal the event to let that thread be able to complete the request. - Otherwise, complete the request. - -Arguments: - - Queue - serial queue - Request - handle to the incoming WDF Request object - -Return Value: - - None - ---*/ -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - - if (requestContext->SyncRequired) - { - KeSetEvent(requestContext->SyncEvent, IO_CD_ROM_INCREMENT, FALSE); - } - else - { - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - WDFDEVICE device = WdfIoQueueGetDevice(Queue); - - deviceExtension = DeviceGetExtension(device); - - RequestCompletion(deviceExtension, Request, STATUS_CANCELLED, 0); - - } - - return; -} - - -NTSTATUS -RequestSynchronizeProcessWithSerialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ -Routine Description: - - This is the mechanism to sync a request process in original thread with serialize queue. - initialize a EVENT and put the request inot serialize queue; - waiting for serialize queue processes to this request and signal the EVENT; - call the request handler to process this request. - -Arguments: - - DeviceExtension - device context - - Request - handle to the incoming WDF Request object - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - PKEVENT bufferToFree = requestContext->SyncEvent; - - if (KeGetCurrentIrql() >= DISPATCH_LEVEL) { - // cannot block at or above DISPATCH_LEVEL - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestSynchronousProcessWithSerialQueue called at DISPATCH_LEVEL or above")); - NT_ASSERT(FALSE); - RequestCompletion(deviceExtension, Request, STATUS_INVALID_LEVEL, 0); - return STATUS_INVALID_LEVEL; - } - - // init the synchronization event - KeInitializeEvent(requestContext->SyncEvent, NotificationEvent, FALSE); - - // do we still need to do something like this? - // SET_FLAG(nextStack->Flags, SL_OVERRIDE_VERIFY_VOLUME); - - // NOTE: this mechanism relies on that KMDF will not complete request by itself. - // Doing that will cause the syncEvent not fired thus this thread will stuck. - // This should not really happen: our EvtCanceledOnQueue callbacks should be - // called even if queues are purged for some reason. The only case when these - // callbacks are not called is when a request is owned by the driver (i.e. has - // already been passed to one of the registered handlers). In this case, it is - // our responsibility to cancel such requests properly. - status = WdfDeviceEnqueueRequest(Device, Request); - - if (!NT_SUCCESS(status)) - { - // Failed to forward request! Pretend the sync event already occured, otherwise we'll hit - // an assert in RequestEvtCleanup. - KeSetEvent(requestContext->SyncEvent, IO_CD_ROM_INCREMENT, FALSE); - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - } - else - { - NTSTATUS waitStatus = STATUS_UNSUCCESSFUL; - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - BOOLEAN fCallSyncCallback = FALSE; - PIRP irp = WdfRequestWdmGetIrp(Request); - - // ok, now wait on the event - while (waitStatus != STATUS_SUCCESS) - { - waitStatus = KeWaitForSingleObject(requestContext->SyncEvent, Executive, KernelMode, TRUE, NULL); - if (waitStatus == STATUS_SUCCESS) // must check equality -- STATUS_ALERTED is success code - { - // do nothing - } - else if (waitStatus != STATUS_ALERTED) - { - // do nothing - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_IOCTL, - "Request %p on device object %p had a non-alert, non-success result from wait (%!HRESULT!)\n", - Request, Device, waitStatus)); - NT_ASSERT(FALSE); - } - else if (PsIsThreadTerminating(PsGetCurrentThread())) - { - // the thread was alerted and is terminating, so cancel the irp - // this will cause EvtIoCanceledOnQueue to be called, which will signal the event, - // so we will get out of the while loop and eventually complete the request. - if (IoCancelIrp(irp)) - { - // cancellation routine was called - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "Sychronize Ioctl: request %p cancelled from device %p\n", - Request, Device)); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "Sychronize Ioctl: request %p could not be cancelled from device %p\n", - Request, Device)); - } - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "SPURIOUS ALERT waiting for Request %p on device %p (%!STATUS!)\n", - Request, Device, status)); - } - } // end of wait loop on the event - - // because we've waited an unknown amount of time, should check - // the cancelled flag to immediately fail the irp as appropriate - if (WdfRequestIsCanceled(Request)) - { - // the request was cancelled, thus we should always stop - // processing here if possible. - status = STATUS_CANCELLED; - RequestCompletion(deviceExtension, Request, status, 0); - } - else if (EXCLUSIVE_MODE(cdData) && !EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) - { - WDF_REQUEST_PARAMETERS requestParameters; - BOOLEAN isBlocked = FALSE; - - // get the request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - status = RequestIsIoctlBlockedByExclusiveAccess(Request, &isBlocked); - if (isBlocked) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "Access Denied! Device in exclusive mode.Failing Ioctl %lx\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - RequestCompletion(deviceExtension, Request, STATUS_ACCESS_DENIED, 0); - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "Ioctl %lx not blocked by cdrom being in exclusive mode\n", - requestParameters.Parameters.DeviceIoControl.IoControlCode)); - fCallSyncCallback = TRUE; - } - } - else - { - fCallSyncCallback = TRUE; - } - - if (fCallSyncCallback) - { - // Synchronization completed successfully. Call the requested routine - status = requestContext->SyncCallback(Device, Request); - } - } - - // The next SequentialQueue evt routine will not be triggered until the current request is completed. - - // clean up the request context setting. - FREE_POOL(bufferToFree); - - return status; -} - -NTSTATUS -RequestIsIoctlBlockedByExclusiveAccess( - _In_ WDFREQUEST Request, - _Out_ PBOOLEAN IsBlocked - ) -/*++ -Routine Description: - - Check if the IOCTL request should be blocked or not according to - the exclusive lock stat. - -Arguments: - - Request - handle to the incoming WDF Request object - -Return Value: - - NTSTATUS - - IsBlocked - TRUE (be blocked); FALSE (not blocked) - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG ioctlCode = 0; - ULONG baseCode = 0; - WDF_REQUEST_PARAMETERS requestParameters; - - // Get the Request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - // check and initialize parameter - if (IsBlocked == NULL) - { - //This is an internal function and this parameter must be supplied. - NT_ASSERT(FALSE); - - return STATUS_INVALID_PARAMETER; - } - else - { - *IsBlocked = FALSE; - } - - // check if this is an IOCTL - if ((requestParameters.Type == WdfRequestTypeDeviceControl) || - (requestParameters.Type == WdfRequestTypeDeviceControlInternal)) - { - // - // Allow minimum set of commands that are required for the disk manager - // to show the CD device, while in exclusive mode. - // Note: These commands should not generate any requests to the device, - // and thus must be handled directly in StartIO during exclusive - // access (except for the exclusive owner, of course). - // - ioctlCode = requestParameters.Parameters.DeviceIoControl.IoControlCode; - baseCode = DEVICE_TYPE_FROM_CTL_CODE(ioctlCode); - - if (ioctlCode == IOCTL_SCSI_GET_ADDRESS || - ioctlCode == IOCTL_STORAGE_GET_HOTPLUG_INFO || - ioctlCode == IOCTL_STORAGE_GET_DEVICE_NUMBER || - ioctlCode == IOCTL_STORAGE_GET_MEDIA_TYPES_EX || - ioctlCode == IOCTL_CDROM_EXCLUSIVE_ACCESS || - ioctlCode == IOCTL_CDROM_GET_INQUIRY_DATA - ) - { - *IsBlocked = FALSE; - } - - // - // Handle IOCTL_STORAGE_QUERY_PROPERTY special because: - // (1) PropertyExistsQuery should not generate device i/o - // (2) Queries for StorageDeviceProperty and StorageAdapterDescriptor - // will return cache'd data - else if (ioctlCode == IOCTL_STORAGE_QUERY_PROPERTY) - { - PSTORAGE_PROPERTY_QUERY query = NULL; - status = WdfRequestRetrieveInputBuffer(Request, - requestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&query, - NULL); - - if (NT_SUCCESS(status)) - { - if (query != NULL) - { - if (query->QueryType == PropertyExistsQuery) - { - *IsBlocked = FALSE; - } - else if ((query->QueryType == PropertyStandardQuery) && - ((query->PropertyId == StorageDeviceProperty) || - (query->PropertyId == StorageAdapterProperty))) - { - *IsBlocked = FALSE; - } - } - } - } - - // Return TRUE for unknown IOCTLs with STORAGE bases - else if (baseCode == IOCTL_SCSI_BASE || - baseCode == IOCTL_DISK_BASE || - baseCode == IOCTL_CDROM_BASE || - baseCode == IOCTL_STORAGE_BASE || - baseCode == IOCTL_DVD_BASE ) - { - *IsBlocked = TRUE; - } - } - else - { - // this should only be called with an IOCTL - NT_ASSERT(FALSE); - - status = STATUS_INVALID_PARAMETER; - } - - return status; -} - -BOOLEAN -DeviceIsMmcUpdateRequired( - _In_ WDFDEVICE Device - ) -/*++ -Routine Description: - - Check if the device needs to update its MMC information. - -Arguments: - - Device - device to be checked. - -Return Value: - - TRUE (require update); FALSE (not require update) - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - - if ((cdData->Mmc.IsMmc) && - (cdData->Mmc.UpdateState == CdromMmcUpdateRequired)) - { - return TRUE; - } - else - { - // no update required: just proceed - return FALSE; - } -} - -VOID -RequestEvtCleanup( - _In_ WDFOBJECT Request - ) -/*++ -Routine Description: - - Request cleanup callback. - -Arguments: - - Request - request to clean up. - -Return Value: - - None - ---*/ -{ - WDFREQUEST request = (WDFREQUEST)Request; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(request); - - if (requestContext->SyncRequired) - { - // the event should have been signaled, just check that - NT_ASSERT(KeReadStateEvent(requestContext->SyncEvent) != 0); - } -} - diff --git a/storage/class/cdrom/src/cdrom.h b/storage/class/cdrom/src/cdrom.h deleted file mode 100644 index 472e240e7..000000000 --- a/storage/class/cdrom/src/cdrom.h +++ /dev/null @@ -1,1609 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - cdrom.h - -Abstract: - - Main header file for cdrom.sys. - This contains structure and function declarations as well as constant values. - -Author: - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#ifndef __CDROM_H__ -#define __CDROM_H__ - -#pragma warning(push) -#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union -#pragma warning(disable:4214) // nonstandard extension used : bit field types other than int -#pragma warning(disable:4152) // nonstandard extension, function/data pointer conversion in expression - -#include "wdf.h" -#include "ntddmmc.h" -#include "ntddcdvd.h" -#include "ntddcdrm.h" -#include "ntdddisk.h" -#include "ntddtape.h" -#include "ntddscsi.h" -#include "ntddvol.h" -#include "specstrings.h" -#include "cdromp.h" - -// Set component ID for DbgPrintEx calls -#ifndef DEBUG_COMP_ID - #define DEBUG_COMP_ID DPFLTR_CDROM_ID -#endif - -// Include initguid.h so GUID_CONSOLE_DISPLAY_STATE is declared -#include - -// Include header file and setup GUID for tracing -#include -#define WPP_GUID_CDROM (A4196372, C3C4, 42d5, 87BF, 7EDB2E9BCC27) -#ifndef WPP_CONTROL_GUIDS - #define WPP_CONTROL_GUIDS WPP_CONTROL_GUIDS_NORMAL_FLAGS(WPP_GUID_CDROM) -#endif - -// This prototype is needed because, although NTIFS.H is now shipping with -// the WDK, can't include both it and the other headers we already use. -_IRQL_requires_max_(DISPATCH_LEVEL) -NTKERNELAPI -BOOLEAN -PsIsThreadTerminating( - _In_ PETHREAD Thread - ); - -// -// -extern CDROM_SCAN_FOR_SPECIAL_INFO CdromHackItems[]; - -#define CDROM_HACK_DEC_RRD (0x00000001) -#define CDROM_HACK_FUJITSU_FMCD_10x (0x00000002) -//#define CDROM_HACK_HITACHI_1750 (0x00000004) -- obsolete -#define CDROM_HACK_HITACHI_GD_2000 (0x00000008) -#define CDROM_HACK_TOSHIBA_SD_W1101 (0x00000010) -//#define CDROM_HACK_TOSHIBA_XM_3xx (0x00000020) -- obsolete -//#define CDROM_HACK_NEC_CDDA (0x00000040) -- obsolete -//#define CDROM_HACK_PLEXTOR_CDDA (0x00000080) -- obsolete -#define CDROM_HACK_BAD_GET_CONFIG_SUPPORT (0x00000100) -//#define CDROM_HACK_FORCE_READ_CD_DETECTION (0x00000200) -- obsolete -//#define CDROM_HACK_READ_CD_SUPPORTED (0x00000400) -- obsolete -#define CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG (0x00000800) -#define CDROM_HACK_BAD_VENDOR_PROFILES (0x00001000) -#define CDROM_HACK_MSFT_VIRTUAL_ODD (0x00002000) -#define CDROM_HACK_LOCKED_PAGES (0x80000000) // not a valid flag to save - -#define CDROM_HACK_VALID_FLAGS (0x00003fff) -#define CDROM_HACK_INVALID_FLAGS (~CDROM_HACK_VALID_FLAGS) - - -// A 64k buffer to be written takes the following amount of time: -// 1x CD == 75 sectors/sec == 0.4266667 seconds == 4266667 100ns units -// 4x CD == 300 sectors/sec == 0.1066667 seconds == 1066667 100ns units -// 10x CD == 300 sectors/sec == 0.0426667 seconds == 426667 100ns units -// 1x DVD == 676 sectors/sec == 0.0473373 seconds == 473373 100ns units -// 16x DVD == 10,816 sectors/sec == 0.0029586 seconds == 29586 100ns units -// 1x HDDVD == 2,230 sectors/sec == 0.0143498 seconds == 143498 100ns units -#define WRITE_RETRY_DELAY_CD_1x ((LONGLONG)4266667) -#define WRITE_RETRY_DELAY_CD_4x ((LONGLONG)1066667) -#define WRITE_RETRY_DELAY_CD_10x ((LONGLONG) 426667) -#define WRITE_RETRY_DELAY_DVD_1x ((LONGLONG) 473373) -#define WRITE_RETRY_DELAY_DVD_4x ((LONGLONG) 118343) -#define WRITE_RETRY_DELAY_DVD_16x ((LONGLONG) 29586) -#define WRITE_RETRY_DELAY_HDDVD_1x ((LONGLONG) 143498) - -// -#define MAXIMUM_RETRIES 4 - -#define CDROM_GET_CONFIGURATION_TIMEOUT (0x4) -#define CDROM_READ_DISC_INFORMATION_TIMEOUT (0x4) -#define CDROM_TEST_UNIT_READY_TIMEOUT (0x14) -#define CDROM_GET_PERFORMANCE_TIMEOUT (0x14) -#define CDROM_READ_CAPACITY_TIMEOUT (0x14) - -#define START_UNIT_TIMEOUT (60 * 4) - -// Used to detect the loss of the autorun irp. -#define MEDIA_CHANGE_TIMEOUT_TIME 300 - -// Indicates whether is is safe to send StartUnit commands -// to this device. It will only be off for some removeable devices. -#define DEV_SAFE_START_UNIT 0x00000004 - -// Indicates that the device is connected to a backup power supply -// and hence write-through and synch cache requests may be ignored -#define DEV_POWER_PROTECTED 0x00000010 - -// The following CDROM_SPECIAL_ flags are set in ScanForSpecialFlags -// in the Device Extension - -// Never Spin Up/Down the drive (may not handle properly) -#define CDROM_SPECIAL_DISABLE_SPIN_DOWN 0x00000001 -//#define CDROM_SPECIAL_DISABLE_SPIN_UP 0x00000002 - -// Don't bother to lock the queue when powering down -// (used mostly to send a quick stop to a cdrom to abort audio playback) -//#define CDROM_SPECIAL_NO_QUEUE_LOCK 0x00000008 - -// Disable write cache due to known bugs -#define CDROM_SPECIAL_DISABLE_WRITE_CACHE 0x00000010 - -// Used to indicate that this request shouldn't invoke any power type operations -// like spinning up the drive. - -#define SRB_CLASS_FLAGS_LOW_PRIORITY 0x10000000 - -// Used to indicate that an SRB is the result of a paging operation. -#define SRB_CLASS_FLAGS_PAGING 0x40000000 - -typedef struct _ERROR_RECOVERY_DATA { - MODE_PARAMETER_HEADER Header; - MODE_PARAMETER_BLOCK BlockDescriptor; - MODE_READ_RECOVERY_PAGE ReadRecoveryPage; -} ERROR_RECOVERY_DATA, *PERROR_RECOVERY_DATA; - -// A compile-time check of the 30,000 limit not overflowing ULONG size... -// Note that it is not expected that a release (FRE) driver will normally -// have such a large history, instead using the compression function. -#define CDROM_INTERPRET_SENSE_INFO2_MAXIMUM_HISTORY_COUNT 30000 -C_ASSERT( (MAXULONG - sizeof(SRB_HISTORY)) / 30000 >= sizeof(SRB_HISTORY_ITEM) ); - -// Intended to reuse a defined IOCTL code that not seen in Optical stack and does not require input parameter. -// This fake IOCTL is used used for MCN process sync-ed with serial queue. -#define IOCTL_MCN_SYNC_FAKE_IOCTL IOCTL_DISK_UPDATE_DRIVE_SIZE - -/*++//////////////////////////////////////////////////////////////////////////// - -PCDROM_ERROR_HANDLER() - -Routine Description: - - This routine is a callback into the driver to handle errors. The queue - shall not be unfrozen when this error handler is called, even though the - SRB flags may mark the queue as having been frozen due to this SRB. - -Irql: - - This routine will be called at KIRQL <= DISPATCH_LEVEL - -Arguments: - - DeviceObject is the device object the error occurred on. - - Srb is the Srb that was being processed when the error occurred. - - Status may be overwritten by the routine if it decides that the error - was benign, or otherwise wishes to change the returned status code - for this command - - Retry may be overwritten to specify that this command should or should - not be retried (if the callee supports retrying commands) - -Return Value: - - status - ---*/ -struct _CDROM_DEVICE_EXTENSION; // *PCDROM_DEVICE_EXTENSION; -typedef struct _CDROM_DEVICE_EXTENSION - CDROM_DEVICE_EXTENSION, - *PCDROM_DEVICE_EXTENSION; - -typedef -VOID -(*PCDROM_ERROR_HANDLER) ( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Inout_ PNTSTATUS Status, - _Inout_ PBOOLEAN Retry - ); - -// CdRom driver extension -typedef struct _CDROM_DRIVER_EXTENSION { - ULONG Version; - PDRIVER_OBJECT DriverObject; - ULONG Flags; - -} CDROM_DRIVER_EXTENSION, *PCDROM_DRIVER_EXTENSION; - -#define CDROM_FLAG_WINPE_MODE 0x00000001 - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CDROM_DRIVER_EXTENSION, DriverGetExtension) - -#define CdromMmcUpdateComplete 0 -#define CdromMmcUpdateRequired 1 -#define CdromMmcUpdateStarted 2 - -typedef struct _CDROM_MMC_EXTENSION { - - BOOLEAN IsMmc; // mmc device - BOOLEAN IsAACS; // aacs compatible device - BOOLEAN IsWriter; // the drive is a writer or not - BOOLEAN WriteAllowed; // currently allow write request or not - - BOOLEAN IsCssDvd; // A CSS protected DVD or CPPM-protected DVDAudio media in Drive. - BOOLEAN StreamingReadSupported; // the drive supports streaming for reads - BOOLEAN StreamingWriteSupported; // the drive supports streaming for writes - - LONG UpdateState; - - // The feature number defines the level and form of - // validation that needs to be performed on Io requests - FEATURE_NUMBER ValidationSchema; - ULONG Blocking; - - SCSI_REQUEST_BLOCK CapabilitiesSrb; - PIRP CapabilitiesIrp; - WDFREQUEST CapabilitiesRequest; - SENSE_DATA CapabilitiesSenseData; - _Field_size_bytes_(CapabilitiesBufferSize) - PGET_CONFIGURATION_HEADER CapabilitiesBuffer; - ULONG CapabilitiesBufferSize; - PMDL CapabilitiesMdl; - - BOOLEAN ReadCdC2Pointers; - BOOLEAN ReadCdSubCode; - -} CDROM_MMC_EXTENSION, *PCDROM_MMC_EXTENSION; - -typedef struct _CDROM_SCRATCH_READ_WRITE_CONTEXT { - - // Information about the data that we need to read/write - ULONG PacketsCount; - ULONG TransferedBytes; - ULONG EntireXferLen; - ULONG MaxLength; - PUCHAR DataBuffer; - LARGE_INTEGER StartingOffset; - BOOLEAN IsRead; - - // A pointer to the SRB history item to be filled upon completion - PSRB_HISTORY_ITEM SrbHistoryItem; - -} CDROM_SCRATCH_READ_WRITE_CONTEXT, *PCDROM_SCRATCH_READ_WRITE_CONTEXT; - -// Many commands get double-buffered. Since the max -// transfer size is typically 64k, most of these requests -// can be handled with a single pre-allocated buffer. -typedef struct _CDROM_SCRATCH_CONTEXT { - - _Field_range_(4*1024, 64*1024) ULONG ScratchBufferSize; // 0x1000..0x10000 (4k..64k) - _Field_size_bytes_(ScratchBufferSize) PVOID ScratchBuffer; // used to get data for clients - - PMDL ScratchBufferMdl; // used to get data for clients - - WDFREQUEST ScratchRequest; - PSCSI_REQUEST_BLOCK ScratchSrb; - PSENSE_DATA ScratchSense; - PSRB_HISTORY ScratchHistory; - - // This MDL is used to performed the request whose required transfer size is bigger than adaptor's max. - PMDL PartialMdl; - BOOLEAN PartialMdlIsBuilt; - - // For debugging, set/clear this field when using the scratch buffer/request - PVOID ScratchInUse; - PCSTR ScratchInUseFileName; - ULONG ScratchInUseLineNumber; - - // Stuff for asynchronous retrying of the transfer. - ULONG NumRetries; - - // Read Write context - CDROM_SCRATCH_READ_WRITE_CONTEXT ScratchReadWriteContext; - -} CDROM_SCRATCH_CONTEXT, *PCDROM_SCRATCH_CONTEXT; - -// Context structure for the IOCTL work item -typedef struct _CDROM_IOCTL_CONTEXT { - - WDFREQUEST OriginalRequest; - -} CDROM_IOCTL_CONTEXT, *PCDROM_IOCTL_CONTEXT; - -// Context structure for the read/write work item -typedef struct _CDROM_READ_WRITE_CONTEXT { - - WDFREQUEST OriginalRequest; - -} CDROM_READ_WRITE_CONTEXT, *PCDROM_READ_WRITE_CONTEXT; - -typedef struct _CDROM_DATA { - - CDROM_MMC_EXTENSION Mmc; - - // hack flags for ScanForSpecial routines - ULONG_PTR HackFlags; - - // the error handling routines need to be per-device, not per-driver.... - PCDROM_ERROR_HANDLER ErrorHandler; - - // Indicates whether an audio play operation is currently being performed. - // Only thing this does is prevent reads and toc requests while playing audio. - BOOLEAN PlayActive; - - // indicate we need to pick a default dvd region for the user if we can - ULONG PickDvdRegion; - - // The well known name link for this device. - UNICODE_STRING WellKnownName; - - // We need to distinguish between the two... - ULONG MaxPageAlignedTransferBytes; - ULONG MaxUnalignedTransferBytes; - - // Indicates that this is a DEC RRD cdrom. - // This drive requires software to fix responses from the faulty firmware - BOOLEAN IsDecRrd; - - // Storage for the error recovery page. This is used as the method - // to switch block sizes for some drive-specific error recovery routines. - // ERROR_RECOVERY_DATA recoveryData; //obsolete along with error process for TOSHIBA_XM_3xx - - // Indicates that the device is in exclusive mode and only - // the requests from the exclusive owner will be processed. - WDFFILEOBJECT ExclusiveOwner; - - // Caller name of the owner, if the device is in exclusive mode. - UCHAR CallerName[CDROM_EXCLUSIVE_CALLER_LENGTH]; - - // Indicates that the device speed should be set to - // default value on the next media change. - BOOLEAN RestoreDefaults; - - // How long to wait between retries if a READ/WRITE irp - // gets a LWIP (2/4/7, 2/4/8)? - LONGLONG ReadWriteRetryDelay100nsUnits; - - // Cached Device Type information. Maybe FILE_DEVICE_CD_ROM or FILE_DEVICE_DVD - // CommonExtension.DevInfo->DeviceType maybe FILE_DEVICE_CD_ROM when this field is FILE_DEVICE_DVD - DEVICE_TYPE DriveDeviceType; - - _Field_size_bytes_(CachedInquiryDataByteCount) - PINQUIRYDATA CachedInquiryData; - ULONG CachedInquiryDataByteCount; - -} CDROM_DATA, *PCDROM_DATA; - - -typedef struct _CDROM_POWER_OPTIONS { - ULONG PowerDown : 1; - ULONG LockQueue : 1; - ULONG HandleSpinDown : 1; - ULONG HandleSpinUp : 1; - ULONG Reserved : 27; -} CDROM_POWER_OPTIONS, *PCDROM_POWER_OPTIONS; - -// this is a private enum, but must be kept here -// to properly compile size of CDROM_DEVICE_EXTENSION -typedef enum { - PowerDownDeviceInitial, - PowerDownDeviceLocked, - PowerDownDeviceQuiesced, - PowerDownDeviceFlushed, - PowerDownDeviceStopped, - PowerDownDeviceOff, - PowerDownDeviceUnlocked -} CDROM_POWER_DOWN_STATE; - -// this is a private enum, but must be kept here -// to properly compile size of CDROM_DEVICE_EXTENSION -typedef enum { - PowerUpDeviceInitial, - PowerUpDeviceLocked, - PowerUpDeviceOn, - PowerUpDeviceStarted, - PowerUpDeviceUnlocked -} CDROM_POWER_UP_STATE; - -// this is a private structure, but must be kept here -// to properly compile size of CDROM_DEVICE_EXTENSION -typedef struct _CDROM_POWER_CONTEXT { - - BOOLEAN InUse; - - LARGE_INTEGER StartTime; - LARGE_INTEGER Step1CompleteTime; // for SYNC CACHE in power down case - LARGE_INTEGER CompleteTime; - - union { - CDROM_POWER_DOWN_STATE PowerDown; - CDROM_POWER_UP_STATE PowerUp; // currently not used. - } PowerChangeState; - - CDROM_POWER_OPTIONS Options; - - WDFREQUEST PowerRequest; - - SCSI_REQUEST_BLOCK Srb; - SENSE_DATA SenseData; - - ULONG RetryCount; - LONGLONG RetryIntervalIn100ns; - -} CDROM_POWER_CONTEXT, *PCDROM_POWER_CONTEXT; - -// device extension structure -typedef struct _CDROM_DEVICE_EXTENSION { - - // Version control field - ULONG Version; - - // structure size - ULONG Size; - - // the structure is fully ready to use - BOOLEAN IsInitialized; - - // the device is active - BOOLEAN IsActive; - - // the device is surprise removed. - BOOLEAN SurpriseRemoved; - - // Back pointer to device object - WDFDEVICE Device; - - // Save IoTarget here, do not retrieve anytime. - WDFIOTARGET IoTarget; - - // Additional WDF queue for serial I/O processing - WDFQUEUE SerialIOQueue; - - // A separate queue for all the create file requests in sync with device - // removal - WDFQUEUE CreateQueue; - - //Main timer of driver, will do Mcn work. (once per second) - WDFTIMER MainTimer; - - // Pointer to the initialization data for this driver. This is more - // efficient than constantly getting the driver extension. - PCDROM_DRIVER_EXTENSION DriverExtension; - - // WDM device information - PDEVICE_OBJECT DeviceObject; - - // Pointer to the physical device object we attached to - PDEVICE_OBJECT LowerPdo; - - // FILE_DEVICE_CD_ROM -- 2 - DEVICE_TYPE DeviceType; - - // The name of the object - UNICODE_STRING DeviceName; - - // System device number - ULONG DeviceNumber; - - // Values for the flags are below. - USHORT DeviceFlags; - - // Flags for special behaviour required by different hardware, - // such as never spinning down or disabling advanced features such as write cache - ULONG ScanForSpecialFlags; - - // Add default Srb Flags. - ULONG SrbFlags; - - // Request timeout in seconds; - ULONG TimeOutValue; - - //The SCSI address of the device. - SCSI_ADDRESS ScsiAddress; - - // Buffer for drive parameters returned in IO device control. - DISK_GEOMETRY DiskGeometry; - - // Log2 of sector size - UCHAR SectorShift; - - // Length of partition in bytes - LARGE_INTEGER PartitionLength; - - // Number of bytes before start of partition - LARGE_INTEGER StartingOffset; - - // Interface name string returned by IoRegisterDeviceInterface. - UNICODE_STRING MountedDeviceInterfaceName; - - // Device capabilities - PSTORAGE_DEVICE_DESCRIPTOR DeviceDescriptor; - - // SCSI port driver capabilities - PSTORAGE_ADAPTER_DESCRIPTOR AdapterDescriptor; - - // Device power properties - PDEVICE_POWER_DESCRIPTOR PowerDescriptor; - - // Request Sense Buffer - PSENSE_DATA SenseData; - - // Total number of SCSI protocol errors on the device. - ULONG ErrorCount; - - // Lock count for removable media. - LONG LockCount; - LONG ProtectedLockCount; - LONG InternalLockCount; - - KEVENT EjectSynchronizationEvent; - WDFWAITLOCK EjectSynchronizationLock; - - // Indicates that the necessary data structures for media change - // detection have been initialized. - PMEDIA_CHANGE_DETECTION_INFO MediaChangeDetectionInfo; - - // Contains necessary data structures for ZPODD support. - PZERO_POWER_ODD_INFO ZeroPowerODDInfo; - - // File system context. Used for kernel-mode requests to disable autorun. - FILE_OBJECT_CONTEXT KernelModeMcnContext; - - // Count of media changes. This field is only valid for the root partition - // (ie. if PhysicalDevice == NULL). - ULONG MediaChangeCount; - - // Storage for a release queue request. - WDFSPINLOCK ReleaseQueueSpinLock; - WDFREQUEST ReleaseQueueRequest; - SCSI_REQUEST_BLOCK ReleaseQueueSrb; - WDFMEMORY ReleaseQueueInputMemory; //This is a wrapper of ReleaseQueueSrb - BOOLEAN ReleaseQueueNeeded; - BOOLEAN ReleaseQueueInProgress; - - // Context structure for power operations. Since we can only have - // one D irp at any time in the stack we don't need to worry about - // allocating multiple of these structures. - CDROM_POWER_CONTEXT PowerContext; - BOOLEAN PowerDownInProgress; - -#if (NTDDI_VERSION >= NTDDI_WIN8) - BOOLEAN IsVolumeOnlinePending; - WDFQUEUE ManualVolumeReadyQueue; -#endif - - // Lock for Shutdown/Flush operations that need to stop/start the queue - WDFWAITLOCK ShutdownFlushWaitLock; - - // device specific data area - CDROM_DATA DeviceAdditionalData; - - // scratch buffer related fields. - CDROM_SCRATCH_CONTEXT ScratchContext; - - // Hold new private data that only classpnp should modify - // in this structure. - PCDROM_PRIVATE_FDO_DATA PrivateFdoData; - - // Work item for async reads and writes and its context - WDFWORKITEM ReadWriteWorkItem; - CDROM_READ_WRITE_CONTEXT ReadWriteWorkItemContext; - - // Auxiliary WDF object for processing ioctl requests that need to go down - // to the port driver. - WDFWORKITEM IoctlWorkItem; - CDROM_IOCTL_CONTEXT IoctlWorkItemContext; - -} CDROM_DEVICE_EXTENSION, *PCDROM_DEVICE_EXTENSION; - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CDROM_DEVICE_EXTENSION, DeviceGetExtension) - -// a type definition for functions to be called after synchronization -typedef -NTSTATUS -SYNC_HANDLER ( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -typedef SYNC_HANDLER *PSYNC_HANDLER ; - -typedef struct _CDROM_REQUEST_CONTEXT { - PCDROM_DEVICE_EXTENSION DeviceExtension; - - WDFREQUEST OriginalRequest; - - LARGE_INTEGER TimeReceived; - LARGE_INTEGER TimeSentDownFirstTime; - LARGE_INTEGER TimeSentDownLasttTime; - - - ULONG RetriedCount; - - // Used to send down an incoming IOCTL in the original context - BOOLEAN SyncRequired; - PKEVENT SyncEvent; - PSYNC_HANDLER SyncCallback; - - // - // Used for READ/WRITE requests. - // The reason why kernel primitives are used for the spinlock and - // the timer instead of WDF object is there is a race condition - // between the cancel callback and the timer routine. - // Because of this, the timer and the spin lock need to be associated - // per request rather than using shared memory in the device extension - // and it is possible for the WDF object initialization to fail whereas - // the kernel primitives initialize provided memory. Initializing the - // kernel primitives will never fail. Since READ/WRITE is a critical - // code path, it is not desired for READs or WRITEs to fail due to - // an allocation failure that can be avoided and because it is not - // uncommon to see a failure during a READ or WRITE that may not - // occur upon a retry. - // - KSPIN_LOCK ReadWriteCancelSpinLock; - KTIMER ReadWriteTimer; - KDPC ReadWriteDpc; - BOOLEAN ReadWriteIsCompleted; - BOOLEAN ReadWriteRetryInitialized; - -} CDROM_REQUEST_CONTEXT, *PCDROM_REQUEST_CONTEXT; - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CDROM_REQUEST_CONTEXT, RequestGetContext) - -// Define context structure for asynchronous completions. -typedef struct _COMPLETION_CONTEXT { - WDFDEVICE Device; - SCSI_REQUEST_BLOCK Srb; -} COMPLETION_CONTEXT, *PCOMPLETION_CONTEXT; - - -// -#define SCSI_CDROM_TIMEOUT 10 -#define SCSI_CHANGER_BONUS_TIMEOUT 10 - -// -// This value is used as the upper limit for all commands CDROM sends down -// to device, unless the default timeout value is overriden by registry value -// "TimeOutValue" and it is larger than this value. -// -#define SCSI_CDROM_OPC_TIMEOUT 260 - -#define HITACHI_MODE_DATA_SIZE 12 -#define MODE_DATA_SIZE 64 - -#define RAW_SECTOR_SIZE 2352 -#define COOKED_SECTOR_SIZE 2048 - -#define CDROM_SRB_LIST_SIZE 4 - -#define PLAY_ACTIVE(x) (x->DeviceAdditionalData.PlayActive) - -#define MSF_TO_LBA(Minutes,Seconds,Frames) \ - (ULONG)((60 * 75 * (Minutes)) + (75 * (Seconds)) + ((Frames) - 150)) - -// Sector types for READ_CD - -#define ANY_SECTOR 0 -#define CD_DA_SECTOR 1 -#define YELLOW_MODE1_SECTOR 2 -#define YELLOW_MODE2_SECTOR 3 -#define FORM2_MODE1_SECTOR 4 -#define FORM2_MODE2_SECTOR 5 - -#define MAX_COPY_PROTECT_AGID 4 - -#ifdef ExAllocatePool - #undef ExAllocatePool - #define ExAllocatePool #assert(FALSE) -#endif - -// memory allocation tags -// Sc?? - Mass storage driver tags -// ScC - Class driver misc allocations -// ScC? - CdRom - -#define CDROM_TAG_AUTORUN_DISABLE 'ACcS' // "ScCA" - Autorun disable functionality -#define CDROM_TAG_MEDIA_CHANGE_DETECTION 'aCcS' // "ScCa" - Media change detection - -#define CDROM_TAG_SCRATCH 'BCcS' // "ScSB" - Scratch buffer (usually 64k) -#define CDROM_TAG_GET_CONFIG 'CCcS' // "ScCC" - Ioctl GET_CONFIGURATION -#define CDROM_TAG_COMPLETION_CONTEXT 'cCcS' // "ScCc" - Context of completion routine -#define CDROM_TAG_DESCRIPTOR 'DCcS' // "ScCD" - Adaptor & Device descriptor buffer -#define CDROM_TAG_DISC_INFO 'dCcS' // "ScCd" - Disc information -#define CDROM_TAG_SYNC_EVENT 'eCcS' // "ScCe" - Request sync event -#define CDROM_TAG_FEATURE 'FCcS' // "ScCF" - Feature descriptor -#define CDROM_TAG_GESN 'GCcS' // "ScCG" - GESN buffer -#define CDROM_TAG_SENSE_INFO 'ICcS' // "ScCI" - Sense info buffers -#define CDROM_TAG_INQUIRY 'iCcS' // "ScCi" - Cached inquiry buffer -#define CDROM_TAG_MODE_DATA 'MCcS' // "ScCM" - Mode data buffer -#define CDROM_TAG_STREAM 'OCCS' // "SCCO" - Set stream buffer -#define CDROM_TAG_NOTIFICATION 'oCcS' // "ScCo" - Device Notification buffer -#define CDROM_TAG_PLAY_ACTIVE 'pCcS' // "ScCp" - Play active checks -#define CDROM_TAG_REGISTRY 'rCcS' // "ScCr" - Registry string -#define CDROM_TAG_SRB 'SCcS' // "ScCS" - Srb allocation -#define CDROM_TAG_STRINGS 'sCcS' // "ScCs" - Assorted string data -#define CDROM_TAG_UPDATE_CAP 'UCcS' // "ScCU" - Update capacity path -#define CDROM_TAG_ZERO_POWER_ODD 'ZCcS' // "ScCZ" - Zero Power ODD - -#define DVD_TAG_READ_KEY 'uCcS' // "ScCu" - Read buffer for dvd key -#define DVD_TAG_RPC2_CHECK 'VCcS' // "ScCV" - Read buffer for dvd/rpc2 check -#define DVD_TAG_DVD_REGION 'vCcS' // "ScCv" - Read buffer for rpc2 check -#define DVD_TAG_SECURITY 'XCcS' // "ScCX" - Security descriptor - - -// registry keys and data entry names. -#define CDROM_SUBKEY_NAME (L"CdRom") // store new settings here -#define CDROM_READ_CD_NAME (L"ReadCD") // READ_CD support previously detected -#define CDROM_NON_MMC_DRIVE_NAME (L"NonMmc") // MMC commands hang -#define CDROM_TYPE_ONE_GET_CONFIG_NAME (L"NoTypeOneGetConfig") // Type One Get Config commands not supported -#define CDROM_NON_MMC_VENDOR_SPECIFIC_PROFILE (L"NonMmcVendorSpecificProfile") // GET_CONFIG returns vendor specific header - // profiles that are not per spec (length divisible by 4) -#define DVD_DEFAULT_REGION (L"DefaultDvdRegion") // this is init. by the dvd class installer -#define DVD_MAX_REGION 8 - -// AACS defines -#define AACS_MKB_PACK_SIZE 0x8000 // does not include header - -//enumeration of device interfaces need to be registered. -typedef enum { - CdRomDeviceInterface = 0, // CdRomClassGuid - MountedDeviceInterface // MOUNTDEV_MOUNTED_DEVICE_GUID -} CDROM_DEVICE_INTERFACES, *PCDROM_DEVICE_INTERFACES; - - -typedef -VOID -(*PCDROM_SCAN_FOR_SPECIAL_HANDLER) ( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG_PTR Data - ); - -// Rountines Definition - -#define FREE_POOL(_PoolPtr) \ - if (_PoolPtr != NULL) { \ - ExFreePool(_PoolPtr); \ - _PoolPtr = NULL; \ - } - -#define EXCLUSIVE_MODE(_CdData) (_CdData->ExclusiveOwner != NULL) -#define EXCLUSIVE_OWNER(_CdData, _FileObject) (_CdData->ExclusiveOwner == _FileObject) - -#define IS_SCSIOP_READ(opCode) \ - ((opCode == SCSIOP_READ6) || \ - (opCode == SCSIOP_READ) || \ - (opCode == SCSIOP_READ12) || \ - (opCode == SCSIOP_READ16)) - -#define IS_SCSIOP_WRITE(opCode) \ - ((opCode == SCSIOP_WRITE6) || \ - (opCode == SCSIOP_WRITE) || \ - (opCode == SCSIOP_WRITE12) || \ - (opCode == SCSIOP_WRITE16)) - -#define IS_SCSIOP_READWRITE(opCode) (IS_SCSIOP_READ(opCode) || IS_SCSIOP_WRITE(opCode)) - -// Bit Flag Macros -#define SET_FLAG(Flags, Bit) ((Flags) |= (Bit)) -#define CLEAR_FLAG(Flags, Bit) ((Flags) &= ~(Bit)) -#define TEST_FLAG(Flags, Bit) (((Flags) & (Bit)) != 0) - -__inline -BOOLEAN -ValidChar(UCHAR Ch) -{ - if (((Ch >= '0') && (Ch <= '9')) || - (((Ch|0x20) >= 'a') && ((Ch|0x20) <= 'z')) || - (strchr(" .,:;_-", Ch) != NULL)) - { - return TRUE; - } - return FALSE; -} - -// could be #define, but this allows typechecking -__inline -BOOLEAN -PORT_ALLOCATED_SENSE( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb - ) -{ - UNREFERENCED_PARAMETER(DeviceExtension); - return (BOOLEAN)((TEST_FLAG(Srb->SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE) && - TEST_FLAG(Srb->SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER)) - ); -} - -__inline -VOID -FREE_PORT_ALLOCATED_SENSE_BUFFER( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb - ) -{ -#ifndef DEBUG - UNREFERENCED_PARAMETER(DeviceExtension); -#endif - NT_ASSERT(TEST_FLAG(Srb->SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE)); - NT_ASSERT(TEST_FLAG(Srb->SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER)); - NT_ASSERT(Srb->SenseInfoBuffer != DeviceExtension->SenseData); - - ExFreePool(Srb->SenseInfoBuffer); - Srb->SenseInfoBuffer = NULL; - Srb->SenseInfoBufferLength = 0; - CLEAR_FLAG(Srb->SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER); - return; -} - -// Standard driver entry function -DRIVER_INITIALIZE DriverEntry; - -// Driver Event callbacks -EVT_WDF_DRIVER_DEVICE_ADD DriverEvtDeviceAdd; - -EVT_WDF_OBJECT_CONTEXT_CLEANUP DriverEvtCleanup; - -// Device Event callbacks - -EVT_WDF_OBJECT_CONTEXT_CLEANUP DeviceEvtCleanup; - -EVT_WDF_FILE_CLOSE DeviceEvtFileClose; - -EVT_WDF_IO_IN_CALLER_CONTEXT DeviceEvtIoInCallerContext; - -EVT_WDF_DEVICE_SELF_MANAGED_IO_INIT DeviceEvtSelfManagedIoInit; - -EVT_WDF_DEVICE_SELF_MANAGED_IO_CLEANUP DeviceEvtSelfManagedIoCleanup; - -EVT_WDF_DEVICE_D0_ENTRY DeviceEvtD0Entry; - -EVT_WDF_DEVICE_D0_EXIT DeviceEvtD0Exit; - -EVT_WDF_DEVICE_SURPRISE_REMOVAL DeviceEvtSurpriseRemoval; - -// Create Queue Event callbacks - -EVT_WDF_IO_QUEUE_IO_DEFAULT CreateQueueEvtIoDefault; - -// Sequential Queue Event callbacks - -// We do not use KMDF annotation for the following function, because it handles -// both read and write requests and there is no single annotation for that. -VOID -SequentialQueueEvtIoReadWrite( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t Length - ); - -EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL SequentialQueueEvtIoDeviceControl; - -EVT_WDF_IO_QUEUE_IO_CANCELED_ON_QUEUE SequentialQueueEvtCanceledOnQueue; - -// Miscellaneous request callbacks - -EVT_WDF_OBJECT_CONTEXT_CLEANUP RequestEvtCleanup; - -EVT_WDFDEVICE_WDM_IRP_PREPROCESS RequestProcessShutdownFlush; - -EVT_WDFDEVICE_WDM_IRP_PREPROCESS RequestProcessSetPower; - - -// helper functions - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceClaimRelease( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN Release - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceReleaseMcnResources( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveDescriptor( - _In_ WDFDEVICE Device, - _In_ PSTORAGE_PROPERTY_ID PropertyId, - _Outptr_ PSTORAGE_DESCRIPTOR_HEADER* Descriptor - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceRetrieveHackFlagsFromRegistry( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceHackFlagsScan( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG_PTR Data - ); - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -StringsAreMatched( - _In_opt_z_ PCHAR StringToMatch, - _In_z_ PCHAR TargetString - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceGetParameter( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ PWSTR SubkeyName, - _In_ PWSTR ParameterName, - _Inout_ PULONG ParameterValue // also default value - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSetParameter( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_z_ PWSTR SubkeyName, - _In_ PWSTR ParameterName, - _In_ ULONG ParameterValue - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -ULONG -DeviceGetTimeOutValueFromRegistry(); - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScanForSpecialHandler( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG_PTR HackFlags - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSendSrbSynchronously( - _In_ WDFDEVICE Device, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_opt_ PVOID BufferAddress, - _In_ ULONG BufferLength, - _In_ BOOLEAN WriteToDevice, - _In_opt_ WDFREQUEST OriginalRequest - ); - -BOOLEAN -RequestSenseInfoInterpret( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, // get IRP MJ code, IoControlCode from it (or attached original request) - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ ULONG RetriedCount, - _Out_ NTSTATUS* Status, - _Out_opt_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ); - -VOID -RequestSetReceivedTime( - _In_ WDFREQUEST Request - ); - -VOID -RequestSetSentTime( - _In_ WDFREQUEST Request - ); - -VOID -RequestClearSendTime( - _In_ WDFREQUEST Request - ); - -BOOLEAN -RequestSenseInfoInterpretForScratchBuffer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG RetriedCount, - _Out_ NTSTATUS* Status, - _Out_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ); - - -VOID -DeviceSendNotification( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ const GUID* Guid, - _In_ ULONG ExtraDataSize, - _In_opt_ PVOID ExtraData - ); - -VOID -DeviceSendStartUnit( - _In_ WDFDEVICE Device - ); - -EVT_WDF_REQUEST_COMPLETION_ROUTINE DeviceAsynchronousCompletion; - -VOID -DeviceReleaseQueue( - _In_ WDFDEVICE Device - ); - -EVT_WDF_REQUEST_COMPLETION_ROUTINE DeviceReleaseQueueCompletion; - -VOID -DevicePerfIncrementErrorCount( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceCacheDeviceInquiryData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceCacheGetConfigurationData( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(APC_LEVEL) -PVOID -DeviceFindFeaturePage( - _In_reads_bytes_(Length) PGET_CONFIGURATION_HEADER FeatureBuffer, - _In_ ULONG const Length, - _In_ FEATURE_NUMBER const Feature - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DevicePrintAllFeaturePages( - _In_reads_bytes_(Usable) PGET_CONFIGURATION_HEADER Buffer, - _In_ ULONG const Usable - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceSetRawReadInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -MediaReadCapacity( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -MediaReadCapacityDataInterpret( - _In_ WDFDEVICE Device, - _In_ PREAD_CAPACITY_DATA ReadCapacityBuffer - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitReleaseQueueContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitPowerContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceCreateWellKnownName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitializeDvd( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DevicePickDvdRegion( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRegisterInterface( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ CDROM_DEVICE_INTERFACES InterfaceType - ); - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -DeviceSendPowerDownProcessRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ PFN_WDF_REQUEST_COMPLETION_ROUTINE CompletionRoutine, - _In_opt_ WDFCONTEXT Context - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceScanForSpecial( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ CDROM_SCAN_FOR_SPECIAL_INFO DeviceList[], - _In_ PCDROM_SCAN_FOR_SPECIAL_HANDLER Function - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeHotplugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -NTSTATUS -DeviceErrorHandlerForMmc( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Inout_ PNTSTATUS Status, - _Inout_ PBOOLEAN Retry - ); - -NTSTATUS -DeviceErrorHandlerForHitachiGD2000( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Inout_ PNTSTATUS Status, - _Inout_ PBOOLEAN Retry - ); - -EVT_WDF_WORKITEM DeviceRestoreDefaultSpeed; - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -VOID -DeviceSetMediaChangeStateEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ MEDIA_CHANGE_DETECTION_STATE NewState, - _Inout_opt_ PMEDIA_CHANGE_DETECTION_STATE OldState - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceSendDelayedMediaChangeNotifications( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -NTSTATUS -RequestSynchronizeProcessWithSerialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceCleanupProtectedLocks( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PFILE_OBJECT_CONTEXT FileObjectContext - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceCleanupDisableMcn( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PFILE_OBJECT_CONTEXT FileObjectContext - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceUnlockExclusive( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFFILEOBJECT FileObject, - _In_ BOOLEAN IgnorePreviousMediaChanges - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestProcessSerializedIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request - ); - -NTSTATUS -RequestIsIoctlBlockedByExclusiveAccess( - _In_ WDFREQUEST Request, - _Out_ PBOOLEAN IsBlocked - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceSendRequestSynchronously( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ BOOLEAN RequestFormated - ); - -VOID -DeviceSendIoctlAsynchronously( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_ PDEVICE_OBJECT TargetDeviceObject - ); - -IO_COMPLETION_ROUTINE RequestAsynchronousIrpCompletion; - -// MMC Update functions - -BOOLEAN -DeviceIsMmcUpdateRequired( - _In_ WDFDEVICE Device - ); - -// Helper functions - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceEnableMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Inout_ PFILE_OBJECT_CONTEXT FileObjectContext, - _In_ BOOLEAN IgnorePreviousMediaChanges - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceDisableMediaChangeDetection( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Inout_ PFILE_OBJECT_CONTEXT FileObjectContext - ); - -NTSTATUS -RequestSetContextFields( - _In_ WDFREQUEST Request, - _In_ PSYNC_HANDLER Handler - ); - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -DeviceIsPlayActive( - _In_ WDFDEVICE Device - ); - -NTSTATUS -RequestDuidGetDeviceIdProperty( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestDuidGetDeviceProperty( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -ULONG -DeviceRetrieveModeSenseUsingScratch( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_reads_bytes_(Length) PCHAR ModeSenseBuffer, - _In_ ULONG Length, - _In_ UCHAR PageCode, - _In_ UCHAR PageControl - ); - -_IRQL_requires_max_(APC_LEVEL) -PVOID -ModeSenseFindSpecificPage( - _In_reads_bytes_(Length) PCHAR ModeSenseBuffer, - _In_ size_t Length, - _In_ UCHAR PageMode, - _In_ BOOLEAN Use6Byte - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -PerformEjectionControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ MEDIA_LOCK_TYPE LockType, - _In_ BOOLEAN Lock - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceDisableMainTimer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceEnableMainTimer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -EVT_WDF_TIMER DeviceMainTimerTickHandler; - -VOID -RequestSetupMcnSyncIrp( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestSetupMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN UseGesn - ); - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -RequestSendMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -RequestPostWorkMcnRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextReuseRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextBeginUse( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextEndUse( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -POWER_SETTING_CALLBACK DevicePowerSettingCallback; - -// Zero Power ODD functions - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeZPODD( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceReleaseZPODDResources( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -NTSTATUS -DeviceZPODDGetPowerupReason( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PSTORAGE_IDLE_POWERUP_REASON PowerupReason - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceZPODDIsInHomePosition( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceMarkActive( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN IsActive, - _In_ BOOLEAN SetIdleTimeout - ); - -// common routines for specific IOCTL process - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DvdStartSessionReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_opt_ WDFREQUEST OriginalRequest, - _In_opt_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ReadDvdStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ReadQChannel( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _Out_ size_t * DataLength - ); - - -#ifndef SIZEOF_ARRAY - #define SIZEOF_ARRAY(ar) (sizeof(ar)/sizeof((ar)[0])) -#endif // !defined(SIZEOF_ARRAY) - - -// 100us to seconds -#define UNIT_100NS_PER_SECOND (10*1000*1000) -#define SECONDS_TO_100NS_UNITS(x) (((LONGLONG)x) * UNIT_100NS_PER_SECOND) - -// -// Bit Flag Macros -// -#define SET_FLAG(Flags, Bit) ((Flags) |= (Bit)) -#define CLEAR_FLAG(Flags, Bit) ((Flags) &= ~(Bit)) -#define TEST_FLAG(Flags, Bit) (((Flags) & (Bit)) != 0) - -// -// neat little hacks to count number of bits set efficiently -// -__inline ULONG CountOfSetBitsUChar(UCHAR _X) - { ULONG i = 0; while (_X) { _X &= _X - 1; i++; } return i; } -__inline ULONG CountOfSetBitsULong(ULONG _X) - { ULONG i = 0; while (_X) { _X &= _X - 1; i++; } return i; } -__inline ULONG CountOfSetBitsULong32(ULONG32 _X) - { ULONG i = 0; while (_X) { _X &= _X - 1; i++; } return i; } -__inline ULONG CountOfSetBitsULong64(ULONG64 _X) - { ULONG i = 0; while (_X) { _X &= _X - 1; i++; } return i; } -__inline ULONG CountOfSetBitsUlongPtr(ULONG_PTR _X) - { ULONG i = 0; while (_X) { _X &= _X - 1; i++; } return i; } - - -__inline -BOOLEAN -IsVolumeMounted( - _In_ PDEVICE_OBJECT DeviceObject - ) -{ -#pragma prefast(push) -#pragma prefast(disable: 28175, "there is no other way to check if there is volume mounted") - return (DeviceObject->Vpb != NULL) && - ((DeviceObject->Vpb->Flags & VPB_MOUNTED) != 0); -#pragma prefast(pop) -} - - -__inline _Ret_range_(0,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -ConvertSectorsPerSecondTo100nsUnitsFor64kWrite( - _In_range_(1,0xFFFFFFFF) ULONG SectorsPerSecond // zero would cause divide-by-zero - ) -{ - // 64k write - // ---------------- == time per 64k write - // sectors/second - // - // (32 / N) == seconds - // (32 / N) * (1,000,000,000) == nanoseconds - // (32 / N) * (1,000,000,000) / 100 == 100ns increments - // (32 * 10,000,000) / N == 100ns increments - // - // 320,000,000 / N == 100ns increments - // And this is safe to run in kernel-mode (no floats) - // - - // this assert ensures that we _never_ can return a value - // larger than the maximum allowed. - C_ASSERT(320000000 < MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS); - - return 320000000 / SectorsPerSecond; -} - -__inline -UCHAR -RequestGetCurrentStackLocationFlags( - _In_ WDFREQUEST Request - ) -{ - PIRP irp = NULL; - PIO_STACK_LOCATION currentStack = NULL; - - irp = WdfRequestWdmGetIrp(Request); - currentStack = IoGetCurrentIrpStackLocation(irp); - - return currentStack->Flags; -} - -__inline -ULONG -TimeOutValueGetCapValue( - _In_ ULONG TimeOutValue, - _In_ ULONG Times - ) -{ - ULONG value = 0; - - if (TimeOutValue > SCSI_CDROM_OPC_TIMEOUT) - { - // if time out value is specified by user in registry, and is - // bigger than OPC time out, it should be big enough - value = TimeOutValue; - } - else - { - // otherwise, OPC time out value should be the upper limit - value = min(TimeOutValue * Times, SCSI_CDROM_OPC_TIMEOUT); - } - - return value; -} - -VOID -RequestCompletion( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ NTSTATUS Status, - _In_ ULONG_PTR Information - ); - -NTSTATUS -RequestSend( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET IoTarget, - _In_ ULONG Flags, - _Out_opt_ PBOOLEAN RequestSent - ); - -EVT_WDF_REQUEST_COMPLETION_ROUTINE RequestDummyCompletionRoutine; - -VOID -RequestProcessInternalDeviceControl( - _In_ WDFREQUEST Request, - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -EVT_WDF_WORKITEM IoctlWorkItemRoutine; - -EVT_WDF_WORKITEM ReadWriteWorkItemRoutine; - -#pragma warning(pop) // un-sets any local warning changes - -#endif // __CDROMP_H__ - - diff --git a/storage/class/cdrom/src/cdrom.inf b/storage/class/cdrom/src/cdrom.inf deleted file mode 100644 index 472453070..000000000 Binary files a/storage/class/cdrom/src/cdrom.inf and /dev/null differ diff --git a/storage/class/cdrom/src/cdrom.rc b/storage/class/cdrom/src/cdrom.rc deleted file mode 100644 index 688f91427..000000000 --- a/storage/class/cdrom/src/cdrom.rc +++ /dev/null @@ -1,23 +0,0 @@ -//+------------------------------------------------------------------------- -// -// Microsoft Windows -// -// Copyright (C) Microsoft Corporation, 1996 - 1999 -// -// File: scsicdrm.rc -// -//-------------------------------------------------------------------------- - -#include - -#include - -#define VER_FILETYPE VFT_DRV -#define VER_FILESUBTYPE VFT2_DRV_SYSTEM -#define VER_FILEDESCRIPTION_STR "SCSI CD-ROM Driver" -#define VER_INTERNALNAME_STR "cdrom.sys" -#define VER_ORIGINALFILENAME_STR "cdrom.sys" -#define VER_LANGNEUTRAL - -#include "common.ver" - diff --git a/storage/class/cdrom/src/cdrom.vcxproj b/storage/class/cdrom/src/cdrom.vcxproj deleted file mode 100644 index 689c9716a..000000000 --- a/storage/class/cdrom/src/cdrom.vcxproj +++ /dev/null @@ -1,168 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {9DB6E759-C294-4E18-9013-82FD8F3DD5E6} - $(MSBuildProjectName) - 1 - false - Debug - Win32 - {E2CAD978-F695-4642-9CD1-65CB518B0B80} - - - - Windows10 - False - Universal - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Universal - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - False - Universal - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Universal - KMDF - WindowsKernelModeDriver10.0 - Driver - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - TracePrint((LEVEL,FLAGS,MSG,...)) - - - $(InfArch) - true - .\$(IntDir)\cdrom.inf - - - true - true - TracePrint((LEVEL,FLAGS,MSG,...)) - - - - cdrom - - - cdrom - - - cdrom - - - cdrom - - - - true - Level4 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib - - - - - true - Level4 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/storage/class/cdrom/src/cdrom.vcxproj.Filters b/storage/class/cdrom/src/cdrom.vcxproj.Filters deleted file mode 100644 index 57895acd6..000000000 --- a/storage/class/cdrom/src/cdrom.vcxproj.Filters +++ /dev/null @@ -1,72 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {1BE21169-AD4D-4A1B-AACD-6310066933B0} - - - h;hpp;hxx;hm;inl;inc;xsd - {9B550B9E-2283-4A6B-BAC8-52E0EAB6DD60} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {B3F87DD6-6AE2-4B7C-9C6F-6BC20F347A17} - - - inf;inv;inx;mof;mc; - {4F903A62-C105-4A95-AB1A-2EB0F3AE253F} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Driver Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/storage/class/cdrom/src/cdromp.h b/storage/class/cdrom/src/cdromp.h deleted file mode 100644 index 2fdf7118c..000000000 --- a/storage/class/cdrom/src/cdromp.h +++ /dev/null @@ -1,383 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - cdromp.h - -Abstract: - - Private header file for cdrom.sys modules. This contains private - structure and function declarations as well as constant values which do - not need to be exported. - -Author: - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#ifndef __CDROMP_H__ -#define __CDROMP_H__ - - -#include -#include -#include -#include -#include - -/* - * IA64 requires 8-byte alignment for pointers, but the IA64 NT kernel expects 16-byte alignment - */ -#ifdef _WIN64 - #define PTRALIGN DECLSPEC_ALIGN(16) -#else - #define PTRALIGN -#endif - -// NOTE: Start with a smaller 100 second maximum, due to current assert in CLASSPNP -// 0x0000 00C9'2A69 C000 (864,000,000,000) is 24 hours in 100ns units -// 0x0000 0000'3B9A CA00 ( 1,000,000,000) is 100 seconds in 100ns units -#define MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS (0x3B9ACA00) - -// structures to simplify matching devices, ids, and hacks required for -// these ids. -typedef struct _CDROM_SCAN_FOR_SPECIAL_INFO { - // - // * NULL pointers indicates that no match is required. - // * empty string will only match an empty string. non-existant strings - // in the device descriptor are considered empty strings for this match. - // (ie. "" will only match "") - // * all other strings will do partial matches, based upon - // string provided (ie. "hi" will match "hitazen" and "higazui") - // * array must end with all three PCHARs being set to NULL. - // - - PCHAR VendorId; - PCHAR ProductId; - PCHAR ProductRevision; - - // - // marked as a ULONG_PTR to allow use as either a ptr to a data block - // or 32 bits worth of flags. (64 bits on 64 bit systems) no longer a - // const so that it may be dynamically built. - // - - ULONG_PTR Data; - -} CDROM_SCAN_FOR_SPECIAL_INFO, *PCDROM_SCAN_FOR_SPECIAL_INFO; - -// Define the various states that media can be in for autorun. -typedef enum _MEDIA_CHANGE_DETECTION_STATE { - MediaUnknown, - MediaPresent, - MediaNotPresent, - MediaUnavailable // e.g. cd-r media undergoing burn -} MEDIA_CHANGE_DETECTION_STATE, *PMEDIA_CHANGE_DETECTION_STATE; - - -/*++//////////////////////////////////////////////////////////////////////////// - - This structure defines the history kept for a given transfer packet. - It includes a srb status/sense data structure that is always either valid - or zero-filled for the full 18 bytes, time sent/completed, and how long - the retry delay was requested to be. - ---*/ -typedef struct _SRB_HISTORY_ITEM { - LARGE_INTEGER TickCountSent; // 0x00..0x07 - LARGE_INTEGER TickCountCompleted; // 0x08..0x0F - ULONG MillisecondsDelayOnRetry; // 0x10..0x13 - SENSE_DATA NormalizedSenseData; // 0x14..0x25 (0x12 bytes) - UCHAR SrbStatus; // 0x26 - UCHAR ClassDriverUse; // 0x27 -- one byte free (alignment) -} SRB_HISTORY_ITEM, *PSRB_HISTORY_ITEM; - -typedef struct _SRB_HISTORY { - ULONG_PTR ClassDriverUse[4]; // for the class driver to use as they please - _Field_range_(1,30000) - ULONG TotalHistoryCount; - _Field_range_(0,TotalHistoryCount) - ULONG UsedHistoryCount; - _Field_size_part_(TotalHistoryCount, UsedHistoryCount) - SRB_HISTORY_ITEM History[1]; -} SRB_HISTORY, *PSRB_HISTORY; - -extern CDROM_SCAN_FOR_SPECIAL_INFO CdRomBadItems[]; - -/*++////////////////////////////////////////////////////////////////////////////*/ - -// legacy registry key and values. -#define CLASSP_REG_SUBKEY_NAME (L"Classpnp") - -#define CLASSP_REG_HACK_VALUE_NAME (L"HackMask") -#define CLASSP_REG_MMC_DETECTION_VALUE_NAME (L"MMCDetectionState") -#define CLASSP_REG_WRITE_CACHE_VALUE_NAME (L"WriteCacheEnableOverride") -#define CLASSP_REG_PERF_RESTORE_VALUE_NAME (L"RestorePerfAtCount") -#define CLASSP_REG_REMOVAL_POLICY_VALUE_NAME (L"UserRemovalPolicy") -#define WINPE_REG_KEY_NAME (L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\MiniNT") - -#define CLASS_PERF_RESTORE_MINIMUM (0x10) -#define CLASS_ERROR_LEVEL_1 (0x4) -#define CLASS_ERROR_LEVEL_2 (0x8) - -#define FDO_HACK_CANNOT_LOCK_MEDIA (0x00000001) -#define FDO_HACK_GESN_IS_BAD (0x00000002) -#define FDO_HACK_NO_RESERVE6 (0x00000008) -#define FDO_HACK_GESN_IGNORE_OPCHANGE (0x00000010) -#define FDO_HACK_NO_STREAMING (0x00000020) -#define FDO_HACK_NO_ASYNCHRONOUS_NOTIFICATION (0x00000040) - -#define FDO_HACK_VALID_FLAGS (0x0000007F) -#define FDO_HACK_INVALID_FLAGS (~FDO_HACK_VALID_FLAGS) - -/* - * Lots of retries of synchronized SCSI commands that devices may not - * even support really slows down the system (especially while booting). - * (Even GetDriveCapacity may be failed on purpose if an external disk is powered off). - * If a disk cannot return a small initialization buffer at startup - * in two attempts (with delay interval) then we cannot expect it to return - * data consistently with four retries. - * So don't set the retry counts as high here as for data SRBs. - * - * If we find that these requests are failing consecutively, - * despite the retry interval, on otherwise reliable media, - * then we should either increase the retry interval for - * that failure or (by all means) increase these retry counts as appropriate. - */ -//#define NUM_LOCKMEDIAREMOVAL_RETRIES 1 -//#define NUM_MODESENSE_RETRIES 1 -//#define NUM_DRIVECAPACITY_RETRIES 1 - -/* - * We retry failed I/O requests at 1-second intervals. - * In the case of a failure due to bus reset, we want to make sure that we retry after the allowable - * reset time. For SCSI, the allowable reset time is 5 seconds. ScsiPort queues requests during - * a bus reset, which should cause us to retry after the reset is over; but the requests queued in - * the miniport are failed all the way back to us immediately. In any event, in order to make - * extra sure that our retries span the allowable reset time, we should retry more than 5 times. - */ -//#define NUM_IO_RETRIES 8 - -#define CDROM_VOLUME_VERIFY_CHECKED 0x34 - -#define CDROM_TAG_PRIVATE_DATA 'CPcS' - -typedef struct _MEDIA_CHANGE_DETECTION_INFO { - - // Use AN if supported so that we don't need to poll for media change notifications. - BOOLEAN AsynchronousNotificationSupported; - - // If AN is turned on and we received an AN signal when the device is exclusively locked, - // we should take a note and send down a GESN when the lock is lifted, since otherwise - // we will lose the signal. Even worse, some ODD models will signal the event again next - // time a SYNC CACHE is sent down, and processing the event in that arbitrary timing may - // cause unexpected behaviors. - BOOLEAN ANSignalPendingDueToExclusiveLock; - - // Mutex to synchronize enable/disable requests and media state changes - KMUTEX MediaChangeMutex; - - // For request erialization use. - // This irp is used in timer callback routine, will be sent to the device itself. - // so that the sequentail queue will get request wrapped on this irp. After doing - // the real work, this irp will be completed to indicate it's ok to send the next - // MCN request. - PIRP MediaChangeSyncIrp; - - // The last known state of the media (present, not present, unknown). - // Protected by MediaChangeMutex. - MEDIA_CHANGE_DETECTION_STATE LastKnownMediaDetectionState; - - // The last state of the media (present, not present, unknown) reported to apps - // via notifications. Protected by MediaChangeMutex - MEDIA_CHANGE_DETECTION_STATE LastReportedMediaDetectionState; - - // This is a count of how many time MCD has been disabled. if it is - // set to zero, then we'll poll the device for MCN events with the - // then-current method (ie. TEST UNIT READY or GESN). this is - // protected by MediaChangeMutex - LONG MediaChangeDetectionDisableCount; - - // recent changes allowed instant retries of the MCN REQUEST. Since this - // could cause an infinite loop, keep a count of how many times we've - // retried immediately so that we can catch if the count exceeds an - // arbitrary limit. - LONG MediaChangeRetryCount; - - // use GESN if it's available - struct { - BOOLEAN Supported; - BOOLEAN HackEventMask; - UCHAR EventMask; - UCHAR NoChangeEventMask; - PUCHAR Buffer; - PMDL Mdl; - ULONG BufferSize; - } Gesn; - - // If this value is one, then the REQUEST is currently in use. - // If this value is zero, then the REQUEST is available. - // Use InterlockedCompareExchange() to set from "available" to "in use". - // ASSERT that InterlockedCompareExchange() showed previous value of - // "in use" when changing back to "available" state. - // This also implicitly protects the MediaChangeSrb and SenseBuffer - // - // This protect is needed in the polling case since the timer is fired asynchronous - // to our sequential I/O queues, and when the timer is fired, our Sync Irp could be - // still using the MediaChangeRequest. However, if AN is used, then each interrupt - // will cause us to queue a request, so interrupts are serialized, and within the - // handling of each request, we already sequentially use the MediaChangeRequest if - // we need retries. We still use it in case of AN to be consistent with polling, but - // if in the future we remove polling altogether, then we don't need this field anymore. - LONG MediaChangeRequestInUse; - - // Pointer to the REQUEST to be used for media change detection. - // protected by Interlocked MediaChangeRequestInUse - WDFREQUEST MediaChangeRequest; - - // The srb for the media change detection. - // protected by Interlocked MediaChangeIrpInUse - SCSI_REQUEST_BLOCK MediaChangeSrb; - PUCHAR SenseBuffer; - ULONG SrbFlags; - - // Handle to the display state notification registration. - PVOID DisplayStateCallbackHandle; - -} MEDIA_CHANGE_DETECTION_INFO, *PMEDIA_CHANGE_DETECTION_INFO; - -#define DELAY_TIME_TO_ENTER_ZERO_POWER_IN_MS (60 * 1000) -#define DELAY_TIME_TO_ENTER_AOAC_IDLE_POWER_IN_MS (10 * 1000) -#define BECOMING_READY_RETRY_COUNT (15) -#define BECOMING_READY_RETRY_INTERNVAL_IN_100NS (2 * 1000 * 1000) - -typedef struct _ZERO_POWER_ODD_INFO { - - UCHAR LoadingMechanism; // From Removable Medium Feature Descriptor - UCHAR Load; // From Removable Medium Feature Descriptor - - D3COLD_SUPPORT_INTERFACE D3ColdInterface; // D3Cold interface from ACPI - - BOOLEAN Reserved; // Reserved - BOOLEAN InZeroPowerState; // Is device currently in Zero Power State - BOOLEAN RetryFirstCommand; // First command after power resume should be retried - BOOLEAN MonitorStartStopUnit; // If 1. drawer 2. soft eject 3. no media 4. Immed=0, - // we will not receive any GESN events, and so we should - // monitor the command to get notified - ULONG BecomingReadyRetryCount; // How many times we should retry for becoming ready - - UCHAR SenseKey; // sense code from TUR to check media & tray status - UCHAR AdditionalSenseCode; // sense code from TUR to check media & tray status - UCHAR AdditionalSenseCodeQualifier; // sense code from TUR to check media & tray status - - PGET_CONFIGURATION_HEADER GetConfigurationBuffer; // Cached Get Configuration response from device - ULONG GetConfigurationBufferSize; // Size of the above buffer - -} ZERO_POWER_ODD_INFO, *PZERO_POWER_ODD_INFO; - -typedef enum { - SimpleMediaLock, - SecureMediaLock, - InternalMediaLock -} MEDIA_LOCK_TYPE, *PMEDIA_LOCK_TYPE; - - -typedef enum _CDROM_DETECTION_STATE { - CdromDetectionUnknown = 0, - CdromDetectionUnsupported = 1, - CdromDetectionSupported = 2 -} CDROM_DETECTION_STATE, *PCDROM_DETECTION_STATE; - - -typedef struct _CDROM_ERROR_LOG_DATA { - LARGE_INTEGER TickCount; // Offset 0x00 - ULONG PortNumber; // Offset 0x08 - - UCHAR ErrorPaging : 1; // Offset 0x0c - UCHAR ErrorRetried : 1; - UCHAR ErrorUnhandled : 1; - UCHAR ErrorReserved : 5; - - UCHAR Reserved[3]; - - SCSI_REQUEST_BLOCK Srb; // Offset 0x10 - - // We define the SenseData as the default length. - // Since the sense data returned by the port driver may be longer, - // SenseData must be at the end of this structure. - // For our internal error log, we only log the default length. - SENSE_DATA SenseData; // Offset 0x50 for x86 (or 0x68 for ia64) (ULONG32 Alignment required!) -} CDROM_ERROR_LOG_DATA, *PCDROM_ERROR_LOG_DATA; - - -#define NUM_ERROR_LOG_ENTRIES 16 - -// -// add to the front of this structure to help prevent illegal -// snooping by other utilities. -// -typedef struct _CDROM_PRIVATE_FDO_DATA { - - // this private structure allows us to - // dynamically re-enable the perf benefits - // lost due to transient error conditions. - // in w2k, a reboot was required. :( - struct { - ULONG OriginalSrbFlags; - ULONG SuccessfulIO; - ULONG ReEnableThreshhold; // 0 means never - } Perf; - - ULONG_PTR HackFlags; - - STORAGE_HOTPLUG_INFO HotplugInfo; - - BOOLEAN TimerStarted; - BOOLEAN LoggedTURFailureSinceLastIO; - BOOLEAN LoggedSYNCFailure; - - // not use WDFSPINLOCK to avoid exposing private object creation - // in initialization code. (cdrom.sys was in WDK example) - KSPIN_LOCK SpinLock; - - // Circular array of timestamped logs of errors that occurred on this device. - ULONG ErrorLogNextIndex; - CDROM_ERROR_LOG_DATA ErrorLogs[NUM_ERROR_LOG_ENTRIES]; - -}CDROM_PRIVATE_FDO_DATA, *PCDROM_PRIVATE_FDO_DATA; - -// -// this is a private structure, but must be kept here -// to properly compile size of FUNCTIONAL_DEVICE_EXTENSION -// -typedef struct _FILE_OBJECT_CONTEXT { - WDFFILEOBJECT FileObject; - WDFDEVICE DeviceObject; - ULONG LockCount; - ULONG McnDisableCount; - BOOLEAN EnforceStreamingRead; - BOOLEAN EnforceStreamingWrite; -} FILE_OBJECT_CONTEXT, *PFILE_OBJECT_CONTEXT; - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FILE_OBJECT_CONTEXT, FileObjectGetContext) - - -#define NOT_READY_RETRY_INTERVAL 10 -#define MODE_PAGE_DATA_SIZE 192 - -// -// per session device -// -#define INVALID_SESSION ((ULONG)-1) - -#endif // __CDROMP_H__ diff --git a/storage/class/cdrom/src/common.c b/storage/class/cdrom/src/common.c deleted file mode 100644 index 13312ac67..000000000 --- a/storage/class/cdrom/src/common.c +++ /dev/null @@ -1,3872 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - common.c - -Abstract: - - shared private routines for cdrom.sys - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - - -#include "ntddk.h" -#include "ntddstor.h" -#include "ntstrsafe.h" - -#include "cdrom.h" -#include "scratch.h" - - -#ifdef DEBUG_USE_WPP -#include "common.tmh" -#endif - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceGetParameter) -#pragma alloc_text(PAGE, DeviceSetParameter) -#pragma alloc_text(PAGE, DeviceSendSrbSynchronously) -#pragma alloc_text(PAGE, DevicePickDvdRegion) -#pragma alloc_text(PAGE, StringsAreMatched) -#pragma alloc_text(PAGE, PerformEjectionControl) -#pragma alloc_text(PAGE, DeviceFindFeaturePage) -#pragma alloc_text(PAGE, DevicePrintAllFeaturePages) -#pragma alloc_text(PAGE, DeviceRegisterInterface) -#pragma alloc_text(PAGE, DeviceRestoreDefaultSpeed) -#pragma alloc_text(PAGE, DeviceSendRequestSynchronously) -#pragma alloc_text(PAGE, MediaReadCapacity) -#pragma alloc_text(PAGE, MediaReadCapacityDataInterpret) -#pragma alloc_text(PAGE, DeviceRetrieveModeSenseUsingScratch) -#pragma alloc_text(PAGE, ModeSenseFindSpecificPage) -#pragma alloc_text(PAGE, DeviceUnlockExclusive) - -#endif - -LPCSTR LockTypeStrings[] = {"Simple", - "Secure", - "Internal" - }; - -VOID -RequestSetReceivedTime( - _In_ WDFREQUEST Request - ) -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - LARGE_INTEGER temp; - - KeQueryTickCount(&temp); - - requestContext->TimeReceived = temp; - - return; -} - -VOID -RequestSetSentTime( - _In_ WDFREQUEST Request - ) -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - LARGE_INTEGER temp; - - KeQueryTickCount(&temp); - - if (requestContext->TimeSentDownFirstTime.QuadPart == 0) - { - requestContext->TimeSentDownFirstTime = temp; - } - - requestContext->TimeSentDownLasttTime = temp; - - if (requestContext->OriginalRequest != NULL) - { - PCDROM_REQUEST_CONTEXT originalRequestContext = RequestGetContext(requestContext->OriginalRequest); - - if (originalRequestContext->TimeSentDownFirstTime.QuadPart == 0) - { - originalRequestContext->TimeSentDownFirstTime = temp; - } - - originalRequestContext->TimeSentDownLasttTime = temp; - } - - return; -} - -VOID -RequestClearSendTime( - _In_ WDFREQUEST Request - ) -/* -Routine Description: - - This function is used to clean SentTime fields in reusable request context. - -Arguments: - Request - - -Return Value: - N/A - -*/ -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - - requestContext->TimeSentDownFirstTime.QuadPart = 0; - requestContext->TimeSentDownLasttTime.QuadPart = 0; - - return; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceGetParameter( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ PWSTR SubkeyName, - _In_ PWSTR ParameterName, - _Inout_ PULONG ParameterValue // also default value - ) -/*++ -Routine Description: - - retrieve device parameter from registry. - -Arguments: - - DeviceExtension - device context. - - SubkeyName - name of subkey - - ParameterName - the registry parameter to be retrieved - -Return Value: - - ParameterValue - registry value retrieved - ---*/ -{ - NTSTATUS status; - WDFKEY rootKey = NULL; - WDFKEY subKey = NULL; - UNICODE_STRING registrySubKeyName; - UNICODE_STRING registryValueName; - ULONG defaultParameterValue; - - PAGED_CODE(); - - RtlInitUnicodeString(®istryValueName, ParameterName); - - if (SubkeyName != NULL) - { - RtlInitUnicodeString(®istrySubKeyName, SubkeyName); - } - - // open the hardware key - status = WdfDeviceOpenRegistryKey(DeviceExtension->Device, - PLUGPLAY_REGKEY_DEVICE, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &rootKey); - - // open the sub key - if (NT_SUCCESS(status) && (SubkeyName != NULL)) - { - status = WdfRegistryOpenKey(rootKey, - ®istrySubKeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &subKey); - - if (!NT_SUCCESS(status)) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - } - - if (NT_SUCCESS(status) && (rootKey != NULL)) - { - defaultParameterValue = *ParameterValue; - - status = WdfRegistryQueryULong((subKey != NULL) ? subKey : rootKey, - ®istryValueName, - ParameterValue); - - if (!NT_SUCCESS(status)) - { - *ParameterValue = defaultParameterValue; // use default value - } - } - - // close what we open - if (subKey != NULL) - { - WdfRegistryClose(subKey); - subKey = NULL; - } - - if (rootKey != NULL) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - - // Windows 2000 SP3 uses the driver-specific key, so look in there - if (!NT_SUCCESS(status)) - { - // open the software key - status = WdfDeviceOpenRegistryKey(DeviceExtension->Device, - PLUGPLAY_REGKEY_DRIVER, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &rootKey); - - // open the sub key - if (NT_SUCCESS(status) && (SubkeyName != NULL)) - { - status = WdfRegistryOpenKey(rootKey, - ®istrySubKeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &subKey); - - if (!NT_SUCCESS(status)) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - } - - if (NT_SUCCESS(status) && (rootKey != NULL)) - { - defaultParameterValue = *ParameterValue; - - status = WdfRegistryQueryULong((subKey != NULL) ? subKey : rootKey, - ®istryValueName, - ParameterValue); - - if (!NT_SUCCESS(status)) - { - *ParameterValue = defaultParameterValue; // use default value - } - else - { - // Migrate the value over to the device-specific key - DeviceSetParameter(DeviceExtension, SubkeyName, ParameterName, *ParameterValue); - } - } - - // close what we open - if (subKey != NULL) - { - WdfRegistryClose(subKey); - subKey = NULL; - } - - if (rootKey != NULL) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - } - - return; - -} // end DeviceetParameter() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSetParameter( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_z_ PWSTR SubkeyName, - _In_ PWSTR ParameterName, - _In_ ULONG ParameterValue - ) -/*++ -Routine Description: - - set parameter to registry. - -Arguments: - - DeviceExtension - device context. - - SubkeyName - name of subkey - - ParameterName - the registry parameter to be retrieved - - ParameterValue - registry value to be set - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status; - WDFKEY rootKey = NULL; - WDFKEY subKey = NULL; - UNICODE_STRING registrySubKeyName; - UNICODE_STRING registryValueName; - - PAGED_CODE(); - - RtlInitUnicodeString(®istryValueName, ParameterName); - - if (SubkeyName != NULL) - { - RtlInitUnicodeString(®istrySubKeyName, SubkeyName); - } - - // open the hardware key - status = WdfDeviceOpenRegistryKey(DeviceExtension->Device, - PLUGPLAY_REGKEY_DEVICE, - KEY_READ | KEY_WRITE, - WDF_NO_OBJECT_ATTRIBUTES, - &rootKey); - - // open the sub key - if (NT_SUCCESS(status) && (SubkeyName != NULL)) - { - status = WdfRegistryOpenKey(rootKey, - ®istrySubKeyName, - KEY_READ | KEY_WRITE, - WDF_NO_OBJECT_ATTRIBUTES, - &subKey); - - if (!NT_SUCCESS(status)) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - } - - if (NT_SUCCESS(status) && (rootKey != NULL)) - { - status = WdfRegistryAssignULong((subKey != NULL) ? subKey : rootKey, - ®istryValueName, - ParameterValue); - } - - // close what we open - if (subKey != NULL) - { - WdfRegistryClose(subKey); - subKey = NULL; - } - - if (rootKey != NULL) - { - WdfRegistryClose(rootKey); - rootKey = NULL; - } - - return status; - -} // end DeviceSetParameter() - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceSendRequestSynchronously( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ BOOLEAN RequestFormated - ) -/*++ -Routine Description: - - send a request to lower driver synchronously. - -Arguments: - - Device - device object. - - Request - request object - - RequestFormated - if the request is already formatted, will no do it in this function - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - BOOLEAN requestCancelled = FALSE; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - - PAGED_CODE(); - - if (!RequestFormated) - { - // set request up for sending down - WdfRequestFormatRequestUsingCurrentType(Request); - } - - // get cancellation status for the original request - if (requestContext->OriginalRequest != NULL) - { - requestCancelled = WdfRequestIsCanceled(requestContext->OriginalRequest); - } - - if (!requestCancelled) - { - status = RequestSend(deviceExtension, - Request, - deviceExtension->IoTarget, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - NULL); - } - else - { - status = STATUS_CANCELLED; - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSendSrbSynchronously( - _In_ WDFDEVICE Device, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_opt_ PVOID BufferAddress, - _In_ ULONG BufferLength, - _In_ BOOLEAN WriteToDevice, - _In_opt_ WDFREQUEST OriginalRequest - ) -/*++ -Routine Description: - - Send a SRB structure to lower driver synchronously. - - Process of this function: - 1. Allocate SenseBuffer; Create Request; Allocate MDL - 2. Do following loop if necessary - 2.1 Reuse Request - 2.2 Format Srb, Irp - 2.3 Send Request - 2.4 Error Intepret and retry decision making. - 3. Release all allocated resosurces. - -Arguments: - - Device - device object. - - Request - request object - - RequestFormated - if the request is already formatted, will no do it in this function - -Return Value: - NTSTATUS - -NOTE: -The caller needs to setup following fields before calling this routine. - srb.CdbLength - srb.TimeOutValue - cdb - -BufferLength and WriteToDevice to control the data direction of the device - BufferLength = 0: No data transfer - BufferLenth != 0 && !WriteToDevice: get data from device - BufferLenth != 0 && WriteToDevice: send data to device ---*/ -{ - NTSTATUS status; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_PRIVATE_FDO_DATA fdoData = deviceExtension->PrivateFdoData; - PUCHAR senseInfoBuffer = NULL; - ULONG retryCount = 0; - BOOLEAN retry = FALSE; - ULONG ioctlCode = 0; - WDFREQUEST request = NULL; - PIRP irp = NULL; - PIO_STACK_LOCATION nextStack = NULL; - PMDL mdlAddress = NULL; - BOOLEAN memoryLocked = FALSE; - WDF_OBJECT_ATTRIBUTES attributes; - PZERO_POWER_ODD_INFO zpoddInfo = deviceExtension->ZeroPowerODDInfo; - - PAGED_CODE(); - - // NOTE: This code is only pagable because we are not freezing - // the queue. Allowing the queue to be frozen from a pagable - // routine could leave the queue frozen as we try to page in - // the code to unfreeze the queue. The result would be a nice - // case of deadlock. Therefore, since we are unfreezing the - // queue regardless of the result, just set the NO_FREEZE_QUEUE - // flag in the SRB. - NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL); - - //1. allocate SenseBuffer and initiate Srb common fields - // these fields will not be changed by lower driver. - { - // Write length to SRB. - Srb->Length = sizeof(SCSI_REQUEST_BLOCK); - Srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - Srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE; - - // Sense buffer is in aligned nonpaged pool. - senseInfoBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - SENSE_BUFFER_SIZE, - CDROM_TAG_SENSE_INFO); - - if (senseInfoBuffer == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: Can't allocate MDL\n")); - - goto Exit; - } - - Srb->SenseInfoBuffer = senseInfoBuffer; - Srb->DataBuffer = BufferAddress; - - // set timeout value to default value if it's not specifically set by caller. - if (Srb->TimeOutValue == 0) - { - Srb->TimeOutValue = deviceExtension->TimeOutValue; - } - } - - //2. Create Request object - { - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - - status = WdfRequestCreate(&attributes, - deviceExtension->IoTarget, - &request); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: Can't create request: %lx\n", - status)); - - goto Exit; - } - - irp = WdfRequestWdmGetIrp(request); - } - - // 3. Build an MDL for the data buffer and stick it into the irp. - if (BufferAddress != NULL) - { - mdlAddress = IoAllocateMdl( BufferAddress, - BufferLength, - FALSE, - FALSE, - irp ); - if (mdlAddress == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: Can't allocate MDL\n")); - - goto Exit; - } - - try - { - MmProbeAndLockPages(mdlAddress, - KernelMode, - (WriteToDevice ? IoReadAccess : IoWriteAccess)); - } - except(EXCEPTION_EXECUTE_HANDLER) - { - status = GetExceptionCode(); - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: Exception %lx locking buffer\n", status)); - - goto Exit; - } - - memoryLocked = TRUE; - } - - // 4. Format Srb, Irp; Send request and retry when necessary - do - { - // clear the control variable. - retry = FALSE; - - // 4.1 reuse the request object; set originalRequest field. - { - WDF_REQUEST_REUSE_PARAMS params; - PCDROM_REQUEST_CONTEXT requestContext = NULL; - - // deassign the MdlAddress, this is the value we assign explicitly. - // doing this can prevent WdfRequestReuse to release the Mdl unexpectly. - if (irp->MdlAddress) - { - irp->MdlAddress = NULL; - } - - WDF_REQUEST_REUSE_PARAMS_INIT(¶ms, - WDF_REQUEST_REUSE_NO_FLAGS, - STATUS_SUCCESS); - - status = WdfRequestReuse(request, ¶ms); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: WdfRequestReuse failed, %!STATUS!\n", - status)); - // exit the loop. - break; - } - - // WDF requests to format the request befor sending it - status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget, - request, - ioctlCode, - NULL, NULL, - NULL, NULL, - NULL, NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendSrbSynchronously: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n", - status)); - // exit the loop. - break; - } - - requestContext = RequestGetContext(request); - requestContext->OriginalRequest = OriginalRequest; - } - - // 4.2 Format Srb and Irp - { - Srb->OriginalRequest = irp; - Srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - Srb->DataTransferLength = BufferLength; - Srb->SrbFlags = deviceExtension->SrbFlags; - - // Disable synchronous transfer for these requests. - SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER); - SET_FLAG(Srb->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); - - if (BufferAddress != NULL) - { - if (WriteToDevice) - { - SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_OUT); - ioctlCode = IOCTL_SCSI_EXECUTE_OUT; - } - else - { - SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_IN); - ioctlCode = IOCTL_SCSI_EXECUTE_IN; - } - } - else - { - ioctlCode = IOCTL_SCSI_EXECUTE_NONE; - } - - - // Zero out status. - Srb->ScsiStatus = 0; - Srb->SrbStatus = 0; - Srb->NextSrb = NULL; - - // irp related fields - irp->MdlAddress = mdlAddress; - - nextStack = IoGetNextIrpStackLocation(irp); - - nextStack->MajorFunction = IRP_MJ_SCSI; - nextStack->Parameters.DeviceIoControl.IoControlCode = ioctlCode; - nextStack->Parameters.Scsi.Srb = Srb; - } - - // 4.3 send Request to lower driver. - status = DeviceSendRequestSynchronously(Device, request, TRUE); - - if (status != STATUS_CANCELLED) - { - NT_ASSERT(SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_PENDING); - NT_ASSERT(status != STATUS_PENDING); - NT_ASSERT(!(Srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN)); - - // 4.4 error process. - if (SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS) - { - LONGLONG retryIntervalIn100ns = 0; - - // Update status and determine if request should be retried. - retry = RequestSenseInfoInterpret(deviceExtension, - request, - Srb, - retryCount, - &status, - &retryIntervalIn100ns); - - if (retry) - { - LARGE_INTEGER t; - t.QuadPart = -retryIntervalIn100ns; - retryCount++; - KeDelayExecutionThread(KernelMode, FALSE, &t); - } - } - else - { - // Request succeeded. - fdoData->LoggedTURFailureSinceLastIO = FALSE; - status = STATUS_SUCCESS; - retry = FALSE; - } - } - } while(retry); - - if ((zpoddInfo != NULL) && - (zpoddInfo->MonitorStartStopUnit != FALSE) && - (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SUCCESS)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceSendSrbSynchronously: soft eject detected, device marked as active\n")); - - DeviceMarkActive(deviceExtension, TRUE, FALSE); - } - - // 5. Release all allocated resources. - - // required even though we allocated our own, since the port driver may - // have allocated one also - if (PORT_ALLOCATED_SENSE(deviceExtension, Srb)) - { - FREE_PORT_ALLOCATED_SENSE_BUFFER(deviceExtension, Srb); - } - -Exit: - - if (senseInfoBuffer != NULL) - { - FREE_POOL(senseInfoBuffer); - } - - Srb->SenseInfoBuffer = NULL; - Srb->SenseInfoBufferLength = 0; - - if (mdlAddress) - { - if (memoryLocked) - { - MmUnlockPages(mdlAddress); - memoryLocked = FALSE; - } - - IoFreeMdl(mdlAddress); - irp->MdlAddress = NULL; - } - - if (request) - { - WdfObjectDelete(request); - } - - return status; -} - - -VOID -DeviceSendNotification( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ const GUID* Guid, - _In_ ULONG ExtraDataSize, - _In_opt_ PVOID ExtraData - ) -/*++ -Routine Description: - - send notification to other components - -Arguments: - - DeviceExtension - device context. - - Guid - GUID for the notification - - ExtraDataSize - data size along with notification - - ExtraData - data buffer send with notification - -Return Value: - None - ---*/ -{ - PTARGET_DEVICE_CUSTOM_NOTIFICATION notification; - ULONG requiredSize; - NTSTATUS status; - - status = RtlULongAdd((sizeof(TARGET_DEVICE_CUSTOM_NOTIFICATION) - sizeof(UCHAR)), - ExtraDataSize, - &requiredSize); - - if (!(NT_SUCCESS(status)) || (requiredSize > 0x0000ffff)) - { - // MAX_USHORT, max total size for these events! - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN, - "Error sending event: size too large! (%x)\n", - requiredSize)); - return; - } - - notification = ExAllocatePool2(POOL_FLAG_NON_PAGED, - requiredSize, - CDROM_TAG_NOTIFICATION); - - // if none allocated, exit - if (notification == NULL) - { - return; - } - - // Prepare and send the request! - RtlZeroMemory(notification, requiredSize); - notification->Version = 1; - notification->Size = (USHORT)(requiredSize); - notification->FileObject = NULL; - notification->NameBufferOffset = -1; - notification->Event = *Guid; - - if (ExtraData != NULL) - { - RtlCopyMemory(notification->CustomDataBuffer, ExtraData, ExtraDataSize); - } - - IoReportTargetDeviceChangeAsynchronous(DeviceExtension->LowerPdo, - notification, - NULL, - NULL); - - FREE_POOL(notification); - - return; -} - - -VOID -DeviceSendStartUnit( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - Send command to SCSI unit to start or power up. - Because this command is issued asynchronounsly, that is, without - waiting on it to complete, the IMMEDIATE flag is not set. This - means that the CDB will not return until the drive has powered up. - This should keep subsequent requests from being submitted to the - device before it has completely spun up. - - This routine is called from the InterpretSense routine, when a - request sense returns data indicating that a drive must be - powered up. - - This routine may also be called from a class driver's error handler, - or anytime a non-critical start device should be sent to the device. - -Arguments: - - Device - The device object. - -Return Value: - - None. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - WDF_OBJECT_ATTRIBUTES attributes; - WDFREQUEST startUnitRequest = NULL; - WDFMEMORY inputMemory = NULL; - - PCOMPLETION_CONTEXT context = NULL; - PSCSI_REQUEST_BLOCK srb = NULL; - PCDB cdb = NULL; - - deviceExtension = DeviceGetExtension(Device); - - if (NT_SUCCESS(status)) - { - // Allocate Srb from nonpaged pool. - context = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(COMPLETION_CONTEXT), - CDROM_TAG_COMPLETION_CONTEXT); - - if (context == NULL) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceSendStartUnit: Failed to allocate completion context\n")); - - status = STATUS_INTERNAL_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - // Save the device object in the context for use by the completion - // routine. - context->Device = Device; - srb = &context->Srb; - - // Zero out srb. - RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK)); - - // setup SRB structure. - srb->Length = sizeof(SCSI_REQUEST_BLOCK); - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->TimeOutValue = START_UNIT_TIMEOUT; - - srb->SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER | - SRB_FLAGS_DISABLE_SYNCH_TRANSFER; - - // setup CDB - srb->CdbLength = 6; - cdb = (PCDB)srb->Cdb; - - cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT; - cdb->START_STOP.Start = 1; - cdb->START_STOP.Immediate = 0; - cdb->START_STOP.LogicalUnitNumber = srb->Lun; - - //Create Request for sending down to port driver - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - attributes.ParentObject = deviceExtension->IoTarget; - - status = WdfRequestCreate(&attributes, - deviceExtension->IoTarget, - &startUnitRequest); - } - - if (NT_SUCCESS(status)) - { - srb->OriginalRequest = WdfRequestWdmGetIrp(startUnitRequest); - NT_ASSERT(srb->OriginalRequest != NULL); - - //Prepare the request - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = startUnitRequest; - - status = WdfMemoryCreatePreallocated(&attributes, - (PVOID)srb, - sizeof(SCSI_REQUEST_BLOCK), - &inputMemory); - } - - if (NT_SUCCESS(status)) - { - status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget, - startUnitRequest, - IOCTL_SCSI_EXECUTE_NONE, - inputMemory, - NULL, - NULL, - NULL, - NULL, - NULL); - } - - if (NT_SUCCESS(status)) - { - // Set a CompletionRoutine callback function. - WdfRequestSetCompletionRoutine(startUnitRequest, - DeviceAsynchronousCompletion, - context); - - status = RequestSend(deviceExtension, - startUnitRequest, - deviceExtension->IoTarget, - 0, - NULL); - } - - // release resources when failed. - if (!NT_SUCCESS(status)) - { - FREE_POOL(context); - if (startUnitRequest != NULL) - { - WdfObjectDelete(startUnitRequest); - } - } - - return; -} // end StartUnit() - - -VOID -DeviceSendIoctlAsynchronously( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_ PDEVICE_OBJECT TargetDeviceObject - ) -/*++ - -Routine Description: - - Send an IOCTL asynchronously - -Arguments: - - DeviceExtension - device context. - IoControlCode - IOCTL code. - TargetDeviceObject - target device object. - -Return Value: - - None. - ---*/ -{ - PIRP irp = NULL; - PIO_STACK_LOCATION nextIrpStack = NULL; - - irp = IoAllocateIrp(DeviceExtension->DeviceObject->StackSize, FALSE); - - if (irp != NULL) - { - nextIrpStack = IoGetNextIrpStackLocation(irp); - - nextIrpStack->MajorFunction = IRP_MJ_DEVICE_CONTROL; - - nextIrpStack->Parameters.DeviceIoControl.OutputBufferLength = 0; - nextIrpStack->Parameters.DeviceIoControl.InputBufferLength = 0; - nextIrpStack->Parameters.DeviceIoControl.IoControlCode = IoControlCode; - nextIrpStack->Parameters.DeviceIoControl.Type3InputBuffer = NULL; - - IoSetCompletionRoutine(irp, - RequestAsynchronousIrpCompletion, - DeviceExtension, - TRUE, - TRUE, - TRUE); - - (VOID) IoCallDriver(TargetDeviceObject, irp); - } -} - -NTSTATUS -RequestAsynchronousIrpCompletion( - _In_ PDEVICE_OBJECT DeviceObject, - _In_ PIRP Irp, - _In_reads_opt_(_Inexpressible_("varies")) PVOID Context - ) -/*++ - -Routine Description: - - Free the Irp. - -Arguments: - - DeviceObject - device that the completion routine fires on. - - Irp - The irp to be completed. - - Context - IRP context - -Return Value: - NTSTATUS - ---*/ -{ - UNREFERENCED_PARAMETER(DeviceObject); - UNREFERENCED_PARAMETER(Context); - - IoFreeIrp(Irp); - - return STATUS_MORE_PROCESSING_REQUIRED; -} - -VOID -DeviceAsynchronousCompletion( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS Params, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This routine is called when an asynchronous I/O request - which was issused by the class driver completes. Examples of such requests - are release queue or START UNIT. This routine releases the queue if - necessary. It then frees the context and the IRP. - -Arguments: - - DeviceObject - The device object for the logical unit; however since this - is the top stack location the value is NULL. - - Irp - Supplies a pointer to the Irp to be processed. - - Context - Supplies the context to be used to process this request. - -Return Value: - - None. - ---*/ -{ - PCOMPLETION_CONTEXT context = (PCOMPLETION_CONTEXT)Context; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(context->Device); - - UNREFERENCED_PARAMETER(Target); - UNREFERENCED_PARAMETER(Params); - - // If this is an execute srb, then check the return status and make sure. - // the queue is not frozen. - if (context->Srb.Function == SRB_FUNCTION_EXECUTE_SCSI) - { - // Check for a frozen queue. - if (context->Srb.SrbStatus & SRB_STATUS_QUEUE_FROZEN) - { - // Unfreeze the queue getting the device object from the context. - DeviceReleaseQueue(context->Device); - } - } - - // free port-allocated sense buffer if we can detect - // - if (PORT_ALLOCATED_SENSE(deviceExtension, &context->Srb)) - { - FREE_PORT_ALLOCATED_SENSE_BUFFER(deviceExtension, &context->Srb); - } - - FREE_POOL(context); - - WdfObjectDelete(Request); - -} // end DeviceAsynchronousCompletion() - - -VOID -DeviceReleaseQueue( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine issues an internal device control command - to the port driver to release a frozen queue. The call - is issued asynchronously as DeviceReleaseQueue will be invoked - from the IO completion DPC (and will have no context to - wait for a synchronous call to complete). - - This routine must be called with the remove lock held. - -Arguments: - - Device - The functional device object for the device with the frozen queue. - -Return Value: - - None. - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PSCSI_REQUEST_BLOCK srb = NULL; - KIRQL currentIrql; - - // we raise irql seperately so we're not swapped out or suspended - // while holding the release queue irp in this routine. this lets - // us release the spin lock before lowering irql. - KeRaiseIrql(DISPATCH_LEVEL, ¤tIrql); - - WdfSpinLockAcquire(deviceExtension->ReleaseQueueSpinLock); - - if (deviceExtension->ReleaseQueueInProgress) - { - // Someone is already doing this work - just set the flag to indicate that - // we need to release the queue again. - deviceExtension->ReleaseQueueNeeded = TRUE; - WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock); - KeLowerIrql(currentIrql); - - return; - } - - // Mark that there is a release queue in progress and drop the spinlock. - deviceExtension->ReleaseQueueInProgress = TRUE; - - WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock); - - srb = &(deviceExtension->ReleaseQueueSrb); - - // Optical media are removable, so we just flush the queue. This will also release it. - srb->Function = SRB_FUNCTION_FLUSH_QUEUE; - - srb->OriginalRequest = WdfRequestWdmGetIrp(deviceExtension->ReleaseQueueRequest); - - // Set a CompletionRoutine callback function. - WdfRequestSetCompletionRoutine(deviceExtension->ReleaseQueueRequest, - DeviceReleaseQueueCompletion, - Device); - // Send the request. If an error occurs, complete the request. - RequestSend(deviceExtension, - deviceExtension->ReleaseQueueRequest, - deviceExtension->IoTarget, - WDF_REQUEST_SEND_OPTION_IGNORE_TARGET_STATE, - NULL); - - KeLowerIrql(currentIrql); - - return; - -} // end DeviceReleaseQueue() - -VOID -DeviceReleaseQueueCompletion( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS Params, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This routine is called when an asynchronous release queue request which - was issused in DeviceReleaseQueue completes. This routine prepares for - the next release queue request and resends it if necessary. - -Arguments: - - Request - The completed request. - - Target - IoTarget object - - Params - Completion parameters - - Context - WDFDEVICE object handle. - -Return Value: - - None. - ---*/ -{ - NTSTATUS status; - WDFDEVICE device = Context; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - - BOOLEAN releaseQueueNeeded = FALSE; - WDF_REQUEST_REUSE_PARAMS params = {0}; - - UNREFERENCED_PARAMETER(Target); - UNREFERENCED_PARAMETER(Params); - - WDF_REQUEST_REUSE_PARAMS_INIT(¶ms, - WDF_REQUEST_REUSE_NO_FLAGS, - STATUS_SUCCESS); - - // Grab the spinlock and clear the release queue in progress flag so others - // can run. Save (and clear) the state of the release queue needed flag - // so that we can issue a new release queue outside the spinlock. - WdfSpinLockAcquire(deviceExtension->ReleaseQueueSpinLock); - - releaseQueueNeeded = deviceExtension->ReleaseQueueNeeded; - - deviceExtension->ReleaseQueueNeeded = FALSE; - deviceExtension->ReleaseQueueInProgress = FALSE; - - // Reuse the ReleaseQueueRequest for the next time. - status = WdfRequestReuse(Request,¶ms); - - if (NT_SUCCESS(status)) - { - // Preformat the ReleaseQueueRequest for the next time. - // This should always succeed because it was already preformatted once during device initialization - status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget, - Request, - IOCTL_SCSI_EXECUTE_NONE, - deviceExtension->ReleaseQueueInputMemory, - NULL, - NULL, - NULL, - NULL, - NULL); - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceReleaseQueueCompletion: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n", - status)); - } - - RequestClearSendTime(Request); - - WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock); - - // If we need a release queue then issue one now. Another processor may - // have already started one in which case we'll try to issue this one after - // it is done - but we should never recurse more than one deep. - if (releaseQueueNeeded) - { - DeviceReleaseQueue(device); - } - - return; - -} // DeviceReleaseQueueCompletion() - - -// -// In order to provide better performance without the need to reboot, -// we need to implement a self-adjusting method to set and clear the -// srb flags based upon current performance. -// -// whenever there is an error, immediately grab the spin lock. the -// MP perf hit here is acceptable, since we're in an error path. this -// is also neccessary because we are guaranteed to be modifying the -// SRB flags here, setting SuccessfulIO to zero, and incrementing the -// actual error count (which is always done within this spinlock). -// -// whenever there is no error, increment a counter. if there have been -// errors on the device, and we've enabled dynamic perf, *and* we've -// just crossed the perf threshhold, then grab the spin lock and -// double check that the threshhold has, indeed been hit(*). then -// decrement the error count, and if it's dropped sufficiently, undo -// some of the safety changes made in the SRB flags due to the errors. -// -// * this works in all cases. even if lots of ios occur after the -// previous guy went in and cleared the successfulio counter, that -// just means that we've hit the threshhold again, and so it's proper -// to run the inner loop again. -// - -VOID -DevicePerfIncrementErrorCount( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -{ - PCDROM_PRIVATE_FDO_DATA fdoData = DeviceExtension->PrivateFdoData; - KIRQL oldIrql; - ULONG errors; - - KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql); - - fdoData->Perf.SuccessfulIO = 0; // implicit interlock - errors = InterlockedIncrement((PLONG)&DeviceExtension->ErrorCount); - - if (errors >= CLASS_ERROR_LEVEL_1) - { - // If the error count has exceeded the error limit, then disable - // any tagged queuing, multiple requests per lu queueing - // and sychronous data transfers. - // - // Clearing the no queue freeze flag prevents the port driver - // from sending multiple requests per logical unit. - CLEAR_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); - CLEAR_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE); - - SET_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER); - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "PerfIncrementErrorCount: Too many errors; disabling tagged queuing and " - "synchronous data tranfers.\n")); - } - - if (errors >= CLASS_ERROR_LEVEL_2) - { - // If a second threshold is reached, disable disconnects. - SET_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_DISABLE_DISCONNECT); - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "PerfIncrementErrorCount: Too many errors; disabling disconnects.\n")); - } - - KeReleaseSpinLock(&fdoData->SpinLock, oldIrql); - return; -} - - -_IRQL_requires_max_(APC_LEVEL) -PVOID -DeviceFindFeaturePage( - _In_reads_bytes_(Length) PGET_CONFIGURATION_HEADER FeatureBuffer, - _In_ ULONG const Length, - _In_ FEATURE_NUMBER const Feature - ) -/*++ -Routine Description: - - find the specific feature page in the buffer - -Arguments: - - FeatureBuffer - buffer contains the device feature set. - - Length - buffer length - - Feature - the feature number looking for. - -Return Value: - - PVOID - pointer to the starting location of the specific feature in buffer. - ---*/ -{ - PUCHAR buffer; - PUCHAR limit; - ULONG validLength; - - PAGED_CODE(); - - if (Length < sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER)) - { - return NULL; - } - - // Calculate the length of valid data available in the - // capabilities buffer from the DataLength field - REVERSE_BYTES(&validLength, FeatureBuffer->DataLength); - - validLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - // set limit to point to first illegal address - limit = (PUCHAR)FeatureBuffer; - limit += min(Length, validLength); - - // set buffer to point to first page - buffer = FeatureBuffer->Data; - - // loop through each page until we find the requested one, or - // until it's not safe to access the entire feature header - // (if equal, have exactly enough for the feature header) - while (buffer + sizeof(FEATURE_HEADER) <= limit) - { - PFEATURE_HEADER header = (PFEATURE_HEADER)buffer; - FEATURE_NUMBER thisFeature; - - thisFeature = (header->FeatureCode[0] << 8) | - (header->FeatureCode[1]); - - if (thisFeature == Feature) - { - PUCHAR temp; - - // if don't have enough memory to safely access all the feature - // information, return NULL - temp = buffer; - temp += sizeof(FEATURE_HEADER); - temp += header->AdditionalLength; - - if (temp > limit) - { - // this means the transfer was cut-off, an insufficiently - // small buffer was given, or other arbitrary error. since - // it's not safe to view the amount of data (even though - // the header is safe) in this feature, pretend it wasn't - // transferred at all... - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Feature %x exists, but not safe to access all its data. returning NULL\n", - Feature)); - return NULL; - } - else - { - return buffer; - } - } - - if ((header->AdditionalLength % 4) && - !(Feature >= 0xff00 && Feature <= 0xffff)) - { - return NULL; - } - - buffer += sizeof(FEATURE_HEADER); - buffer += header->AdditionalLength; - } - - return NULL; -} - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DevicePrintAllFeaturePages( - _In_reads_bytes_(Usable) PGET_CONFIGURATION_HEADER Buffer, - _In_ ULONG const Usable - ) -/*++ -Routine Description: - - print out all feature pages in the buffer - -Arguments: - - Buffer - buffer contains the device feature set. - - Usable - - -Return Value: - - none - ---*/ -{ -#if DBG - PFEATURE_HEADER header; - - PAGED_CODE(); - - //////////////////////////////////////////////////////////////////////////////// - // items expected to ALWAYS be current if they exist - //////////////////////////////////////////////////////////////////////////////// - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureProfileList); - if (header != NULL) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: CurrentProfile %x " - "with %x bytes of data at %p\n", - Buffer->CurrentProfile[0] << 8 | - Buffer->CurrentProfile[1], - Usable, Buffer)); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCore); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "CORE Features" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureMorphing); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Morphing" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRemovableMedium); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Removable Medium" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeaturePowerManagement); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Power Management" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureEmbeddedChanger); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Embedded Changer" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureMicrocodeUpgrade); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Microcode Update" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureTimeout); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Timeouts" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureLogicalUnitSerialNumber); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "LUN Serial Number" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureFirmwareDate); - if (header) { - - ULONG featureSize = header->AdditionalLength; - featureSize += RTL_SIZEOF_THROUGH_FIELD(FEATURE_HEADER, AdditionalLength); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Firmware Date" - )); - - if (featureSize >= RTL_SIZEOF_THROUGH_FIELD(FEATURE_DATA_FIRMWARE_DATE, Minute)) - { - PFEATURE_DATA_FIRMWARE_DATE date = (PFEATURE_DATA_FIRMWARE_DATE)header; - // show date as "YYYY/MM/DD hh:mm", which is 18 chars (17+NULL) - UCHAR dateString[18] = { 0 }; - dateString[ 0] = date->Year[0]; - dateString[ 1] = date->Year[1]; - dateString[ 2] = date->Year[2]; - dateString[ 3] = date->Year[3]; - dateString[ 4] = '/'; - dateString[ 5] = date->Month[0]; - dateString[ 6] = date->Month[1]; - dateString[ 7] = '/'; - dateString[ 8] = date->Day[0]; - dateString[ 9] = date->Day[1]; - dateString[10] = ' '; - dateString[11] = ' '; - dateString[12] = date->Hour[0]; - dateString[13] = date->Hour[1]; - dateString[14] = ':'; - dateString[15] = date->Minute[0]; - dateString[16] = date->Minute[1]; - dateString[17] = 0; - // SECONDS IS NOT AVAILABLE ON EARLY IMPLEMENTATIONS -- ignore it - //dateString[17] = ':'; - //dateString[18] = date->Seconds[0]; - //dateString[19] = date->Seconds[1]; - //dateString[20] = 0; - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: Firmware Date/Time %s (UTC)\n", - (PCSTR)dateString - )); - } - } - -//////////////////////////////////////////////////////////////////////////////// -// items expected not to always be current -//////////////////////////////////////////////////////////////////////////////// - - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureWriteProtect); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Software Write Protect" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRandomReadable); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Random Reads" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureMultiRead); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Multi-Read" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdRead); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "reading from CD-ROM/R/RW" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdRead); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD Structure Reads" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRandomWritable); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Random Writes" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureIncrementalStreamingWritable); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Incremental Streaming Writing" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureSectorErasable); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Sector Erasable Media" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureFormattable); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Formatting" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDefectManagement); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "defect management" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureWriteOnce); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Write Once Media" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRestrictedOverwrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Restricted Overwrites" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdrwCAVWrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "CD-RW CAV recording" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureMrw); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Mount Rainier media" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureEnhancedDefectReporting); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Enhanced Defect Reporting" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdPlusRW); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD+RW media" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRigidRestrictedOverwrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Rigid Restricted Overwrite" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdTrackAtOnce); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "CD Recording (Track At Once)" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdMastering); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "CD Recording (Mastering)" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdRecordableWrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD Recording (Mastering)" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRead); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DD CD Reading" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRWrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DD CD-R Writing" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRWWrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DD CD-RW Writing" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureLayerJumpRecording); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Layer Jump Recording" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureHDDVDRead); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "HD-DVD Reading" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureHDDVDWrite); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "HD-DVD Writing" - )); - } - - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureSMART); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "S.M.A.R.T." - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureCDAudioAnalogPlay); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Analogue CD Audio Operations" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdCSS); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD CSS" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureRealTimeStreaming); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "Real-time Streaming Reads" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDiscControlBlocks); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD Disc Control Blocks" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdCPRM); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "DVD CPRM" - )); - } - - header = DeviceFindFeaturePage(Buffer, Usable, FeatureAACS); - if (header) { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT, - "CdromGetConfiguration: %s %s\n", - (header->Current ? - "Currently supports" : "Is able to support"), - "AACS" - )); - } - -#else - PAGED_CODE(); - - UNREFERENCED_PARAMETER(Usable); - UNREFERENCED_PARAMETER(Buffer); - -#endif // DBG - return; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -MediaReadCapacity( - _In_ WDFDEVICE Device - ) -/*++ -Routine Description: - - Get media capacity - -Arguments: - - Device - the device that owns the media - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - SCSI_REQUEST_BLOCK srb; - PCDB cdb = NULL; - READ_CAPACITY_DATA capacityData; - - PAGED_CODE(); - - RtlZeroMemory(&srb, sizeof(srb)); - RtlZeroMemory(&capacityData, sizeof(capacityData)); - - cdb = (PCDB)(&srb.Cdb); - - //Prepare SCSI command fields - srb.CdbLength = 10; - srb.TimeOutValue = CDROM_READ_CAPACITY_TIMEOUT; - cdb->CDB10.OperationCode = SCSIOP_READ_CAPACITY; - - status = DeviceSendSrbSynchronously(Device, - &srb, - &capacityData, - sizeof(READ_CAPACITY_DATA), - FALSE, - NULL); - - //Remember the result - if (!NT_SUCCESS(status)) - { - //Set the BytesPerBlock to zero, this is for safe as if error happens this field should stay zero (no change). - //it will be treated as error case in MediaReadCapacityDataInterpret() - capacityData.BytesPerBlock = 0; - } - - MediaReadCapacityDataInterpret(Device, &capacityData); - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -VOID -MediaReadCapacityDataInterpret( - _In_ WDFDEVICE Device, - _In_ PREAD_CAPACITY_DATA ReadCapacityBuffer - ) -/*++ -Routine Description: - - Interpret media capacity and set corresponding fields in device context - -Arguments: - - Device - the device that owns the media - - ReadCapacityBuffer - data buffer of capacity - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - ULONG lastSector = 0; - ULONG bps = 0; - ULONG lastBit = 0; - ULONG bytesPerBlock = 0; - BOOLEAN errorHappened = FALSE; - - PAGED_CODE(); - - NT_ASSERT(ReadCapacityBuffer); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "MediaReadCapacityDataInterpret: Entering\n")); - - // Swizzle bytes from Read Capacity and translate into - // the necessary geometry information in the device extension. - bytesPerBlock = ReadCapacityBuffer->BytesPerBlock; - - ((PFOUR_BYTE)&bps)->Byte0 = ((PFOUR_BYTE)&bytesPerBlock)->Byte3; - ((PFOUR_BYTE)&bps)->Byte1 = ((PFOUR_BYTE)&bytesPerBlock)->Byte2; - ((PFOUR_BYTE)&bps)->Byte2 = ((PFOUR_BYTE)&bytesPerBlock)->Byte1; - ((PFOUR_BYTE)&bps)->Byte3 = ((PFOUR_BYTE)&bytesPerBlock)->Byte0; - - // Insure that bps is a power of 2. - // This corrects a problem with the HP 4020i CDR where it - // returns an incorrect number for bytes per sector. - if (!bps) - { - // Set disk geometry to default values (per ISO 9660). - bps = 2048; - errorHappened = TRUE; - } - else - { - lastBit = (ULONG)(-1); - while (bps) - { - lastBit++; - bps = (bps >> 1); - } - bps = (1 << lastBit); - } - - deviceExtension->DiskGeometry.BytesPerSector = bps; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "MediaReadCapacityDataInterpret: Calculated bps %#x\n", - deviceExtension->DiskGeometry.BytesPerSector)); - - // Copy last sector in reverse byte order. - bytesPerBlock = ReadCapacityBuffer->LogicalBlockAddress; - - ((PFOUR_BYTE)&lastSector)->Byte0 = ((PFOUR_BYTE)&bytesPerBlock)->Byte3; - ((PFOUR_BYTE)&lastSector)->Byte1 = ((PFOUR_BYTE)&bytesPerBlock)->Byte2; - ((PFOUR_BYTE)&lastSector)->Byte2 = ((PFOUR_BYTE)&bytesPerBlock)->Byte1; - ((PFOUR_BYTE)&lastSector)->Byte3 = ((PFOUR_BYTE)&bytesPerBlock)->Byte0; - - // Calculate sector to byte shift. - WHICH_BIT(bps, deviceExtension->SectorShift); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "MediaReadCapacityDataInterpret: Sector size is %d\n", - deviceExtension->DiskGeometry.BytesPerSector)); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "MediaReadCapacityDataInterpret: Number of Sectors is %d\n", - lastSector + 1)); - - // Calculate media capacity in bytes. - if (errorHappened) - { - // Set disk geometry to default values (per ISO 9660). - deviceExtension->PartitionLength.QuadPart = (LONGLONG)(0x7fffffff); - } - else - { - deviceExtension->PartitionLength.QuadPart = (LONGLONG)(lastSector + 1); - deviceExtension->PartitionLength.QuadPart = - (deviceExtension->PartitionLength.QuadPart << deviceExtension->SectorShift); - } - - // we've defaulted to 32/64 forever. don't want to change this now... - deviceExtension->DiskGeometry.TracksPerCylinder = 0x40; - deviceExtension->DiskGeometry.SectorsPerTrack = 0x20; - - // Calculate number of cylinders. - deviceExtension->DiskGeometry.Cylinders.QuadPart = (LONGLONG)((lastSector + 1) / (32 * 64)); - - deviceExtension->DiskGeometry.MediaType = RemovableMedia; - - return; -} - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DevicePickDvdRegion( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - pick a default dvd region - -Arguments: - - Device - Device Object - -Return Value: - - none - ---*/ -{ - NTSTATUS status; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - - // these five pointers all point to dvdReadStructure or part of - // its data, so don't deallocate them more than once! - PDVD_READ_STRUCTURE dvdReadStructure; - PDVD_COPY_PROTECT_KEY copyProtectKey; - PDVD_COPYRIGHT_DESCRIPTOR dvdCopyRight; - PDVD_RPC_KEY rpcKey; - PDVD_SET_RPC_KEY dvdRpcKey; - - size_t bytesReturned = 0; - ULONG bufferLen = 0; - UCHAR mediaRegion = 0; - ULONG pickDvdRegion = 0; - ULONG defaultDvdRegion = 0; - ULONG dvdRegion = 0; - WDFKEY registryKey = NULL; - - DECLARE_CONST_UNICODE_STRING(registryValueName, DVD_DEFAULT_REGION); - - PAGED_CODE(); - - if ((pickDvdRegion = InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, 0)) == 0) - { - // it was non-zero, so either another thread will do this, or - // we no longer need to pick a region - return; - } - - bufferLen = max( - max(sizeof(DVD_DESCRIPTOR_HEADER) + - sizeof(DVD_COPYRIGHT_DESCRIPTOR), - sizeof(DVD_READ_STRUCTURE) - ), - max(DVD_RPC_KEY_LENGTH, - DVD_SET_RPC_KEY_LENGTH - ) - ); - - dvdReadStructure = (PDVD_READ_STRUCTURE) - ExAllocatePool2(POOL_FLAG_PAGED, bufferLen, DVD_TAG_DVD_REGION); - - if (dvdReadStructure == NULL) - { - InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, pickDvdRegion); - return; - } - - copyProtectKey = (PDVD_COPY_PROTECT_KEY)dvdReadStructure; - - dvdCopyRight = (PDVD_COPYRIGHT_DESCRIPTOR) - ((PDVD_DESCRIPTOR_HEADER)dvdReadStructure)->Data; - - // get the media region - RtlZeroMemory (dvdReadStructure, bufferLen); - dvdReadStructure->Format = DvdCopyrightDescriptor; - - // Build and send a request for READ_KEY - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Getting Copyright Descriptor\n", - Device)); - - status = ReadDvdStructure(deviceExtension, - NULL, - dvdReadStructure, - sizeof(DVD_READ_STRUCTURE), - dvdReadStructure, - sizeof(DVD_DESCRIPTOR_HEADER) + sizeof(DVD_COPYRIGHT_DESCRIPTOR), - &bytesReturned); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Got Copyright Descriptor %x\n", - Device, status)); - - if ((NT_SUCCESS(status)) && - (dvdCopyRight->CopyrightProtectionType == 0x01)) - { - // keep the media region bitmap around - // a 1 means ok to play - if (dvdCopyRight->RegionManagementInformation == 0xff) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): RegionManagementInformation " - "is set to dis-allow playback for all regions. This is " - "most likely a poorly authored disc. defaulting to all " - "region disc for purpose of choosing initial region\n", - Device)); - dvdCopyRight->RegionManagementInformation = 0; - } - - mediaRegion = ~dvdCopyRight->RegionManagementInformation; - } - else - { - // can't automatically pick a default region on a drive without media, so just exit - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): failed to auto-choose a region due to status %x getting copyright descriptor\n", - Device, status)); - goto getout; - } - - // get the device region - RtlZeroMemory (copyProtectKey, bufferLen); - copyProtectKey->KeyLength = DVD_RPC_KEY_LENGTH; - copyProtectKey->KeyType = DvdGetRpcKey; - - // Build and send a request for READ_KEY for RPC key - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Getting RpcKey\n", - Device)); - status = DvdStartSessionReadKey(deviceExtension, - IOCTL_DVD_READ_KEY, - NULL, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - &bytesReturned); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Got RpcKey %x\n", - Device, status)); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): failed to get RpcKey from " - "a DVD Device\n", Device)); - goto getout; - } - - // so we now have what we can get for the media region and the - // drive region. we will not set a region if the drive has one - // set already (mask is not all 1's), nor will we set a region - // if there are no more user resets available. - rpcKey = (PDVD_RPC_KEY)copyProtectKey->KeyData; - - if (rpcKey->RegionMask != 0xff) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): not picking a region since " - "it is already chosen\n", Device)); - goto getout; - } - - if (rpcKey->UserResetsAvailable <= 1) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): not picking a region since " - "only one change remains\n", Device)); - goto getout; - } - - // OOBE sets this key based upon the system locale - status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(), - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - ®istryKey); - - if (NT_SUCCESS(status)) - { - status = WdfRegistryQueryULong(registryKey, - ®istryValueName, - &defaultDvdRegion); - - WdfRegistryClose(registryKey); - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): failed to read registry value due to status %x\n", - Device, status)); - - // by default the default Dvd region is 0 - defaultDvdRegion = 0; - status = STATUS_SUCCESS; - } - - if (defaultDvdRegion > DVD_MAX_REGION) - { - // the registry has a bogus default - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): registry has a bogus default " - "region value of %x\n", Device, defaultDvdRegion)); - - defaultDvdRegion = 0; - } - - // if defaultDvdRegion == 0, it means no default. - - // we will select the initial dvd region for the user - - if ((defaultDvdRegion != 0) && - (mediaRegion & (1 << (defaultDvdRegion - 1)))) - { - // first choice: - // the media has region that matches - // the default dvd region. - dvdRegion = (1 << (defaultDvdRegion - 1)); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Choice #1: media matches " - "drive's default, chose region %x\n", Device, dvdRegion)); - } - else if (mediaRegion) - { - // second choice: - // pick the lowest region number from the media - UCHAR mask = 1; - dvdRegion = 0; - - while (mediaRegion && !dvdRegion) - { - // pick the lowest bit - dvdRegion = mediaRegion & mask; - mask <<= 1; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Choice #2: choosing lowest " - "media region %x\n", Device, dvdRegion)); - } - else if (defaultDvdRegion) - { - // third choice: - // default dvd region from the dvd class installer - dvdRegion = (1 << (defaultDvdRegion - 1)); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Choice #3: using default " - "region for this install %x\n", Device, dvdRegion)); - } - else - { - // unable to pick one for the user -- this should rarely - // happen, since the proppage dvd class installer sets - // the key based upon the system locale - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Choice #4: failed to choose " - "a media region\n", Device)); - goto getout; - } - - // now that we've chosen a region, set the region by sending the - // appropriate request to the drive - RtlZeroMemory (copyProtectKey, bufferLen); - copyProtectKey->KeyLength = DVD_SET_RPC_KEY_LENGTH; - copyProtectKey->KeyType = DvdSetRpcKey; - dvdRpcKey = (PDVD_SET_RPC_KEY)copyProtectKey->KeyData; - dvdRpcKey->PreferredDriveRegionCode = (UCHAR)~dvdRegion; - - // Build and send request for SEND_KEY - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Sending new Rpc Key to region %x\n", - Device, dvdRegion)); - - status = DvdSendKey(deviceExtension, - NULL, - copyProtectKey, - DVD_SET_RPC_KEY_LENGTH, - &bytesReturned); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "DevicePickDvdRegion (%p): Sent new Rpc Key %x\n", - Device, status)); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "DevicePickDvdRegion (%p): unable to set dvd initial " - " region code (%x)\n", Device, status)); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, "DevicePickDvdRegion (%p): Successfully set dvd " - "initial region\n", Device)); - - pickDvdRegion = 0; - } - -getout: - if (dvdReadStructure) - { - FREE_POOL(dvdReadStructure); - } - - // update the new PickDvdRegion value - InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, pickDvdRegion); - - return; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRegisterInterface( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ CDROM_DEVICE_INTERFACES InterfaceType - ) -/*++ -Routine Description: - - used to register device class interface or mount device interface - -Arguments: - - DeviceExtension - device context - - InterfaceType - interface type to be registered. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - WDFSTRING string = NULL; - GUID* interfaceGuid = NULL; - PUNICODE_STRING savingString = NULL; - BOOLEAN setRestricted = FALSE; - UNICODE_STRING localString; - - PAGED_CODE(); - - //Get parameters - switch(InterfaceType) - { - case CdRomDeviceInterface: - interfaceGuid = (LPGUID)&GUID_DEVINTERFACE_CDROM; - setRestricted = TRUE; - savingString = &localString; - break; - case MountedDeviceInterface: - interfaceGuid = (LPGUID)&MOUNTDEV_MOUNTED_DEVICE_GUID; - savingString = &(DeviceExtension->MountedDeviceInterfaceName); - break; - default: - return STATUS_INVALID_PARAMETER; - } - - status = WdfDeviceCreateDeviceInterface(DeviceExtension->Device, - interfaceGuid, - NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "DeviceRegisterInterface: Unable to register cdrom " - "DCA for fdo %p type: %s [%lx]\n", - DeviceExtension->Device, - (InterfaceType == CdRomDeviceInterface)? "CdRom Interface" : "Mounted Device Interface", - status)); - } - - // Retrieve interface string - if (NT_SUCCESS(status)) - { - // The string object will be released when its parent object is released. - WDF_OBJECT_ATTRIBUTES attributes; - - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = DeviceExtension->Device; - - status = WdfStringCreate(WDF_NO_OBJECT_ATTRIBUTES, - NULL, - &string); - } - - if (NT_SUCCESS(status)) - { - status = WdfDeviceRetrieveDeviceInterfaceString(DeviceExtension->Device, - interfaceGuid, - NULL, - string); - } - - if (NT_SUCCESS(status)) - { - WdfStringGetUnicodeString(string, savingString); - - if (setRestricted) { - - - WdfObjectDelete(string); - } - } - - return status; -} // end DeviceRegisterInterface() - - -VOID -DeviceRestoreDefaultSpeed( - _In_ WDFWORKITEM WorkItem - ) -/*++ - -Routine Description: - - This workitem is called on a media change when the CDROM device - speed should be restored to the default value. - -Arguments: - - Fdo - Supplies the device object for the CDROM device. - WorkItem - Supplies the pointer to the workitem. - -Return Value: - - None - ---*/ -{ - NTSTATUS status; - WDFDEVICE device = WdfWorkItemGetParentObject(WorkItem); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - PPERFORMANCE_DESCRIPTOR perfDescriptor; - ULONG transferLength = sizeof(PERFORMANCE_DESCRIPTOR); - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb = (PCDB)srb.Cdb; - - PAGED_CODE(); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "DeviceRestoreDefaultSpeed: Restore device speed for %p\n", device)); - - perfDescriptor = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - transferLength, - CDROM_TAG_STREAM); - if (perfDescriptor == NULL) - { - return; - } - - RtlZeroMemory(perfDescriptor, transferLength); - - perfDescriptor->RestoreDefaults = TRUE; - - srb.TimeOutValue = deviceExtension->TimeOutValue; - - srb.CdbLength = 12; - cdb->SET_STREAMING.OperationCode = SCSIOP_SET_STREAMING; - REVERSE_BYTES_SHORT(&cdb->SET_STREAMING.ParameterListLength, &transferLength); - - status = DeviceSendSrbSynchronously(device, - &srb, - perfDescriptor, - transferLength, - TRUE, - NULL); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceRestoreDefaultSpeed: Set Streaming command completed with status: 0x%X\n", status)); - - FREE_POOL(perfDescriptor); - WdfObjectDelete(WorkItem); - - return; -} - -// custom string match -- careful! -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -StringsAreMatched( - _In_opt_z_ PCHAR StringToMatch, - _In_z_ PCHAR TargetString - ) -/*++ - -Routine Description: - - compares if two strings are identical - -Arguments: - - StringToMatch - source string. - TargetString - target string. - -Return Value: - - BOOLEAN - TRUE (identical); FALSE (not match) - ---*/ -{ - size_t length; - - PAGED_CODE(); - - NT_ASSERT(TargetString); - - // if no match requested, return TRUE - if (StringToMatch == NULL) - { - return TRUE; - } - - // cache the string length for efficiency - length = strlen(StringToMatch); - - // ZERO-length strings may only match zero-length strings - if (length == 0) - { - return (strlen(TargetString) == 0); - } - - // strncmp returns zero if the strings match - return (strncmp(StringToMatch, TargetString, length) == 0); -} - - -NTSTATUS -RequestSetContextFields( - _In_ WDFREQUEST Request, - _In_ PSYNC_HANDLER Handler - ) -/*++ - -Routine Description: - - set the request object context fields - -Arguments: - - Request - request object. - Handler - the function that finally handles this request. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - PKEVENT syncEvent = NULL; - - syncEvent = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(KEVENT), - CDROM_TAG_SYNC_EVENT); - - if (syncEvent == NULL) - { - // memory allocation failed. - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - // now, put the special synchronization information into the context - requestContext->SyncRequired = TRUE; - requestContext->SyncEvent = syncEvent; - requestContext->SyncCallback = Handler; - - status = STATUS_SUCCESS; - } - - return status; -} - - -NTSTATUS -RequestDuidGetDeviceIdProperty( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - - -Arguments: - - DeviceExtension - device context - Request - request object. - RequestParameters - request parameter - DataLength - transferred data length. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSTORAGE_DEVICE_ID_DESCRIPTOR deviceIdDescriptor = NULL; - PSTORAGE_DESCRIPTOR_HEADER descHeader = NULL; - STORAGE_PROPERTY_ID propertyId = StorageDeviceIdProperty; - - *DataLength = 0; - - // Get the VPD page 83h data. - status = DeviceRetrieveDescriptor(DeviceExtension->Device, - &propertyId, - (PSTORAGE_DESCRIPTOR_HEADER*)&deviceIdDescriptor); - - if (NT_SUCCESS(status) && (deviceIdDescriptor == NULL)) - { - status = STATUS_NOT_FOUND; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &descHeader, - NULL); - } - - if (NT_SUCCESS(status)) - { - PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid = NULL; - ULONG offset = descHeader->Size; - PUCHAR dest = (PUCHAR)descHeader + offset; - size_t outputBufferSize; - - outputBufferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - - // Adjust required size and potential destination location. - status = RtlULongAdd(descHeader->Size, deviceIdDescriptor->Size, &descHeader->Size); - - if (NT_SUCCESS(status) && - (outputBufferSize < descHeader->Size)) - { - // Output buffer is too small. Return error and make sure - // the caller gets info about required buffer size. - *DataLength = descHeader->Size; - status = STATUS_BUFFER_OVERFLOW; - } - - if (NT_SUCCESS(status)) - { - storageDuid = (PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader; - storageDuid->StorageDeviceIdOffset = offset; - - RtlCopyMemory(dest, - deviceIdDescriptor, - deviceIdDescriptor->Size); - - *DataLength = storageDuid->Size; - status = STATUS_SUCCESS; - } - - FREE_POOL(deviceIdDescriptor); - } - - return status; -} - -NTSTATUS -RequestDuidGetDeviceProperty( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - - -Arguments: - - DeviceExtension - device context - Request - request object. - RequestParameters - request parameter - DataLength - transferred data length. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = DeviceExtension->DeviceDescriptor; - PSTORAGE_DESCRIPTOR_HEADER descHeader = NULL; - PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid; - PUCHAR dest = NULL; - - if (deviceDescriptor == NULL) - { - status = STATUS_NOT_FOUND; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &descHeader, - NULL); - } - - if (NT_SUCCESS(status) && - (deviceDescriptor->SerialNumberOffset == 0)) - { - status = STATUS_NOT_FOUND; - } - - // Use this info only if serial number is available. - if (NT_SUCCESS(status)) - { - ULONG offset = descHeader->Size; - size_t outputBufferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - - // Adjust required size and potential destination location. - dest = (PUCHAR)descHeader + offset; - - status = RtlULongAdd(descHeader->Size, deviceDescriptor->Size, &descHeader->Size); - - if (NT_SUCCESS(status) && - (outputBufferSize < descHeader->Size)) - { - // Output buffer is too small. Return error and make sure - // the caller get info about required buffer size. - *DataLength = descHeader->Size; - status = STATUS_BUFFER_OVERFLOW; - } - - if (NT_SUCCESS(status)) - { - storageDuid = (PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader; - storageDuid->StorageDeviceOffset = offset; - - RtlCopyMemory(dest, - deviceDescriptor, - deviceDescriptor->Size); - - *DataLength = storageDuid->Size; - status = STATUS_SUCCESS; - } - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -ULONG -DeviceRetrieveModeSenseUsingScratch( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_reads_bytes_(Length) PCHAR ModeSenseBuffer, - _In_ ULONG Length, - _In_ UCHAR PageCode, - _In_ UCHAR PageControl - ) -/*++ - -Routine Description: - - retrieve mode sense informaiton of the device - -Arguments: - - DeviceExtension - device context - ModeSenseBuffer - buffer to savee the mode sense info. - Length - buffer length - PageCode - . - PageControl - - -Return Value: - - ULONG - transferred data length - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG transferSize = min(Length, DeviceExtension->ScratchContext.ScratchBufferSize); - CDB cdb; - - PAGED_CODE(); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.MODE_SENSE.OperationCode = SCSIOP_MODE_SENSE; - cdb.MODE_SENSE.PageCode = PageCode; - cdb.MODE_SENSE.Pc = PageControl; - cdb.MODE_SENSE.AllocationLength = (UCHAR)transferSize; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, NULL, transferSize, TRUE, &cdb, 6); - - if (NT_SUCCESS(status)) - { - transferSize = min(Length, DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength); - RtlCopyMemory(ModeSenseBuffer, - DeviceExtension->ScratchContext.ScratchBuffer, - transferSize); - } - - ScratchBuffer_EndUse(DeviceExtension); - - return transferSize; -} - -_IRQL_requires_max_(APC_LEVEL) -PVOID -ModeSenseFindSpecificPage( - _In_reads_bytes_(Length) PCHAR ModeSenseBuffer, - _In_ size_t Length, - _In_ UCHAR PageMode, - _In_ BOOLEAN Use6BytesCdb - ) -/*++ - -Routine Description: - - This routine scans through the mode sense data and finds the requested - mode sense page code. - -Arguments: - ModeSenseBuffer - Supplies a pointer to the mode sense data. - - Length - Indicates the length of valid data. - - PageMode - Supplies the page mode to be searched for. - - Use6BytesCdb - Indicates whether 6 or 10 byte mode sense was used. - -Return Value: - - A pointer to the the requested mode page. If the mode page was not found - then NULL is return. - ---*/ -{ - PCHAR limit; - ULONG parameterHeaderLength; - PVOID result = NULL; - - PAGED_CODE(); - - limit = ModeSenseBuffer + Length; - parameterHeaderLength = (Use6BytesCdb) - ? sizeof(MODE_PARAMETER_HEADER) - : sizeof(MODE_PARAMETER_HEADER10); - - if (Length >= parameterHeaderLength) - { - PMODE_PARAMETER_HEADER10 modeParam10; - ULONG blockDescriptorLength; - - // Skip the mode select header and block descriptors. - if (Use6BytesCdb) - { - blockDescriptorLength = ((PMODE_PARAMETER_HEADER)ModeSenseBuffer)->BlockDescriptorLength; - } - else - { - modeParam10 = (PMODE_PARAMETER_HEADER10) ModeSenseBuffer; - blockDescriptorLength = modeParam10->BlockDescriptorLength[1]; - } - - ModeSenseBuffer += parameterHeaderLength + blockDescriptorLength; - - // ModeSenseBuffer now points at pages. Walk the pages looking for the - // requested page until the limit is reached. - while (ModeSenseBuffer + - RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength) < limit) - { - if (((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageCode == PageMode) - { - // found the mode page. make sure it's safe to touch it all - // before returning the pointer to caller - if (ModeSenseBuffer + ((PMODE_DISCONNECT_PAGE)ModeSenseBuffer)->PageLength > limit) - { - // Return NULL since the page is not safe to access in full - result = NULL; - } - else - { - result = ModeSenseBuffer; - } - break; - } - - // Advance to the next page which is 4-byte-aligned offset after this page. - ModeSenseBuffer += ((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageLength + - RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength); - } - } - - return result; -} // end ModeSenseFindSpecificPage() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -PerformEjectionControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ MEDIA_LOCK_TYPE LockType, - _In_ BOOLEAN Lock - ) -/*++ - -Routine Description: - - ejection control process - -Arguments: - - DeviceExtension - device extension - Request - WDF request to be used for communication with the device - LockType - the type of lock - Lock - if TRUE, lock the device; if FALSE, unlock it - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - PFILE_OBJECT_CONTEXT fileObjectContext = NULL; - SCSI_REQUEST_BLOCK srb; - PCDB cdb = NULL; - - LONG newLockCount = 0; - LONG newProtectedLockCount = 0; - LONG newInternalLockCount = 0; - LONG newFileLockCount = 0; - BOOLEAN countChanged = FALSE; - BOOLEAN previouslyLocked = FALSE; - BOOLEAN nowLocked = FALSE; - - PAGED_CODE(); - - // Prevent race conditions while working with lock counts - status = WdfWaitLockAcquire(DeviceExtension->EjectSynchronizationLock, NULL); - if (!NT_SUCCESS(status)) - { - NT_ASSERT(FALSE); - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "PerformEjectionControl: " - "Received request for %s lock type\n", - LockTypeStrings[LockType] - )); - - - // If this is a "secured" request, retrieve the file object context - if (LockType == SecureMediaLock) - { - WDFFILEOBJECT fileObject = NULL; - - fileObject = WdfRequestGetFileObject(Request); - - if (fileObject == NULL) - { - status = STATUS_INVALID_HANDLE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "FileObject does not match to the one in IRP_MJ_CREATE, KMDF returns NULL\n")); - goto Exit; - } - - fileObjectContext = FileObjectGetContext(fileObject); - NT_ASSERT(fileObjectContext != NULL); - } - - // Lock counts should never fall below 0 - NT_ASSERT(DeviceExtension->LockCount >= 0); - NT_ASSERT(DeviceExtension->ProtectedLockCount >= 0); - NT_ASSERT(DeviceExtension->InternalLockCount >= 0); - - // Get the current lock counts - newLockCount = DeviceExtension->LockCount; - newProtectedLockCount = DeviceExtension->ProtectedLockCount; - newInternalLockCount = DeviceExtension->InternalLockCount; - if (fileObjectContext) - { - // fileObjectContext->LockCount is ULONG and should always >= 0 - newFileLockCount = fileObjectContext->LockCount; - } - - // Determine which lock counts need to be changed and how - if (Lock && LockType == SimpleMediaLock) - { - newLockCount++; - countChanged = TRUE; - } - else if (Lock && LockType == SecureMediaLock) - { - newFileLockCount++; - newProtectedLockCount++; - countChanged = TRUE; - } - else if (Lock && LockType == InternalMediaLock) - { - newInternalLockCount++; - countChanged = TRUE; - } - else if (!Lock && LockType == SimpleMediaLock) - { - if (newLockCount != 0) - { - newLockCount--; - countChanged = TRUE; - } - } - else if (!Lock && LockType == SecureMediaLock) - { - if ( (newFileLockCount == 0) || (newProtectedLockCount == 0) ) - { - status = STATUS_INVALID_DEVICE_STATE; - goto Exit; - } - newFileLockCount--; - newProtectedLockCount--; - countChanged = TRUE; - } - else if (!Lock && LockType == InternalMediaLock) - { - NT_ASSERT(newInternalLockCount != 0); - newInternalLockCount--; - countChanged = TRUE; - } - - if ( (DeviceExtension->LockCount != 0) || - (DeviceExtension->ProtectedLockCount != 0) || - (DeviceExtension->InternalLockCount != 0) ) - { - previouslyLocked = TRUE; - } - if ( (newLockCount != 0) || - (newProtectedLockCount != 0) || - (newInternalLockCount != 0) ) - { - nowLocked = TRUE; - } - - // Only send command down to device when necessary - if (previouslyLocked != nowLocked) - { - // Compose and send the PREVENT ALLOW MEDIA REMOVAL command. - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - srb.CdbLength = 6; - srb.TimeOutValue = DeviceExtension->TimeOutValue; - - cdb = (PCDB)&srb.Cdb; - cdb->MEDIA_REMOVAL.OperationCode = SCSIOP_MEDIUM_REMOVAL; - cdb->MEDIA_REMOVAL.Prevent = Lock; - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - NULL, - 0, - FALSE, - Request); - } - -Exit: - - // Store the updated lock counts on success - if (countChanged && NT_SUCCESS(status)) - { - DeviceExtension->LockCount = newLockCount; - DeviceExtension->ProtectedLockCount = newProtectedLockCount; - DeviceExtension->InternalLockCount = newInternalLockCount; - if (fileObjectContext) - { - fileObjectContext->LockCount = newFileLockCount; - } - } - - WdfWaitLockRelease(DeviceExtension->EjectSynchronizationLock); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "PerformEjectionControl: %!STATUS!, " - "Count Changed: %d, Command Sent: %d, " - "Current Counts: Internal: %x Secure: %x Simple: %x\n", - status, - countChanged, - previouslyLocked != nowLocked, - DeviceExtension->InternalLockCount, - DeviceExtension->ProtectedLockCount, - DeviceExtension->LockCount - )); - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceUnlockExclusive( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFFILEOBJECT FileObject, - _In_ BOOLEAN IgnorePreviousMediaChanges - ) -/*++ - -Routine Description: - - to unlock the exclusive lock - -Arguments: - - DeviceExtension - device context - FileObject - file object that currently holds the lock - IgnorePreviousMediaChanges - if TRUE, ignore previously accumulated media changes - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &DeviceExtension->DeviceAdditionalData; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - BOOLEAN ANPending = 0; - LONG requestInUse = 0; - - PAGED_CODE(); - - if (!EXCLUSIVE_MODE(cdData)) - { - // Device is not locked for exclusive access. - // Can not process unlock request. - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessUnlockDevice: Device not locked for exclusive access, can't unlock device.\n")); - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (!EXCLUSIVE_OWNER(cdData, FileObject)) - { - // Request not from the exclusive owner, can't unlock the device. - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessUnlockDevice: Unable to unlock device, invalid file object\n")); - - status = STATUS_INVALID_HANDLE; - } - - if (NT_SUCCESS(status)) - { - // Unless we were explicitly requested not to do so, generate a media removal notification - // followed by a media arrival notification similar to volume lock/unlock file system events. - if (!IgnorePreviousMediaChanges) - { - MEDIA_CHANGE_DETECTION_STATE previousMediaState = MediaUnknown; - - // Change the media state to "unavailable", which will cause a removal notification if the media - // was previously present. At the same time, store the previous state in previousMediaState. - DeviceSetMediaChangeStateEx(DeviceExtension, MediaUnavailable, &previousMediaState); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceUnlockExclusive: Changing the media state to MediaUnavailable\n")); - - // Restore the previous media state, which will cause a media arrival notification if the media - // was originally present. - DeviceSetMediaChangeStateEx(DeviceExtension, previousMediaState, NULL); - } - - // Set DO_VERIFY_VOLUME so that the file system will remount on it. - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - } - - // Set MMC state to update required - cdData->Mmc.WriteAllowed = FALSE; - cdData->Mmc.UpdateState = CdromMmcUpdateRequired; - - // Send unlock notification - DeviceSendNotification(DeviceExtension, - &GUID_IO_CDROM_EXCLUSIVE_UNLOCK, - 0, - NULL); - - InterlockedExchangePointer((PVOID)&cdData->ExclusiveOwner, NULL); - - if ((info != NULL) && (info->AsynchronousNotificationSupported != FALSE)) - { - ANPending = info->ANSignalPendingDueToExclusiveLock; - info->ANSignalPendingDueToExclusiveLock = FALSE; - - if ((ANPending != FALSE) && (info->MediaChangeDetectionDisableCount == 0)) - { - // if the request is not in use, mark it as such. - requestInUse = InterlockedCompareExchange((PLONG)&info->MediaChangeRequestInUse, 1, 0); - - if (requestInUse == 0) - { - // The last MCN finished. ok to issue the new one. - RequestSetupMcnSyncIrp(DeviceExtension); - - // The irp will go into KMDF framework and a request will be created there to represent it. - IoCallDriver(DeviceExtension->DeviceObject, info->MediaChangeSyncIrp); - } - } - } - } - - return status; -} - - -VOID -RequestCompletion( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ NTSTATUS Status, - _In_ ULONG_PTR Information - ) -{ -#ifdef DBG - ULONG ioctlCode = 0; - WDF_REQUEST_PARAMETERS requestParameters; - - // Get the Request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - if (requestParameters.Type == WdfRequestTypeDeviceControl) - { - ioctlCode = requestParameters.Parameters.DeviceIoControl.IoControlCode; - - if (requestParameters.Parameters.DeviceIoControl.IoControlCode != IOCTL_MCN_SYNC_FAKE_IOCTL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "Request complete - IOCTL - code: %X; Status: %X; Information: %X\n", - ioctlCode, - Status, - (ULONG)Information)); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "Request complete - IOCTL - code: %X; Status: %X; Information: %X\n", - ioctlCode, - Status, - (ULONG)Information)); - } - } - else if (requestParameters.Type == WdfRequestTypeRead) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "Request complete - READ - Starting Offset: %X; Length: %X; Transferred Length: %X; Status: %X\n", - (ULONG)requestParameters.Parameters.Read.DeviceOffset, - (ULONG)requestParameters.Parameters.Read.Length, - (ULONG)Information, - Status)); - } - else if (requestParameters.Type == WdfRequestTypeWrite) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "Request complete - WRITE - Starting Offset: %X; Length: %X; Transferred Length: %X; Status: %X\n", - (ULONG)requestParameters.Parameters.Write.DeviceOffset, - (ULONG)requestParameters.Parameters.Write.Length, - (ULONG)Information, - Status)); - } -#endif - - if (IoIsErrorUserInduced(Status)) - { - PIRP irp = WdfRequestWdmGetIrp(Request); - if (irp->Tail.Overlay.Thread) - { - IoSetHardErrorOrVerifyDevice(irp, DeviceExtension->DeviceObject); - } - } - - if (!NT_SUCCESS(Status) && DeviceExtension->SurpriseRemoved == TRUE) - { - // IMAPI expects ERROR_DEV_NOT_EXISTS if recorder has been surprised removed, - // or it will retry WRITE commands for up to 3 minutes - // CDROM behavior should be consistent for all requests, including SCSI pass-through - Status = STATUS_DEVICE_DOES_NOT_EXIST; - } - - WdfRequestCompleteWithInformation(Request, Status, Information); - - return; -} - - -VOID -RequestDummyCompletionRoutine( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS Params, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This is a dummy competion routine that simply calls WdfRequestComplete. We have to use - this dummy competion routine instead of WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET, because - the latter causes the framework to not check if the I/O target is closed or not. - -Arguments: - - Request - completed request - Target - the I/O target that completed the request - Params - request parameters - Context - not used - -Return Value: - - none - ---*/ -{ - UNREFERENCED_PARAMETER(Target); - UNREFERENCED_PARAMETER(Params); - UNREFERENCED_PARAMETER(Context); - - WdfRequestCompleteWithInformation(Request, - WdfRequestGetStatus(Request), - WdfRequestGetInformation(Request)); -} - - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -DeviceSendPowerDownProcessRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ PFN_WDF_REQUEST_COMPLETION_ROUTINE CompletionRoutine, - _In_opt_ PVOID Context - ) -/*++ - -Routine Description: - - This function is called during processing power down request. - It is used to send either SYNC CACHE command or STOP UNIT command. - - Caller should set proper value in deviceExtension->PowerContext.PowerChangeState.PowerDown - to trigger the correct command be sent. - -Arguments: - - DeviceExtension - - - CompletionRoutine - Completion routine that needs to be set for the request - - Context - Completion context associated with the completion routine - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - BOOLEAN requestSent = FALSE; - - BOOLEAN shouldRetry = TRUE; - PCDB cdb = (PCDB)DeviceExtension->PowerContext.Srb.Cdb; - ULONG timeoutValue = DeviceExtension->TimeOutValue; - ULONG retryCount = 1; - - // reset some fields. - DeviceExtension->PowerContext.RetryIntervalIn100ns = 0; - status = PowerContextReuseRequest(DeviceExtension); - RequestClearSendTime(DeviceExtension->PowerContext.PowerRequest); - - if (!NT_SUCCESS(status)) - { - return status; - } - - // set proper timeout value and max retry count. - switch(DeviceExtension->PowerContext.PowerChangeState.PowerDown) - { - case PowerDownDeviceInitial: - case PowerDownDeviceQuiesced: - case PowerDownDeviceStopped: - break; - - case PowerDownDeviceLocked: - // Case of issuing SYNC CACHE command. Do not use power irp timeout remaining time in this case - // as we want to give best try on SYNC CACHE command. - retryCount = MAXIMUM_RETRIES; - timeoutValue = DeviceExtension->TimeOutValue; - break; - - case PowerDownDeviceFlushed: - { - // Case of issuing STOP UNIT command - // As "Imme" bit is set to '1', this command should be completed in short time. - // This command is at low importance, failure of this command has very small impact. - ULONG secondsRemaining = 0; - -#if (WINVER >= 0x0601) - // this API is introduced in Windows7 - PoQueryWatchdogTime(DeviceExtension->LowerPdo, &secondsRemaining); -#endif - - if (secondsRemaining == 0) - { - // not able to retrieve remaining time from PoQueryWatchdogTime API, use default values. - retryCount = MAXIMUM_RETRIES; - timeoutValue = SCSI_CDROM_TIMEOUT; - } - else - { - // plan to leave about 30 seconds to lower level drivers if possible. - if (secondsRemaining >= 32) - { - retryCount = (secondsRemaining - 30)/SCSI_CDROM_TIMEOUT + 1; - timeoutValue = SCSI_CDROM_TIMEOUT; - - if (retryCount > MAXIMUM_RETRIES) - { - retryCount = MAXIMUM_RETRIES; - } - - if (retryCount == 1) - { - timeoutValue = secondsRemaining - 30; - } - } - else - { - // issue the command with minimal timeout value and do not retry on it. - retryCount = 1; - timeoutValue = 2; - } - } - } - break; - default: - NT_ASSERT( FALSE ); - status = STATUS_NOT_IMPLEMENTED; - return status; - } - - DeviceExtension->PowerContext.RetryCount = retryCount; - - // issue command. - while (shouldRetry) - { - - // set SRB fields. - DeviceExtension->PowerContext.Srb.SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER | - SRB_FLAGS_DISABLE_SYNCH_TRANSFER | - SRB_FLAGS_NO_QUEUE_FREEZE | - SRB_FLAGS_BYPASS_LOCKED_QUEUE | - SRB_FLAGS_D3_PROCESSING; - - DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_EXECUTE_SCSI; - DeviceExtension->PowerContext.Srb.TimeOutValue = timeoutValue; - - if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceInitial) - { - DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_LOCK_QUEUE; - } - else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceLocked) - { - DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_QUIESCE_DEVICE; - } - else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced) - { - // Case of issuing SYNC CACHE command. - DeviceExtension->PowerContext.Srb.CdbLength = 10; - cdb->SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE; - } - else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceFlushed) - { - // Case of issuing STOP UNIT command. - DeviceExtension->PowerContext.Srb.CdbLength = 6; - cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT; - cdb->START_STOP.Start = 0; - cdb->START_STOP.Immediate = 1; - } - else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceStopped) - { - DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_UNLOCK_QUEUE; - } - - // Set up completion routine and context if requested - if (CompletionRoutine) - { - WdfRequestSetCompletionRoutine(DeviceExtension->PowerContext.PowerRequest, - CompletionRoutine, - Context); - } - - status = RequestSend(DeviceExtension, - DeviceExtension->PowerContext.PowerRequest, - DeviceExtension->IoTarget, - CompletionRoutine ? 0 : WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - &requestSent); - - if (requestSent) - { - if ((CompletionRoutine == NULL) && - (SRB_STATUS(DeviceExtension->PowerContext.Srb.SrbStatus) != SRB_STATUS_SUCCESS)) - { - TracePrint((TRACE_LEVEL_ERROR, - TRACE_FLAG_POWER, - "%p\tError occured when issuing %s command to device. Srb %p, Status %x\n", - DeviceExtension->PowerContext.PowerRequest, - (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced) ? "SYNC CACHE" : "STOP UNIT", - &DeviceExtension->PowerContext.Srb, - DeviceExtension->PowerContext.Srb.SrbStatus)); - - NT_ASSERT(!(TEST_FLAG(DeviceExtension->PowerContext.Srb.SrbStatus, SRB_STATUS_QUEUE_FROZEN))); - - shouldRetry = RequestSenseInfoInterpret(DeviceExtension, - DeviceExtension->PowerContext.PowerRequest, - &(DeviceExtension->PowerContext.Srb), - retryCount - DeviceExtension->PowerContext.RetryCount, - &status, - &(DeviceExtension->PowerContext.RetryIntervalIn100ns)); - - if (shouldRetry && (DeviceExtension->PowerContext.RetryCount-- == 0)) - { - shouldRetry = FALSE; - } - } - else - { - // succeeded, do not need to retry. - shouldRetry = FALSE; - } - - } - else - { - // request failed to be sent - shouldRetry = FALSE; - } - - if (shouldRetry) - { - LARGE_INTEGER t; - t.QuadPart = -DeviceExtension->PowerContext.RetryIntervalIn100ns; - KeDelayExecutionThread(KernelMode, FALSE, &t); - - status = PowerContextReuseRequest(DeviceExtension); - if (!NT_SUCCESS(status)) - { - shouldRetry = FALSE; - } - } - } - - if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced) - { - // record SYNC CACHE command completion time stamp. - KeQueryTickCount(&DeviceExtension->PowerContext.Step1CompleteTime); - } - - return status; -} - -NTSTATUS -RequestSend( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET IoTarget, - _In_ ULONG Flags, - _Out_opt_ PBOOLEAN RequestSent - ) -/*++ - -Routine Description: - - Send the request to the target, wake up the device from Zero Power state if necessary. - -Arguments: - - DeviceExtension - device extension - Request - the request to be sent - IoTarget - target of the above request - Flags - flags for the operation - RequestSent - optional, if the request was sent - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - BOOLEAN requestSent = FALSE; - WDF_REQUEST_SEND_OPTIONS options; - - UNREFERENCED_PARAMETER(DeviceExtension); - - if ((DeviceExtension->ZeroPowerODDInfo != NULL) && - (DeviceExtension->ZeroPowerODDInfo->InZeroPowerState != FALSE)) - { - } - - // Now send down the request - if (NT_SUCCESS(status)) - { - WDF_REQUEST_SEND_OPTIONS_INIT(&options, Flags); - - RequestSetSentTime(Request); - - // send request and check status - - // Disable SDV warning about infinitely waiting in caller's context: - // 1. Some requests (such as SCSI_PASS_THROUGH, contains buffer from user space) need to be sent down in caller’s context. - // Consequently, these requests wait in caller’s context until they are allowed to be sent down. - // 2. Considering the situation that during sleep, a request can be hold by storage port driver. When system resumes, any time out value (if we set using KMDF time out value) might be expires. - // This will cause the waiting request being failed (behavior change). We’d rather not set time out value. - - _Analysis_assume_(options.Timeout != 0); - requestSent = WdfRequestSend(Request, IoTarget, &options); - _Analysis_assume_(options.Timeout == 0); - - // If WdfRequestSend fails, or if the WDF_REQUEST_SEND_OPTION_SYNCHRONOUS flag is set, - // the driver can call WdfRequestGetStatus immediately after calling WdfRequestSend. - if ((requestSent == FALSE) || - (Flags & WDF_REQUEST_SEND_OPTION_SYNCHRONOUS)) - { - status = WdfRequestGetStatus(Request); - - if (requestSent == FALSE) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "WdfRequestSend failed: %lx\n", - status - )); - } - } - else - { - status = STATUS_SUCCESS; - } - - if (RequestSent != NULL) - { - *RequestSent = requestSent; - } - } - - return status; -} - diff --git a/storage/class/cdrom/src/data.c b/storage/class/cdrom/src/data.c deleted file mode 100644 index 72ec53b85..000000000 --- a/storage/class/cdrom/src/data.c +++ /dev/null @@ -1,283 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - -Abstract: - - -Environment: - - -Notes: - -Revision History: - ---*/ - -#include "ntddk.h" -#include "cdrom.h" - - -#ifdef ALLOC_DATA_PRAGMA -#pragma data_seg("PAGEDATA") -#endif - -/* - -#define CDROM_HACK_DEC_RRD (0x00000001) -#define CDROM_HACK_FUJITSU_FMCD_10x (0x00000002) - #define CDROM_HACK_HITACHI_1750 (0x00000004) - obsolete. -#define CDROM_HACK_HITACHI_GD_2000 (0x00000008) -#define CDROM_HACK_TOSHIBA_SD_W1101 (0x00000010) - #define CDROM_HACK_TOSHIBA_XM_3xx (0x00000020) - obsolete. -#define CDROM_HACK_NEC_CDDA (0x00000040) -#define CDROM_HACK_PLEXTOR_CDDA (0x00000080) -#define CDROM_HACK_BAD_GET_CONFIG_SUPPORT (0x00000100) -#define CDROM_HACK_FORCE_READ_CD_DETECTION (0x00000200) -#define CDROM_HACK_READ_CD_SUPPORTED (0x00000400) - -*/ - -CDROM_SCAN_FOR_SPECIAL_INFO CdromHackItems[] = { - // digital put out drives using 512 byte block sizes, - // and needed us to send a mode page to set the sector - // size back to 2048. - { "DEC" , "RRD" , NULL, 0x0001 }, - // these fujitsu drives take longer than ten seconds to - // timeout commands when audio discs are placed in them - { "FUJITSU" , "FMCD-101" , NULL, 0x0002 }, - { "FUJITSU" , "FMCD-102" , NULL, 0x0002 }, - // these hitachi drives don't work properly in PIO mode - //{ "HITACHI ", "CDR-1750S" , NULL, 0x0004 }, - //{ "HITACHI ", "CDR-3650/1650S" , NULL, 0x0004 }, - // this particular gem doesn't automatcially spin up - // on some media access commands. - { "" , "HITACHI GD-2000" , NULL, 0x0008 }, - { "" , "HITACHI DVD-ROM GD-2000" , NULL, 0x0008 }, - // this particular drive doesn't support DVD playback. - // just print an error message in CHK builds. - { "TOSHIBA ", "SD-W1101 DVD-RAM" , NULL, 0x0010 }, - // not sure what this device's issue was. seems to - // require mode selects at various times. - //{ "TOSHIBA ", "CD-ROM XM-3" , NULL, 0x0020 }, - // NEC defined a "READ_CD" type command before there was - // a standard, so fall back on this as an option. - { "NEC" , NULL , NULL, 0x0040 }, - // plextor defined a "READ_CD" type command before there was - // a standard, so fall back on this as an option. - { "PLEXTOR ", NULL , NULL, 0x0080 }, - // this drive times out and sometimes disappears from the bus - // when send GET_CONFIGURATION commands. don't send them. - { "" , "LG DVD-ROM DRD-840B" , NULL, 0x0100 }, - { "" , "SAMSUNG DVD-ROM SD-608" , NULL, 0x0300 }, - // these drives should have supported READ_CD, but at least - // some firmware revisions did not. force READ_CD detection. - { "" , "SAMSUNG DVD-ROM SD-" , NULL, 0x0200 }, - // the mitsumi drive below doesn't follow the block-only spec, - // and we end up hanging when sending it commands it doesn't - // understand. this causes complications later, also. - { "MITSUMI ", "CR-4802TE " , NULL, 0x0100 }, - // some drives return various funky errors (such as 3/2/0 NO_SEEK_COMPLETE) - // during the detection of READ_CD support, resulting in iffy detection. - // since they probably don't support mode switching, which is really old - // legacy stuff anyways, the ability to read digitally is lost when - // these drives return unexpected error codes. note: MMC compliant drives - // are presumed to support READ_CD, as are DVD drives, and anything - // connected to a bus type other than IDE or SCSI, and therefore don't - // need to be here. - { "YAMAHA ", "CRW8424S " , NULL, 0x0400 }, - // Polling frequently on virtual optical devices created by Hyper-V will - // cause a significant perf / power hit. These devices need to be polled - // less frequently for device state changes. - { "MSFT ", NULL , NULL, 0x2000 }, - // and finally, a place to finish the list. :) - { NULL , NULL , NULL, 0x0000 } -}; - -CDROM_SCAN_FOR_SPECIAL_INFO CdRomBadItems[] = { // Type (HH, slim) + WHQL Date, if known - { "" , "MITSUMI CD-ROM FX240" , NULL , 0x02 }, - { "" , "MITSUMI CD-ROM FX320" , NULL , 0x02 }, - { "" , "MITSUMI CD-ROM FX322" , NULL , 0x02 }, - { "" , "TEAC DV-28E-A" , "2.0A", 0x02 }, - { "" , "HP CD-Writer cd16h" , "Q000", 0x02 }, - { "" , "_NEC NR-7800A" , "1.33", 0x02 }, - { "" , "COMPAQ CRD-8481B" , NULL , 0x04 }, - // The following is a list of device that report too many OpChange/Add events. - // They require ignoring (or not sending) the OpChange flag in the GESN command. - // This list contains vendor ID and product ID as separate strings for USB/1394 interface. - { "HL-DT-ST", "DVDRAM GMA-4020B" , NULL , 0x10 }, // hh , 2002/04/22 - { "HL-DT-ST", "DVD-RW GCA-4020B" , NULL , 0x10 }, // hh , 2002/05/14 - { "HL-DT-ST", "DVDRAM GSA-4040B" , NULL , 0x10 }, // hh , 2003/05/06 - { "HL-DT-ST", "DVDRAM GMA-4040B" , NULL , 0x10 }, // hh , 2003/07/27 - { "HL-DT-ST", "DVD-RW GWA-4040B" , NULL , 0x10 }, // hh , 2003/11/18 - { "HL-DT-ST", "DVDRAM GSA-4081B" , NULL , 0x10 }, // hh , 2003/11/06 - { "HL-DT-ST", "DVDRAM GSA-4082B" , NULL , 0x10 }, // hh , 2004/01/27 - { "HL-DT-ST", "DVD-RW GWA-4082B" , NULL , 0x10 }, // hh , 2004/03/11 - { "HL-DT-ST", "DVDRAM GSA-4120B" , NULL , 0x10 }, // hh , 2004/05/16 - { "HL-DT-ST", "DVD+RW GRA-4120B" , NULL , 0x10 }, // hh , 2004/04/28 - { "HL-DT-ST", "DVDRAM GSA-4160B" , NULL , 0x10 }, // hh , 2004/08/12 - { "HL-DT-ST", "DVD-RW GWA-4160B" , NULL , 0x10 }, // hh , 2004/08/24 - { "HL-DT-ST", "DVDRAM GSA-4163B" , NULL , 0x10 }, // hh , 2004/11/09 - { "HL-DT-ST", "DVD-RW GWA-4163B" , NULL , 0x10 }, // hh , 2004/12/29 - { "HL-DT-ST", "DVDRAM GSA-4165B" , NULL , 0x10 }, // hh , 2005/06/09 - { "HL-DT-ST", "DVDRAM_GSA-4165B" , NULL , 0x10 }, // hh , 2005/06/28 - { "HL-DT-ST", "DVD-RW GWA-4165B" , NULL , 0x10 }, // hh , 2005/08/23 - { "HL-DT-ST", "DVDRAM GSA-4167B" , NULL , 0x10 }, // hh , 2005/07/01 - { "HL-DT-ST", "DVDRAM GSA-H10N" , NULL , 0x10 }, // hh , 2006/02/16 - { "HL-DT-ST", "DVDRAM_GSA-H10N" , NULL , 0x10 }, // hh , 2006/02/16 - { "HL-DT-ST", "DVDRAM GSA-H10L" , NULL , 0x10 }, // hh , 2006/02/27 - { "HL-DT-ST", "DVDRAM_GSA-H10L" , NULL , 0x10 }, // hh , 2006/04/21 - { "HL-DT-ST", "DVDRAM GSA-H10A" , NULL , 0x10 }, // hh , 2006/01/03 - { "HL-DT-ST", "DVDRAM_GSA-H10A" , NULL , 0x10 }, // hh , 2006/05/14 - { "HL-DT-ST", "DVD-RW GSA-H11N" , NULL , 0x10 }, // hh , 2006/04/28 - { "HL-DT-ST", "DVD-RW_GSA-H11N" , NULL , 0x10 }, // hh , 2006/02/22 - - { "HL-DT-ST", "DVDRAM GSA-4080N" , NULL , 0x10 }, // slim, 2004/08/08 - { "HL-DT-ST", "DVDRAM GMA-4080N" , NULL , 0x10 }, // slim, 2004/11/09 - { "HL-DT-ST", "DVD-RW GCA-4080N" , NULL , 0x10 }, // slim, 2004/11/22 - { "HL-DT-ST", "DVD-RW GWA-4080N" , NULL , 0x10 }, // slim, 2004/08/17 - { "HL-DT-ST", "DVDRAM GSA-4082N" , NULL , 0x10 }, // slim, 2005/07/12 - { "HL-DT-ST", "DVDRAM_GSA-4082N" , NULL , 0x10 }, // slim, 2005/09/21 - { "HL-DT-ST", "DVDRAM GMA-4082N" , NULL , 0x10 }, // slim, 2005/10/20 - { "HL-DT-ST", "DVD-RW GRA-4082N" , NULL , 0x10 }, // slim, 2006/06/07 - { "HL-DT-ST", "DVD-RW GWA-4082N" , NULL , 0x10 }, // slim, 2005/05/24 - { "HL-DT-ST", "DVDRAM GMA4082Nf" , NULL , 0x10 }, // slim, 2006/02/28 - { "HL-DT-ST", "DVDRAM GMA4082Nj" , NULL , 0x10 }, // slim, 2006/01/26 - - { "HL-DT-ST", "DVDRAM GSA-4084N" , NULL , 0x10 }, // slim, 2005/12/21 - { "HL-DT-ST", "DVDRAM GMA-4084N" , NULL , 0x10 }, // slim, 2006/02/15 - { "HP" , "DVD Writer 550s" , NULL , 0x10 }, // slim, 2006/05/08 - { "HL-DT-ST", "DVDRAM GSA-T10N" , NULL , 0x10 }, // slim, 2006/07/26 - { "HL-DT-ST", "DVDRAM_GSA-T10N" , NULL , 0x10 }, // slim, 2006/07/26 - { "HL-DT-ST", "DVD+-RW GSA-T11N" , NULL , 0x10 }, // slim, 2006/07/25 - - { "HL-DT-ST", "DVD-ROM GDR8160B" , NULL , 0x10 }, // hh , 2001/10/12 - { "COMPAQ" , "DVD-ROM GDR8160B" , NULL , 0x10 }, // hh , 2001/11/08 - { "HL-DT-ST", "DVD-ROM GDR8161B" , NULL , 0x10 }, // hh , 2002/07/19 - { "HL-DT-ST", "DVD-ROM GDR8162B" , NULL , 0x10 }, // hh , 2003/04/22 - { "HL-DT-ST", "DVD-ROM GDR8163B" , NULL , 0x10 }, // hh , 2004/05/19 - { "HL-DT-ST", "DVD-ROM GDR8164B" , NULL , 0x10 }, // hh , 2005/06/29 - { "HL-DT-ST", "DVD-ROM GDRH10N" , NULL , 0x10 }, // hh , 2006/03/07 - - { "HL-DT-ST", "DVD-ROM GDR8081N" , NULL , 0x10 }, // slim, 2001/08/27 - { "HL-DT-ST", "DVD-ROM GDR8082N" , NULL , 0x10 }, // slim, 2003/02/02 - { "HL-DT-ST", "DVD-ROM GDR8083N" , NULL , 0x10 }, // slim, 2003/02/02 - { "HL-DT-ST", "DVD-ROM GDR8085N" , NULL , 0x10 }, // slim, 2005/11/10 - - { "HL-DT-ST", "RW/DVD GCC-4080N" , NULL , 0x10 }, // slim, 2001/08/21 - { "HL-DT-ST", "RW/DVD_GCC-4080N" , NULL , 0x10 }, // slim, - { "HL-DT-ST", "RW/DVD GCC-4160N" , NULL , 0x10 }, // slim, 2002/04/08 - { "HL-DT-ST", "RW/DVD GCC-4240N" , NULL , 0x10 }, // slim, 2002/04/26 - { "HL-DT-ST", "RW/DVD GCC-4241N" , NULL , 0x10 }, // slim, 2003/04/07 - { "HL-DT-ST", "RW/DVD_GCC-4241N" , NULL , 0x10 }, // slim, 2004/03/07 - { "HL-DT-ST", "RW/DVD GCC-4242N" , NULL , 0x10 }, // slim, 2003/12/21 - { "HL-DT-ST", "RW/DVD GCC-4246N" , NULL , 0x10 }, // slim, 2005/05/23 - { "HL-DT-ST", "BD-RE GBW-H10N" , NULL , 0x10 }, // hh , 2006/06/27 - - { "HL-DT-ST", "DVDRAM GSA-4083N" , NULL , 0x10 }, // hh , 2006/05/17 - { "HL-DT-ST", "DVD+-RW GWA4083N" , NULL , 0x10 }, // hh , 2006/06/05 - - { "PIONEER", "DVD-RW DVR-106D" , NULL , 0x10 }, // hh , ? - { "ASUS", "DVD-RW DRW-0402P" , NULL , 0x10 }, // hh , ? - - // - // This list contains devices that claims to support asynchronous notification, but - // doesn't handle it well (e.g., some TSST devices will not report media removal if - // the GESN command is sent down immediately after the AN interrupt, they need some - // time in between to be able to correctly report media removal). - // - - { "TSSTcorp", "CDDVDW SN-S083A" , "SB00", 0x40 }, // slim, ? - - // - // This list contains vendor ID and product ID as a single string for ATAPI interface. - // - - { "", "HL-DT-ST DVDRAM GMA-4020B" , NULL , 0x10 }, // hh , 2002/04/22 - { "", "HL-DT-ST DVD-RW GCA-4020B" , NULL , 0x10 }, // hh , 2002/05/14 - { "", "HL-DT-ST DVDRAM GSA-4040B" , NULL , 0x10 }, // hh , 2003/05/06 - { "", "HL-DT-ST DVDRAM GMA-4040B" , NULL , 0x10 }, // hh , 2003/07/27 - { "", "HL-DT-ST DVD-RW GWA-4040B" , NULL , 0x10 }, // hh , 2003/11/18 - { "", "HL-DT-ST DVDRAM GSA-4081B" , NULL , 0x10 }, // hh , 2003/11/06 - { "", "HL-DT-ST DVDRAM GSA-4082B" , NULL , 0x10 }, // hh , 2004/01/27 - { "", "HL-DT-ST DVD-RW GWA-4082B" , NULL , 0x10 }, // hh , 2004/03/11 - { "", "HL-DT-ST DVDRAM GSA-4120B" , NULL , 0x10 }, // hh , 2004/05/16 - { "", "HL-DT-ST DVD+RW GRA-4120B" , NULL , 0x10 }, // hh , 2004/04/28 - { "", "HL-DT-ST DVDRAM GSA-4160B" , NULL , 0x10 }, // hh , 2004/08/12 - { "", "HL-DT-ST DVD-RW GWA-4160B" , NULL , 0x10 }, // hh , 2004/08/24 - { "", "HL-DT-ST DVDRAM GSA-4163B" , NULL , 0x10 }, // hh , 2004/11/09 - { "", "HL-DT-ST DVD-RW GWA-4163B" , NULL , 0x10 }, // hh , 2004/12/29 - { "", "HL-DT-ST DVDRAM GSA-4165B" , NULL , 0x10 }, // hh , 2005/06/09 - { "", "HL-DT-ST DVDRAM_GSA-4165B" , NULL , 0x10 }, // hh , 2005/06/28 - { "", "HL-DT-ST DVD-RW GWA-4165B" , NULL , 0x10 }, // hh , 2005/08/23 - { "", "HL-DT-ST DVDRAM GSA-4167B" , NULL , 0x10 }, // hh , 2005/07/01 - { "", "HL-DT-ST DVDRAM GSA-H10N" , NULL , 0x10 }, // hh , 2006/02/16 - { "", "HL-DT-ST DVDRAM_GSA-H10N" , NULL , 0x10 }, // hh , 2006/02/16 - { "", "HL-DT-ST DVDRAM GSA-H10L" , NULL , 0x10 }, // hh , 2006/02/27 - { "", "HL-DT-ST DVDRAM_GSA-H10L" , NULL , 0x10 }, // hh , 2006/04/21 - { "", "HL-DT-ST DVDRAM GSA-H10A" , NULL , 0x10 }, // hh , 2006/01/03 - { "", "HL-DT-ST DVDRAM_GSA-H10A" , NULL , 0x10 }, // hh , 2006/05/14 - { "", "HL-DT-ST DVD-RW GSA-H11N" , NULL , 0x10 }, // hh , 2006/04/28 - { "", "HL-DT-ST DVD-RW_GSA-H11N" , NULL , 0x10 }, // hh , 2006/02/22 - - { "", "HL-DT-ST DVDRAM GSA-4080N" , NULL , 0x10 }, // slim, 2004/08/08 - { "", "HL-DT-ST DVDRAM GMA-4080N" , NULL , 0x10 }, // slim, 2004/11/09 - { "", "HL-DT-ST DVD-RW GCA-4080N" , NULL , 0x10 }, // slim, 2004/11/22 - { "", "HL-DT-ST DVD-RW GWA-4080N" , NULL , 0x10 }, // slim, 2004/08/17 - { "", "HL-DT-ST DVDRAM GSA-4082N" , NULL , 0x10 }, // slim, 2005/07/12 - { "", "HL-DT-ST DVDRAM_GSA-4082N" , NULL , 0x10 }, // slim, 2005/09/21 - { "", "HL-DT-ST DVDRAM GMA-4082N" , NULL , 0x10 }, // slim, 2005/10/20 - { "", "HL-DT-ST DVD-RW GRA-4082N" , NULL , 0x10 }, // slim, 2006/06/07 - { "", "HL-DT-ST DVD-RW GWA-4082N" , NULL , 0x10 }, // slim, 2005/05/24 - { "", "HL-DT-ST DVDRAM GMA4082Nf" , NULL , 0x10 }, // slim, 2006/02/28 - { "", "HL-DT-ST DVDRAM GMA4082Nj" , NULL , 0x10 }, // slim, 2006/01/26 - - { "", "HL-DT-ST DVDRAM GSA-4084N" , NULL , 0x10 }, // slim, 2005/12/21 - { "", "HL-DT-ST DVDRAM GMA-4084N" , NULL , 0x10 }, // slim, 2006/02/15 - { "", "HP DVD Writer 550s" , NULL , 0x10 }, // slim, 2006/05/08 - { "", "HL-DT-ST DVDRAM GSA-T10N" , NULL , 0x10 }, // slim, 2006/07/26 - { "", "HL-DT-ST DVDRAM_GSA-T10N" , NULL , 0x10 }, // slim, 2006/07/26 - { "", "HL-DT-ST DVD+-RW GSA-T11N" , NULL , 0x10 }, // slim, 2006/07/25 - - { "", "HL-DT-ST DVD-ROM GDR8160B" , NULL , 0x10 }, // hh , 2001/10/12 - { "", "COMPAQ DVD-ROM GDR8160B" , NULL , 0x10 }, // hh , 2001/11/08 - { "", "HL-DT-ST DVD-ROM GDR8161B" , NULL , 0x10 }, // hh , 2002/07/19 - { "", "HL-DT-ST DVD-ROM GDR8162B" , NULL , 0x10 }, // hh , 2003/04/22 - { "", "HL-DT-ST DVD-ROM GDR8163B" , NULL , 0x10 }, // hh , 2004/05/19 - { "", "HL-DT-ST DVD-ROM GDR8164B" , NULL , 0x10 }, // hh , 2005/06/29 - { "", "HL-DT-ST DVD-ROM GDRH10N" , NULL , 0x10 }, // hh , 2006/03/07 - - { "", "HL-DT-ST DVD-ROM GDR8081N" , NULL , 0x10 }, // slim, 2001/08/27 - { "", "HL-DT-ST DVD-ROM GDR8082N" , NULL , 0x10 }, // slim, 2003/02/02 - { "", "HL-DT-ST DVD-ROM GDR8083N" , NULL , 0x10 }, // slim, 2003/02/02 - { "", "HL-DT-ST DVD-ROM GDR8085N" , NULL , 0x10 }, // slim, 2005/11/10 - - { "", "HL-DT-ST RW/DVD GCC-4080N" , NULL , 0x10 }, // slim, 2001/08/21 - { "", "HL-DT-ST RW/DVD_GCC-4080N" , NULL , 0x10 }, // slim, - { "", "HL-DT-ST RW/DVD GCC-4160N" , NULL , 0x10 }, // slim, 2002/04/08 - { "", "HL-DT-ST RW/DVD GCC-4240N" , NULL , 0x10 }, // slim, 2002/04/26 - { "", "HL-DT-ST RW/DVD GCC-4241N" , NULL , 0x10 }, // slim, 2003/04/07 - { "", "HL-DT-ST RW/DVD_GCC-4241N" , NULL , 0x10 }, // slim, 2004/03/07 - { "", "HL-DT-ST RW/DVD GCC-4242N" , NULL , 0x10 }, // slim, 2003/12/21 - { "", "HL-DT-ST RW/DVD GCC-4246N" , NULL , 0x10 }, // slim, 2005/05/23 - { "", "HL-DT-ST BD-RE GBW-H10N" , NULL , 0x10 }, // hh , 2006/06/27 - - { "", "HL-DT-ST DVDRAM GSA-4083N" , NULL , 0x10 }, // hh , 2006/05/17 - { "", "HL-DT-ST DVD+-RW GWA4083N" , NULL , 0x10 }, // hh , 2006/06/05 - - { "", "PIONEER DVD-RW DVR-106D" , NULL , 0x10 }, // hh , ? - { "", "ASUS DVD-RW DRW-0402P" , NULL , 0x10 }, // hh , ? - - - // Sony sourced some drives from LG also.... - - { NULL , NULL , NULL , 0x00 }, -}; - - -#ifdef ALLOC_DATA_PRAGMA -#pragma data_seg() -#endif diff --git a/storage/class/cdrom/src/guid.c b/storage/class/cdrom/src/guid.c deleted file mode 100644 index 8af1f877f..000000000 --- a/storage/class/cdrom/src/guid.c +++ /dev/null @@ -1,16 +0,0 @@ -/*-- -Copyright (C) Microsoft Corporation. All rights reserved. ---*/ - -#include "initguid.h" -#include "ntddk.h" -#include "ntddstor.h" -#include "mountmgr.h" -#include "ioevent.h" -#include "devpkey.h" -#include "wdmguid.h" - -// no code, just GUIDs being defined - - - diff --git a/storage/class/cdrom/src/init.c b/storage/class/cdrom/src/init.c deleted file mode 100644 index 0dc176fda..000000000 --- a/storage/class/cdrom/src/init.c +++ /dev/null @@ -1,2740 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - init.c - -Abstract: - - Initialization routines for CDROM - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - - -#include "ntddk.h" -#include "ntddstor.h" -#include "ntstrsafe.h" -#include "devpkey.h" - -#include "cdrom.h" -#include "scratch.h" -#include "mmc.h" - -#ifdef DEBUG_USE_WPP -#include "init.tmh" -#endif - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitAllocateBuffers( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveScsiAddress( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_ADDRESS ScsiAddress - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveDescriptorsAndTransferLength( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceScanSpecialDevices( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitMmcContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetMmcSupportInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN IsMmcDevice - ); - -#if (NTDDI_VERSION >= NTDDI_WIN8) -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceIsPortable( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN IsPortable - ); -#endif - - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceClaimRelease) -#pragma alloc_text(PAGE, DeviceEvtSelfManagedIoInit) - -#pragma alloc_text(PAGE, DeviceInitReleaseQueueContext) -#pragma alloc_text(PAGE, DeviceInitAllocateBuffers) -#pragma alloc_text(PAGE, DeviceInitPowerContext) -#pragma alloc_text(PAGE, DeviceCreateWellKnownName) -#pragma alloc_text(PAGE, DeviceRetrieveScsiAddress) -#pragma alloc_text(PAGE, DeviceRetrieveDescriptorsAndTransferLength) -#pragma alloc_text(PAGE, DeviceInitializeHotplugInfo) -#pragma alloc_text(PAGE, DeviceScanSpecialDevices) -#pragma alloc_text(PAGE, DeviceGetTimeOutValueFromRegistry) -#pragma alloc_text(PAGE, DeviceGetMmcSupportInfo) -#pragma alloc_text(PAGE, DeviceRetrieveDescriptor) -#pragma alloc_text(PAGE, DeviceRetrieveHackFlagsFromRegistry) -#pragma alloc_text(PAGE, DeviceScanForSpecial) -#pragma alloc_text(PAGE, DeviceHackFlagsScan) -#pragma alloc_text(PAGE, DeviceInitMmcContext) -#pragma alloc_text(PAGE, ScanForSpecialHandler) -#pragma alloc_text(PAGE, DeviceSetRawReadInfo) -#pragma alloc_text(PAGE, DeviceInitializeDvd) -#pragma alloc_text(PAGE, DeviceCacheDeviceInquiryData) - -#if (NTDDI_VERSION >= NTDDI_WIN8) -#pragma alloc_text(PAGE, DeviceIsPortable) -#endif - -#endif - -#pragma warning(push) -#pragma warning(disable:4152) // nonstandard extension, function/data pointer conversion in expression -#pragma warning(disable:26000) // read overflow reported because of pointer type conversion - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceClaimRelease( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN Release - ) -/*++ - -Routine Description: - - This function claims a device in the port driver. The port driver object - is updated with the correct driver object if the device is successfully - claimed. - -Arguments: - - Device - The WDFDEVICE that needs to be claimed or released. - - Release - Indicates the logical unit should be released rather than claimed. - -Return Value: - - Returns a status indicating success or failure of the operation. - ---*/ -{ - NTSTATUS status; - SCSI_REQUEST_BLOCK srb = {0}; - WDF_MEMORY_DESCRIPTOR descriptor; - WDFREQUEST request; - WDF_OBJECT_ATTRIBUTES attributes; - - PAGED_CODE(); - - //Create a request - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - - status = WdfRequestCreate(&attributes, - DeviceExtension->IoTarget, - &request); - - if (NT_SUCCESS(status)) - { - //fill up srb structure - srb.OriginalRequest = WdfRequestWdmGetIrp(request); - NT_ASSERT(srb.OriginalRequest != NULL); - - srb.Length = sizeof(SCSI_REQUEST_BLOCK); - - srb.Function = Release - ? SRB_FUNCTION_RELEASE_DEVICE - : SRB_FUNCTION_CLAIM_DEVICE; - - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&descriptor, - &srb, - sizeof(srb)); - - status = WdfIoTargetSendInternalIoctlOthersSynchronously(DeviceExtension->IoTarget, - request, - IOCTL_SCSI_EXECUTE_NONE, - &descriptor, - NULL, - NULL, - NULL, - NULL); - - NT_ASSERT(!TEST_FLAG(srb.SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER)); - - // The request should be deleted. - WdfObjectDelete(request); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DeviceClaimRelease: Failed to %s device, status: 0x%X\n", - Release ? "Release" : "Claim", - status)); - } - } - else - { - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_PNP, - "DeviceClaimRelease: Failed to create request, status: 0x%X\n", - status)); - } - - if (Release) - { - // We only release the device when we don't want to manage it. - // The failure status does not matter. - status = STATUS_SUCCESS; - } - - return status; -} // end DeviceClaimRelease() - - -NTSTATUS -DeviceEvtSelfManagedIoInit( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine is called only once after the device is added in system, so it's used to do - hardware-dependent device initialization work and resource allocation. - If this routine fails, DeviceEvtSelfManagedIoCleanup will be invoked by the framework. - -Arguments: - - Device - Handle to device object - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - - PAGED_CODE(); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_PNP, - "DeviceEvtSelfManagedIoInit: WDFDEVICE %p is being started.\n", - Device)); - - deviceExtension = DeviceGetExtension(Device); - - // 1. Set/retrieve basic information, some of the following operations may depend on it - if (NT_SUCCESS(status)) - { - // We do not care if this function fails, SCSI address is mainly for debugging/tracing purposes. - (VOID) DeviceRetrieveScsiAddress(deviceExtension, &deviceExtension->ScsiAddress); - } - - if (NT_SUCCESS(status)) - { - status = DeviceRetrieveDescriptorsAndTransferLength(deviceExtension); - } - - if (NT_SUCCESS(status)) - { - // This function should be called after DeviceRetrieveDescriptorsAndTransferLength() - // It depends on MaxTransferLenth fields. - status = DeviceInitAllocateBuffers(deviceExtension); - } - - // 2. The following functions depend on the allocated buffers. - - // perf re-enable after failing. Q: Is this one used by cdrom.sys? - if (NT_SUCCESS(status)) - { - // allow perf to be re-enabled after a given number of failed IOs - // require this number to be at least CLASS_PERF_RESTORE_MINIMUM - ULONG t = CLASS_PERF_RESTORE_MINIMUM; - - DeviceGetParameter(deviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_PERF_RESTORE_VALUE_NAME, - &t); - if (t >= CLASS_PERF_RESTORE_MINIMUM) - { - deviceExtension->PrivateFdoData->Perf.ReEnableThreshhold = t; - } - } - - // 3. Retrieve information about special devices and hack flags. - if (NT_SUCCESS(status)) - { - DeviceRetrieveHackFlagsFromRegistry(deviceExtension); - // scan for bad items. - DeviceScanForSpecial(deviceExtension, CdRomBadItems, DeviceHackFlagsScan); - // Check to see if it's a special device that needs special error process. - DeviceScanSpecialDevices(deviceExtension); // may send command to device - } - - // 4. Initialize the hotplug information only after the ScanForSpecial routines, - // as it relies upon the hack flags - deviceExtension->PrivateFdoData->HackFlags. - if (NT_SUCCESS(status)) - { - status = DeviceInitializeHotplugInfo(deviceExtension); - } - - if (NT_SUCCESS(status)) - { - // cache the device's inquiry data - status = DeviceCacheDeviceInquiryData(deviceExtension); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to cache the device's inquiry data, failng %!STATUS!\n", - status - )); - } - } - - // 5. Initialize MMC context, media change notification stuff and read media capacity - if (NT_SUCCESS(status)) - { - status = DeviceInitializeMediaChangeDetection(deviceExtension); - } - if (NT_SUCCESS(status)) - { - status = DeviceInitMmcContext(deviceExtension); - } - if (NT_SUCCESS(status)) - { - status = DeviceInitializeZPODD(deviceExtension); - } - if (NT_SUCCESS(status)) - { - // Do READ CAPACITY. This SCSI command returns the last sector address - // on the device and the bytes per sector. These are used to calculate - // the drive capacity in bytes. - status = MediaReadCapacity(Device); - - // If READ CAPACITY succeeded, we can safely conclude that there is a media present - if (NT_SUCCESS(status)) - { - DeviceSetMediaChangeStateEx(deviceExtension, - MediaPresent, - NULL); - } - - // READ CAPACITY is not critical for init, ignore all errors occuring during its execution - status = STATUS_SUCCESS; - } - - // 6. Perform DVD-specific initialization - if (NT_SUCCESS(status)) - { - status = DeviceInitializeDvd(Device); - } - - // 7. Miscellaneous initialization actions - if (NT_SUCCESS(status)) - { - if (deviceExtension->PrivateFdoData != NULL) - { - deviceExtension->PrivateFdoData->Perf.OriginalSrbFlags = deviceExtension->SrbFlags; - } - - if (deviceExtension->DeviceAdditionalData.Mmc.IsWriter) - { - // OPC can really take this long per IMAPIv1 timeout.... - deviceExtension->TimeOutValue = max(deviceExtension->TimeOutValue, SCSI_CDROM_OPC_TIMEOUT); - } - } - - // 8. Enable the main timer, create ARC name as needed - if (NT_SUCCESS(status)) - { - // Device successfully added and initialized, increase CdRomCount. - IoGetConfigurationInformation()->CdRomCount++; - - deviceExtension->IsInitialized = TRUE; - - DeviceEnableMainTimer(deviceExtension); - - } - -#if (NTDDI_VERSION >= NTDDI_WIN8) - // 9. Set volume interface properties - if (NT_SUCCESS(status)) - { - BOOLEAN isCritical = FALSE; - BOOLEAN isPortable = FALSE; - BOOLEAN isRemovable = TEST_FLAG(deviceExtension->DeviceObject->Characteristics, FILE_REMOVABLE_MEDIA); - DEVPROP_BOOLEAN propCritical = DEVPROP_FALSE; - DEVPROP_BOOLEAN propPortable = DEVPROP_FALSE; - DEVPROP_BOOLEAN propRemovable = DEVPROP_FALSE; - - status = DeviceIsPortable(deviceExtension, &isPortable); - - if (NT_SUCCESS(status)) - { - if (isPortable) { - SET_FLAG(deviceExtension->DeviceObject->Characteristics, FILE_PORTABLE_DEVICE); - } - - propPortable = isPortable ? DEVPROP_TRUE : DEVPROP_FALSE; - - status = IoSetDeviceInterfacePropertyData(&deviceExtension->MountedDeviceInterfaceName, - &DEVPKEY_Storage_Portable, - 0, - 0, - DEVPROP_TYPE_BOOLEAN, - sizeof(DEVPROP_BOOLEAN), - &propPortable); - } - - if (NT_SUCCESS(status)) - { - propRemovable = isRemovable ? DEVPROP_TRUE : DEVPROP_FALSE; - - status = IoSetDeviceInterfacePropertyData(&deviceExtension->MountedDeviceInterfaceName, - &DEVPKEY_Storage_Removable_Media, - 0, - 0, - DEVPROP_TYPE_BOOLEAN, - sizeof(DEVPROP_BOOLEAN), - &propRemovable); - } - - if (NT_SUCCESS(status)) - { - isCritical = TEST_FLAG(deviceExtension->DeviceObject->Flags, - (DO_SYSTEM_SYSTEM_PARTITION | - DO_SYSTEM_BOOT_PARTITION | - DO_SYSTEM_CRITICAL_PARTITION)); - - propCritical = isCritical ? DEVPROP_TRUE : DEVPROP_FALSE; - - status = IoSetDeviceInterfacePropertyData(&deviceExtension->MountedDeviceInterfaceName, - &DEVPKEY_Storage_System_Critical, - 0, - 0, - DEVPROP_TYPE_BOOLEAN, - sizeof(DEVPROP_BOOLEAN), - &propCritical); - } - - } -#endif - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitReleaseQueueContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Part of device initialize routine. Initialize ReleaseQueue related stuff. - -Arguments: - - DeviceExtension - device extension of WDFDEVICE. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDF_OBJECT_ATTRIBUTES attributes; - - PAGED_CODE(); - - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - attributes.ParentObject = DeviceExtension->Device; - - status = WdfRequestCreate(&attributes, - DeviceExtension->IoTarget, - &(DeviceExtension->ReleaseQueueRequest)); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, "Cannot create the release queue request\n")); - - return status; - } - - // Initialize ReleaseQueueInputMemory, a wrapper around ReleaseQueueSrb - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = DeviceExtension->ReleaseQueueRequest; - - status = WdfMemoryCreatePreallocated(&attributes, - &DeviceExtension->ReleaseQueueSrb, - sizeof(SCSI_REQUEST_BLOCK), - &DeviceExtension->ReleaseQueueInputMemory); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, "Failed to allocate ReleaseQueueSrb.\n")); - - return status; - } - - // Preformat the release queue request here to ensure that this call will never - // fail during an actual release of the queue. - if (NT_SUCCESS(status)) - { - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - DeviceExtension->ReleaseQueueRequest, - IOCTL_SCSI_EXECUTE_NONE, - DeviceExtension->ReleaseQueueInputMemory, - NULL, - NULL, - NULL, - NULL, - NULL); - } - - // Set a CompletionRoutine callback function for ReleaseQueueRequest. - if (NT_SUCCESS(status)) - { - WdfRequestSetCompletionRoutine(DeviceExtension->ReleaseQueueRequest, - DeviceReleaseQueueCompletion, - DeviceExtension->Device); - } - - // Create a spinlock for ReleaseQueueRequest - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = DeviceExtension->Device; - - status = WdfSpinLockCreate(&attributes, - &(DeviceExtension->ReleaseQueueSpinLock)); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, - "DeviceInitReleaseQueueContext: Cannot create the release queue spinlock\n")); - - return status; - } - - // Initialize miscellaneous ReleaseQueue related fields - DeviceExtension->ReleaseQueueNeeded = FALSE; - DeviceExtension->ReleaseQueueInProgress = FALSE; - DeviceExtension->ReleaseQueueSrb.Length = sizeof(SCSI_REQUEST_BLOCK); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitPowerContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Part of device initialize routine. Initialize PowerContext related stuff. - -Arguments: - - DeviceExtension - device extension of WDFDEVICE. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDF_OBJECT_ATTRIBUTES attributes; - - PAGED_CODE(); - - // create request object for Power operations - - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - attributes.ParentObject = DeviceExtension->Device; - - status = WdfRequestCreate(&attributes, - DeviceExtension->IoTarget, - &(DeviceExtension->PowerContext.PowerRequest) ); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, "Cannot create the power request object.\n")); - - return status; - } - - // Preformat the power request. With this being done, we never need to worry about - // WdfIoTargetFormatRequestForInternalIoctlOthers ever failing later. - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - DeviceExtension->PowerContext.PowerRequest, - IOCTL_SCSI_EXECUTE_IN, - NULL, NULL, - NULL, NULL, - NULL, NULL); - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceCreateWellKnownName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine creates a symbolic link to the cdrom device object - under \dosdevices. The number of the cdrom device does not neccessarily - match between \dosdevices and \device, but usually will be the same. - - Saves the buffer - -Arguments: - - DeviceObject - - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - UNICODE_STRING unicodeLinkName = {0}; - WCHAR wideLinkName[64] = {0}; - PWCHAR savedName; - - LONG cdromNumber = DeviceExtension->DeviceNumber; - - PAGED_CODE(); - - // if already linked, assert then return - if (DeviceExtension->DeviceAdditionalData.WellKnownName.Buffer != NULL) - { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, - "DeviceCreateWellKnownName: link already exists %p\n", - DeviceExtension->DeviceAdditionalData.WellKnownName.Buffer)); - - NT_ASSERT(FALSE); - - return STATUS_UNSUCCESSFUL; - } - - // find an unused CdRomNN to link to. - // It's doing this way because the same might be used for other device in another driver. - do - { - status = RtlStringCchPrintfW((NTSTRSAFE_PWSTR)wideLinkName, - RTL_NUMBER_OF(wideLinkName), - L"\\DosDevices\\CdRom%d", - cdromNumber); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, - "DeviceCreateWellKnownName: Format symbolic link failed with error: 0x%X\n", status)); - return status; - } - - RtlInitUnicodeString(&unicodeLinkName, wideLinkName); - - status = WdfDeviceCreateSymbolicLink(DeviceExtension->Device, - &unicodeLinkName); - - cdromNumber++; - - } while((status == STATUS_OBJECT_NAME_COLLISION) || - (status == STATUS_OBJECT_NAME_EXISTS)); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, - "DeviceCreateWellKnownName: Error %lx linking %wZ to " - "device %wZ\n", - status, - &unicodeLinkName, - &(DeviceExtension->DeviceName))); - return status; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceCreateWellKnownName: successfully linked %wZ " - "to device %wZ\n", - &unicodeLinkName, - &(DeviceExtension->DeviceName))); - - // Save away the symbolic link name in the driver data block. We need - // it so we can delete the link when the device is removed. - savedName = ExAllocatePool2(POOL_FLAG_PAGED, - unicodeLinkName.MaximumLength, - CDROM_TAG_STRINGS); - - if (savedName == NULL) - { - // Test Note: test path should excise here to see if the symbolic is deleted by framework. - // IoDeleteSymbolicLink(&unicodeLinkName); - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "DeviceCreateWellKnownName: unable to allocate memory.\n")); - - return STATUS_INSUFFICIENT_RESOURCES; - } - - RtlZeroMemory(savedName, unicodeLinkName.MaximumLength); - RtlCopyMemory(savedName, unicodeLinkName.Buffer, unicodeLinkName.MaximumLength); - - RtlInitUnicodeString(&(DeviceExtension->DeviceAdditionalData.WellKnownName), savedName); - - // the name was saved and the link created - - return STATUS_SUCCESS; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveScsiAddress( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_ADDRESS ScsiAddress - ) -/*++ - -Routine Description: - - retrieve SCSI address information and put into device extension - -Arguments: - - DeviceExtension - device context. - ScsiAddress - the buffer to put the scsi address info. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - WDF_MEMORY_DESCRIPTOR outputDescriptor; - - PAGED_CODE(); - - if ((DeviceExtension == NULL) || - (ScsiAddress == NULL)) - { - return STATUS_INVALID_PARAMETER; - } - - //Get IOTARGET for sending request to port driver. - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&outputDescriptor, - (PVOID)ScsiAddress, - sizeof(SCSI_ADDRESS)); - - status = WdfIoTargetSendIoctlSynchronously(DeviceExtension->IoTarget, - NULL, - IOCTL_SCSI_GET_ADDRESS, - NULL, - &outputDescriptor, - NULL, - NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "DeviceRetrieveScsiAddress: Get Address failed %lx\n", - status)); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetAddress: Port %x, Path %x, Target %x, Lun %x\n", - ScsiAddress->PortNumber, - ScsiAddress->PathId, - ScsiAddress->TargetId, - ScsiAddress->Lun)); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitAllocateBuffers( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Part of device initialize routine. - Allocate all buffers in Device Extension. - -Arguments: - - DeviceExtension - device extension of WDFDEVICE. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PVOID senseData = NULL; - - PAGED_CODE(); - - // allocate a private extension for class data - if (DeviceExtension->PrivateFdoData == NULL) - { - DeviceExtension->PrivateFdoData = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(CDROM_PRIVATE_FDO_DATA), - CDROM_TAG_PRIVATE_DATA); - } - - if (DeviceExtension->PrivateFdoData == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - // initialize the struct's various fields. - RtlZeroMemory(DeviceExtension->PrivateFdoData, sizeof(CDROM_PRIVATE_FDO_DATA)); - } - - // Allocate request sense buffer. - senseData = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - SENSE_BUFFER_SIZE, - CDROM_TAG_SENSE_INFO); - - if (senseData == NULL) - { - // The buffer cannot be allocated. - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - // Set the sense data pointer in the device extension. - DeviceExtension->SenseData = senseData; - } - - // Allocate scratch buffer -- Must occur after determining - // max transfer size, but before other CD specific detection - // (which relies upon this buffer). - if (!ScratchBuffer_Allocate(DeviceExtension)) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch buffer, failing %!STATUS!\n", - status - )); - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveDescriptorsAndTransferLength( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Part of device initialize routine. - Retrieve Device Descriptor and Adaptor Descriptor. - -Arguments: - - DeviceExtension - device extension of WDFDEVICE. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - STORAGE_PROPERTY_ID propertyId; - - PAGED_CODE(); - - if (NT_SUCCESS(status)) - { - // Call port driver to get adapter capabilities. - propertyId = StorageAdapterProperty; - - status = DeviceRetrieveDescriptor(DeviceExtension->Device, - &propertyId, - (PSTORAGE_DESCRIPTOR_HEADER*)&DeviceExtension->AdapterDescriptor); - } - if (NT_SUCCESS(status)) - { - // Call port driver to get device descriptor. - propertyId = StorageDeviceProperty; - - status = DeviceRetrieveDescriptor(DeviceExtension->Device, - &propertyId, - (PSTORAGE_DESCRIPTOR_HEADER*)&DeviceExtension->DeviceDescriptor); - } - if (NT_SUCCESS(status)) - { - // Call port driver to get device power property. - // Not all port drivers support this property, and it's not fatal if this query fails. - propertyId = StorageDevicePowerProperty; - - (void) DeviceRetrieveDescriptor(DeviceExtension->Device, - &propertyId, - (PSTORAGE_DESCRIPTOR_HEADER*)&DeviceExtension->PowerDescriptor); - } - - if (NT_SUCCESS(status)) - { - // Determine the maximum page-aligned and non-page-aligned transfer - // lengths here, so we needn't do this in common READ/WRITE code paths - - // start with the number of pages the adapter can support - ULONG maxAlignedTransfer = DeviceExtension->AdapterDescriptor->MaximumPhysicalPages; - ULONG maxUnalignedTransfer = DeviceExtension->AdapterDescriptor->MaximumPhysicalPages; - - - // Unaligned buffers could cross a page boundary. - if (maxUnalignedTransfer > 1) - { - maxUnalignedTransfer--; - } - - // if we'd overflow multiplying by page size, just max out the - // transfer length allowed by the number of pages limit. - if (maxAlignedTransfer >= (((ULONG)-1) / PAGE_SIZE)) - { - maxAlignedTransfer = (ULONG)-1; - } - else - { - maxAlignedTransfer *= PAGE_SIZE; - } - - if (maxUnalignedTransfer >= (((ULONG)-1) / PAGE_SIZE)) - { - maxUnalignedTransfer = (ULONG)-1; - } - else - { - maxUnalignedTransfer *= PAGE_SIZE; - } - - // finally, take the smaller of the above and the adapter's - // reported maximum number of bytes per transfer. - maxAlignedTransfer = min(maxAlignedTransfer, DeviceExtension->AdapterDescriptor->MaximumTransferLength); - maxUnalignedTransfer = min(maxUnalignedTransfer, DeviceExtension->AdapterDescriptor->MaximumTransferLength); - - // Make sure the values are reasonable and not zero. - maxAlignedTransfer = max(maxAlignedTransfer, PAGE_SIZE); - maxUnalignedTransfer = max(maxUnalignedTransfer, PAGE_SIZE); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "Device %p Max aligned/unaligned transfer size is %x/%x\n", - DeviceExtension->Device, - maxAlignedTransfer, - maxUnalignedTransfer - )); - DeviceExtension->DeviceAdditionalData.MaxPageAlignedTransferBytes = maxAlignedTransfer; - DeviceExtension->DeviceAdditionalData.MaxUnalignedTransferBytes = maxUnalignedTransfer; - } - else - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, "DeviceRetrieveDescriptorsAndTransferLength failed %lx\n", status)); - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceRetrieveDescriptor( - _In_ WDFDEVICE Device, - _In_ PSTORAGE_PROPERTY_ID PropertyId, - _Outptr_ PSTORAGE_DESCRIPTOR_HEADER* Descriptor - ) -/*++ - -Routine Description: - - This routine will perform a query for the specified property id and will - allocate a non-paged buffer to store the data in. It is the responsibility - of the caller to ensure that this buffer is freed. - - This routine must be run at IRQL_PASSIVE_LEVEL - -Arguments: - - Device - the device object - PropertyId - type of property to retrieve - Descriptor - buffer allocated in this function to hold the descriptor data - -Return Value: - - status - ---*/ -{ - NTSTATUS status; - WDF_MEMORY_DESCRIPTOR memoryDescriptor; - - STORAGE_PROPERTY_QUERY query = {0}; - ULONG bufferLength = 0; - - PSTORAGE_DESCRIPTOR_HEADER descriptor = NULL; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - - PAGED_CODE(); - - // Set the passed-in descriptor pointer to NULL as default - *Descriptor = NULL; - - // On the first pass we just want to get the first few - // bytes of the descriptor so we can read it's size - query.PropertyId = *PropertyId; - query.QueryType = PropertyStandardQuery; - - descriptor = (PVOID)&query; - - NT_ASSERT(sizeof(STORAGE_PROPERTY_QUERY) >= (sizeof(ULONG)*2)); - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memoryDescriptor, - (PVOID)&query, - sizeof(STORAGE_PROPERTY_QUERY)); - - status = WdfIoTargetSendIoctlSynchronously(deviceExtension->IoTarget, - NULL, - IOCTL_STORAGE_QUERY_PROPERTY, - &memoryDescriptor, - &memoryDescriptor, - NULL, - NULL); - - if(!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "DeviceRetrieveDescriptor: error %lx trying to " - "query properties #1\n", status)); - return status; - } - - if (descriptor->Size == 0) - { - // This DebugPrint is to help third-party driver writers - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "DeviceRetrieveDescriptor: size returned was zero?! (status " - "%x\n", status)); - return STATUS_UNSUCCESSFUL; - } - - // This time we know how much data there is so we can - // allocate a buffer of the correct size - bufferLength = descriptor->Size; - NT_ASSERT(bufferLength >= sizeof(STORAGE_PROPERTY_QUERY)); - bufferLength = max(bufferLength, sizeof(STORAGE_PROPERTY_QUERY)); - - descriptor = ExAllocatePool2(POOL_FLAG_NON_PAGED, bufferLength, CDROM_TAG_DESCRIPTOR); - - if(descriptor == NULL) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "DeviceRetrieveDescriptor: unable to memory for descriptor " - "(%d bytes)\n", bufferLength)); - return STATUS_INSUFFICIENT_RESOURCES; - } - - // setup the query again, as it was overwritten above - RtlZeroMemory(&query, sizeof(STORAGE_PROPERTY_QUERY)); - query.PropertyId = *PropertyId; - query.QueryType = PropertyStandardQuery; - - // copy the input to the new outputbuffer - RtlCopyMemory(descriptor, - &query, - sizeof(STORAGE_PROPERTY_QUERY)); - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memoryDescriptor, - (PVOID)descriptor, - bufferLength); - - status = WdfIoTargetSendIoctlSynchronously(deviceExtension->IoTarget, - NULL, - IOCTL_STORAGE_QUERY_PROPERTY, - &memoryDescriptor, - &memoryDescriptor, - NULL, - NULL); - - if(!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "DeviceRetrieveDescriptor: error %lx trying to " - "query properties #1\n", status)); - FREE_POOL(descriptor); - - return status; - } - - // return the memory we've allocated to the caller - *Descriptor = descriptor; - - return status; -} // end DeviceRetrieveDescriptor() - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceRetrieveHackFlagsFromRegistry( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - try to retrieve hack flages from registry and put the information in - device extension. - -Arguments: - - DeviceExtension - the device context - -Return Value: - - none - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFKEY hardwareKey = NULL; - WDFKEY subKey = NULL; - ULONG deviceHacks = 0; - - DECLARE_CONST_UNICODE_STRING(subKeyName, CLASSP_REG_SUBKEY_NAME); - DECLARE_CONST_UNICODE_STRING(valueName, CLASSP_REG_HACK_VALUE_NAME); - - PAGED_CODE(); - - status = WdfDeviceOpenRegistryKey(DeviceExtension->Device, - PLUGPLAY_REGKEY_DEVICE, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &hardwareKey); - if (NT_SUCCESS(status)) - { - status = WdfRegistryOpenKey(hardwareKey, - &subKeyName, - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - &subKey); - - if (NT_SUCCESS(status)) - { - status = WdfRegistryQueryULong(subKey, - &valueName, - &deviceHacks); - if (NT_SUCCESS(status)) - { - // remove unknown values and save... - CLEAR_FLAG(deviceHacks, FDO_HACK_INVALID_FLAGS); - SET_FLAG(DeviceExtension->PrivateFdoData->HackFlags, deviceHacks); - } - - WdfRegistryClose(subKey); - } - - WdfRegistryClose(hardwareKey); - } - - - // - // we should modify the system hive to include another key for us to grab - // settings from. in this case: Classpnp\HackFlags - // - // the use of a DWORD value for the HackFlags allows 32 hacks w/o - // significant use of the registry, and also reduces OEM exposure. - // - // definition of bit flags: - // 0x00000001 -- Device succeeds PREVENT_MEDIUM_REMOVAL, but - // cannot actually prevent removal. - // 0x00000002 -- Device hard-hangs or times out for GESN requests. - // 0x00000008 -- Device does not support RESERVE(6) and RELEASE(6). - // 0x00000010 -- Device may incorrecly report operational changes in GESN. - // 0x00000020 -- Device does not support streaming READ(12) / WRITE(12). - // 0x00000040 -- Device does not support asynchronous notification. - // 0xffffff80 -- Currently reserved, may be used later. - // - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -VOID DeviceScanForSpecial( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ CDROM_SCAN_FOR_SPECIAL_INFO DeviceList[], - _In_ PCDROM_SCAN_FOR_SPECIAL_HANDLER Function) -/*++ - -Routine Description: - - scan the list of devices that should be hacked or not supported. - -Arguments: - - DeviceExtension - the device context - DeviceList - the device list - Function - function used to scan from the list. - -Return Value: - - none - ---*/ -{ - PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor; - PUCHAR vendorId; - PUCHAR productId; - PUCHAR productRevision; - UCHAR nullString[] = ""; - - PAGED_CODE(); - NT_ASSERT(DeviceList); - NT_ASSERT(Function); - - if (DeviceList == NULL) - { - return; - } - if (Function == NULL) - { - return; - } - - deviceDescriptor = DeviceExtension->DeviceDescriptor; - - // SCSI sets offsets to -1, ATAPI sets to 0. check for both. - if (deviceDescriptor->VendorIdOffset != 0 && - deviceDescriptor->VendorIdOffset != -1) - { - vendorId = ((PUCHAR)deviceDescriptor); - vendorId += deviceDescriptor->VendorIdOffset; - } - else - { - vendorId = nullString; - } - - if (deviceDescriptor->ProductIdOffset != 0 && - deviceDescriptor->ProductIdOffset != -1) - { - productId = ((PUCHAR)deviceDescriptor); - productId += deviceDescriptor->ProductIdOffset; - } - else - { - productId = nullString; - } - - if (deviceDescriptor->ProductRevisionOffset != 0 && - deviceDescriptor->ProductRevisionOffset != -1) - { - productRevision = ((PUCHAR)deviceDescriptor); - productRevision += deviceDescriptor->ProductRevisionOffset; - } - else - { - productRevision = nullString; - } - - // loop while the device list is valid (not null-filled) - for (;(DeviceList->VendorId != NULL || - DeviceList->ProductId != NULL || - DeviceList->ProductRevision != NULL); DeviceList++) - { - if (StringsAreMatched(DeviceList->VendorId, (LPSTR)vendorId) && - StringsAreMatched(DeviceList->ProductId, (LPSTR)productId) && - StringsAreMatched(DeviceList->ProductRevision, (LPSTR)productRevision) - ) - { - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "DeviceScanForSpecial: Found matching " - "controller Ven: %s Prod: %s Rev: %s\n", - (LPCSTR)vendorId, (LPCSTR)productId, (LPCSTR)productRevision)); - - // pass the context to the call back routine and exit - (Function)(DeviceExtension, DeviceList->Data); - - // for CHK builds, try to prevent wierd stacks by having a debug - // print here. it's a hack, but i know of no other way to prevent - // the stack from being wrong. - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "DeviceScanForSpecial: " - "completed callback\n")); - return; - - } // else the strings did not match - - } // none of the devices matched. - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "DeviceScanForSpecial: no match found for %p\n", - DeviceExtension->DeviceObject)); - return; - -} // end DeviceScanForSpecial() - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceHackFlagsScan( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG_PTR Data - ) -{ - PAGED_CODE(); - - // remove invalid flags and save - CLEAR_FLAG(Data, FDO_HACK_INVALID_FLAGS); - SET_FLAG(DeviceExtension->PrivateFdoData->HackFlags, Data); - - return; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeHotplugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Retrieve information into struc STORAGE_HOTPLUG_INFO in DeviceExtension - initialize the hotplug information only after the ScanForSpecial routines, - as it relies upon the hack flags - DeviceExtension->PrivateFdoData->HackFlags. - -Arguments: - - DeviceExtension - the device context - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_PRIVATE_FDO_DATA fdoData = DeviceExtension->PrivateFdoData; - DEVICE_REMOVAL_POLICY deviceRemovalPolicy = 0; - ULONG resultLength = 0; - ULONG writeCacheOverride; - - PAGED_CODE(); - - // start with some default settings - RtlZeroMemory(&(fdoData->HotplugInfo), sizeof(STORAGE_HOTPLUG_INFO)); - - // set the size (aka version) - fdoData->HotplugInfo.Size = sizeof(STORAGE_HOTPLUG_INFO); - - // set if the device has removable media - if (DeviceExtension->DeviceDescriptor->RemovableMedia) - { - fdoData->HotplugInfo.MediaRemovable = TRUE; - } - else - { - fdoData->HotplugInfo.MediaRemovable = FALSE; - } - - // - // this refers to devices which, for reasons not yet understood, - // do not fail PREVENT_MEDIA_REMOVAL requests even though they - // have no way to lock the media into the drive. this allows - // the filesystems to turn off delayed-write caching for these - // devices as well. - // - - if (TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_CANNOT_LOCK_MEDIA)) - { - fdoData->HotplugInfo.MediaHotplug = TRUE; - } - else - { - fdoData->HotplugInfo.MediaHotplug = FALSE; - } - - // Query the default removal policy from the kernel - status = WdfDeviceQueryProperty(DeviceExtension->Device, - DevicePropertyRemovalPolicy, - sizeof(DEVICE_REMOVAL_POLICY), - (PVOID)&deviceRemovalPolicy, - &resultLength); - if (NT_SUCCESS(status)) - { - if (resultLength != sizeof(DEVICE_REMOVAL_POLICY)) - { - status = STATUS_UNSUCCESSFUL; - } - } - - if (NT_SUCCESS(status)) - { - // Look into the registry to see if the user has chosen - // to override the default setting for the removal policy. - // User can override only if the default removal policy is - // orderly or suprise removal. - - if ((deviceRemovalPolicy == RemovalPolicyExpectOrderlyRemoval) || - (deviceRemovalPolicy == RemovalPolicyExpectSurpriseRemoval)) - { - DEVICE_REMOVAL_POLICY userRemovalPolicy = 0; - - DeviceGetParameter(DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_REMOVAL_POLICY_VALUE_NAME, - (PULONG)&userRemovalPolicy); - - // Validate the override value and use it only if it is an - // allowed value. - if ((userRemovalPolicy == RemovalPolicyExpectOrderlyRemoval) || - (userRemovalPolicy == RemovalPolicyExpectSurpriseRemoval)) - { - deviceRemovalPolicy = userRemovalPolicy; - } - } - - // use this info to set the DeviceHotplug setting - // don't rely on DeviceCapabilities, since it can't properly - // determine device relations, etc. let the kernel figure this - // stuff out instead. - if (deviceRemovalPolicy == RemovalPolicyExpectSurpriseRemoval) - { - fdoData->HotplugInfo.DeviceHotplug = TRUE; - } - else - { - fdoData->HotplugInfo.DeviceHotplug = FALSE; - } - - // this refers to the *filesystem* caching, but has to be included - // here since it's a per-device setting. this may change to be - // stored by the system in the future. - writeCacheOverride = FALSE; - DeviceGetParameter(DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_WRITE_CACHE_VALUE_NAME, - &writeCacheOverride); - - if (writeCacheOverride) - { - fdoData->HotplugInfo.WriteCacheEnableOverride = TRUE; - } - else - { - fdoData->HotplugInfo.WriteCacheEnableOverride = FALSE; - } - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "Could not initialize hotplug information %lx\n", status)); - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitMmcContext( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine initializes and populates the internal data structures that are - used to discover various MMC-defined capabilities of the device. - - This routine will not clean up allocate resources if it fails - that - is left for device stop/removal routines - -Arguments: - - DeviceExtension - device extension - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - DeviceExtension->DeviceAdditionalData.Mmc.IsMmc = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.IsAACS = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.IsWriter = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.IsCssDvd = FALSE; - DeviceExtension->DeviceAdditionalData.DriveDeviceType = FILE_DEVICE_CD_ROM; - - // Determine if the drive is MMC-Capable - if (NT_SUCCESS(status)) - { - status = DeviceGetMmcSupportInfo(DeviceExtension, - &DeviceExtension->DeviceAdditionalData.Mmc.IsMmc); - - if (!NT_SUCCESS(status)) - { - //Currently, only low resource error comes here. - //That is a success case for unsupporting this command. - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "DeviceInitMmcContext: Failed to get the support info for GET CONFIGURATION " - "command, failng %!STATUS!\n", status - )); - - DeviceExtension->DeviceAdditionalData.Mmc.IsMmc = FALSE; - status = STATUS_SUCCESS; - } - } - - if (NT_SUCCESS(status) && DeviceExtension->DeviceAdditionalData.Mmc.IsMmc) - { - // the drive supports at least a subset of MMC commands - // (and therefore supports READ_CD, etc...) - - // allocate a buffer for all the capabilities and such - status = DeviceAllocateMmcResources(DeviceExtension->Device); - } - - if (NT_SUCCESS(status) && DeviceExtension->DeviceAdditionalData.Mmc.IsMmc) - { - PFEATURE_HEADER header = NULL; - FEATURE_NUMBER validationSchema; - ULONG blockingFactor; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceInitMmcContext: FDO %p GET CONFIGURATION buffer %p\n", - DeviceExtension->Device, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer - )); - - // Update several properties using the retrieved Configuration Data. - - // print all the feature pages (DBG only) - DevicePrintAllFeaturePages(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize); - - // if AACS feature exists, enable AACS flag in the driver - header = DeviceFindFeaturePage(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FeatureAACS); - if (header) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceInitMmcContext: Reporting AACS support for device due to " - "GET CONFIGURATION showing support\n" - )); - DeviceExtension->DeviceAdditionalData.Mmc.IsAACS = TRUE; - } - -#ifdef ENABLE_AACS_TESTING - DeviceExtension->DeviceAdditionalData.Mmc.IsAACS = TRUE; // just force it true for testing -#endif // ENABLE_AACS_TESTING - - // Check if it's a DVD device - header = DeviceFindFeaturePage(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FeatureDvdRead); - if (header != NULL) - { - DeviceExtension->DeviceAdditionalData.DriveDeviceType = FILE_DEVICE_DVD; - } - - // check if drive is writer - DeviceUpdateMmcWriteCapability(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FALSE, //Check if the drive has the ability to write. - (PBOOLEAN)&(DeviceExtension->DeviceAdditionalData.Mmc.IsWriter), - &validationSchema, - &blockingFactor); - - // check if there is a CSS protected DVD or CPPM-protected DVDAudio media in drive. - header = DeviceFindFeaturePage(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FeatureDvdCSS); - - DeviceExtension->DeviceAdditionalData.Mmc.IsCssDvd = (header != NULL) && (header->Current); - - // Flag the StartIo routine to update its state and hook in the error handler - DeviceExtension->DeviceAdditionalData.Mmc.UpdateState = CdromMmcUpdateRequired; - DeviceExtension->DeviceAdditionalData.ErrorHandler = DeviceErrorHandlerForMmc; - - SET_FLAG(DeviceExtension->DeviceFlags, DEV_SAFE_START_UNIT); - - // Read the CDROM mode sense page to get additional info for raw read requests. - // only valid for MMC devices - DeviceSetRawReadInfo(DeviceExtension); - } - - // Set Read-Only device flag for non-MMC device. - if (!(DeviceExtension->DeviceAdditionalData.Mmc.IsMmc)) - { - ULONG deviceCharacteristics = WdfDeviceGetCharacteristics(DeviceExtension->Device); - - deviceCharacteristics |= FILE_READ_ONLY_DEVICE; - - WdfDeviceSetCharacteristics(DeviceExtension->Device, deviceCharacteristics); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceInitMmcContext: FDO %p Device is not an MMC compliant device, so setting " - "to read-only (legacy) mode", - DeviceExtension->Device - )); - } - - // Set DEV_SAFE_START_UNIT flag for newer devices. - if (DeviceExtension->DeviceAdditionalData.DriveDeviceType == FILE_DEVICE_DVD) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceInitMmcContext: DVD Devices require START UNIT\n")); - SET_FLAG(DeviceExtension->DeviceFlags, DEV_SAFE_START_UNIT); - - } - else if ((DeviceExtension->DeviceDescriptor->BusType != BusTypeScsi) && - (DeviceExtension->DeviceDescriptor->BusType != BusTypeAtapi) && - (DeviceExtension->DeviceDescriptor->BusType != BusTypeUnknown) - ) - { - // devices on the newer busses require START_UNIT - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceInitMmcContext: Devices for newer buses require START UNIT\n")); - SET_FLAG(DeviceExtension->DeviceFlags, DEV_SAFE_START_UNIT); - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -ULONG -DeviceGetTimeOutValueFromRegistry() -/*++ - -Routine Description: - - get the device time out value from registry - -Arguments: - - None - -Return Value: - - ULONG - value of timeout - ---*/ -{ - NTSTATUS status; - WDFKEY registryKey = NULL; - ULONG timeOutValue = 0; - - DECLARE_CONST_UNICODE_STRING(registryValueName, L"TimeOutValue"); - - PAGED_CODE(); - - // open the service key. - status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(), - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - ®istryKey); - - if (NT_SUCCESS(status)) - { - status = WdfRegistryQueryULong(registryKey, - ®istryValueName, - &timeOutValue); - - WdfRegistryClose(registryKey); - } - - if (!NT_SUCCESS(status)) - { - timeOutValue = 0; - } - - return timeOutValue; - -} // end DeviceGetTimeOutValueFromRegistry() - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceScanSpecialDevices( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This function checks to see if an SCSI logical unit requires an special - initialization or error processing. - -Arguments: - - Device - device object. - -Return Value: - - None. - ---*/ -{ - - PAGED_CODE(); - - // set our hack flags - DeviceScanForSpecial(DeviceExtension, CdromHackItems, ScanForSpecialHandler); - - // - // All CDRom's can ignore the queue lock failure for power operations - // and do not require handling the SpinUp case (unknown result of sending - // a cdrom a START_UNIT command -- may eject disks?) - // - // We send the stop command mostly to stop outstanding asynch operations - // (like audio playback) from running when the system is powered off. - // Because of this and the unlikely chance that a PLAY command will be - // sent in the window between the STOP and the time the machine powers down - // we don't require queue locks. This is important because without them - // classpnp's power routines will send the START_STOP_UNIT command to the - // device whether or not it supports locking (atapi does not support locking - // and if we requested them we would end up not stopping audio on atapi - // devices). -// SET_FLAG(deviceExtension->ScanForSpecialFlags, CDROM_SPECIAL_DISABLE_SPIN_UP); -// SET_FLAG(deviceExtension->ScanForSpecialFlags, CDROM_SPECIAL_NO_QUEUE_LOCK); - - if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_TOSHIBA_SD_W1101)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceScanSpecialDevices: Found Toshiba SD-W1101 DVD-RAM " - "-- This drive will *NOT* support DVD-ROM playback.\n")); - } - else if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_HITACHI_GD_2000)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceScanSpecialDevices: Found Hitachi GD-2000\n")); - - // Setup an error handler to spin up the drive when it idles out - // since it seems to like to fail to spin itself back up on its - // own for a REPORT_KEY command. It may also lose the AGIDs that - // it has given, which will result in DVD playback failures. - // This routine will just do what it can... - DeviceExtension->DeviceAdditionalData.ErrorHandler = DeviceErrorHandlerForHitachiGD2000; - - // this drive may require START_UNIT commands to spin - // the drive up when it's spun itself down. - SET_FLAG(DeviceExtension->DeviceFlags, DEV_SAFE_START_UNIT); - } - else if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_FUJITSU_FMCD_10x)) - { - // When Read command is issued to FMCD-101 or FMCD-102 and there is a music - // cd in it. It takes longer time than SCSI_CDROM_TIMEOUT before returning - // error status. - DeviceExtension->TimeOutValue = 20; - } - else if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_DEC_RRD)) - { - NTSTATUS status; - PMODE_PARM_READ_WRITE_DATA modeParameters; - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceScanSpecialDevices: Found DEC RRD.\n")); - - DeviceExtension->DeviceAdditionalData.IsDecRrd = TRUE; - - // Setup an error handler to reinitialize the cd rom after it is reset? - // - //DeviceExtension->DevInfo->ClassError = DecRrdProcessError; - - // Found a DEC RRD cd-rom. These devices do not pass MS HCT - // multi-media tests because the DEC firmware modifieds the block - // from the PC-standard 2K to 512. Change the block transfer size - // back to the PC-standard 2K by using a mode select command. - - modeParameters = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(MODE_PARM_READ_WRITE_DATA), - CDROM_TAG_MODE_DATA); - if (modeParameters == NULL) - { - return; - } - - RtlZeroMemory(modeParameters, sizeof(MODE_PARM_READ_WRITE_DATA)); - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - // Set the block length to 2K. - modeParameters->ParameterListHeader.BlockDescriptorLength = sizeof(MODE_PARAMETER_BLOCK); - - // Set block length to 2K (0x0800) in Parameter Block. - modeParameters->ParameterListBlock.BlockLength[0] = 0x00; //MSB - modeParameters->ParameterListBlock.BlockLength[1] = 0x08; - modeParameters->ParameterListBlock.BlockLength[2] = 0x00; //LSB - - // Build the mode select CDB. - srb.CdbLength = 6; - srb.TimeOutValue = DeviceExtension->TimeOutValue; - - cdb = (PCDB)srb.Cdb; - cdb->MODE_SELECT.PFBit = 1; - cdb->MODE_SELECT.OperationCode = SCSIOP_MODE_SELECT; - cdb->MODE_SELECT.ParameterListLength = HITACHI_MODE_DATA_SIZE; - - // Send the request to the device. - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - modeParameters, - sizeof(MODE_PARM_READ_WRITE_DATA), - TRUE, - NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "DeviceScanSpecialDevices: Setting DEC RRD to 2K block" - "size failed [%x]\n", status)); - } - - ExFreePool(modeParameters); - } - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScanForSpecialHandler( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG_PTR HackFlags - ) -{ - PAGED_CODE(); - - CLEAR_FLAG(HackFlags, CDROM_HACK_INVALID_FLAGS); - - DeviceExtension->DeviceAdditionalData.HackFlags = HackFlags; - - return; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceCacheDeviceInquiryData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - get inquiry data from device and cache it into device extension - The first INQUIRY command sent is with 0x24 bytes required data, - as ATAport driver always sends this to enumerate devices and 0x24 - bytes is the minimum data device should return by spec. - -Arguments: - - DeviceExtension - device extension. - -Return Value: - - NTSTATUS. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb = (PCDB)(&srb.Cdb); - PINQUIRYDATA tmpInquiry = NULL; - - // by spec, device should return at least 36 bytes. - ULONG requestedInquiryTransferBytes = MINIMUM_CDROM_INQUIRY_SIZE; - BOOLEAN needResendCommand = TRUE; - BOOLEAN portDriverHack = FALSE; - - // this ensures that the strings vendorID, productID, and firmwareRevision - // are all available in the inquiry data. In addition, MMC spec requires - // all type 5 devices to have minimum 36 bytes of inquiry. - static const UCHAR minInquiryAdditionalLength = - MINIMUM_CDROM_INQUIRY_SIZE - - RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, AdditionalLength); - - C_ASSERT( RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, AdditionalLength) <= 8 ); - C_ASSERT( RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, ProductRevisionLevel) == MINIMUM_CDROM_INQUIRY_SIZE ); - - PAGED_CODE(); - - // short-circuit here for if already cached for this device - // required to avoid use of scratch buffer after initialization - // of MCN code. - if (DeviceExtension->DeviceAdditionalData.CachedInquiryData != NULL) - { - NT_ASSERT(DeviceExtension->DeviceAdditionalData.CachedInquiryDataByteCount != 0); - return STATUS_SUCCESS; - } - - // 1. retrieve the inquiry data length - - // 1.1 allocate inquiry data buffer - tmpInquiry = ExAllocatePool2(POOL_FLAG_NON_PAGED, - requestedInquiryTransferBytes, - CDROM_TAG_INQUIRY); - if (tmpInquiry == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - - // 1.2 send INQUIRY command - if (NT_SUCCESS(status)) - { - srb.CdbLength = 6; - cdb->AsByte[0] = SCSIOP_INQUIRY; - cdb->AsByte[3] = (UCHAR)( requestedInquiryTransferBytes >> (8*1) ); - cdb->AsByte[4] = (UCHAR)( requestedInquiryTransferBytes >> (8*0) ); - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - tmpInquiry, - requestedInquiryTransferBytes, - FALSE, - NULL); - } - - // 1.3 get required data length - if (NT_SUCCESS(status)) - { - if ((requestedInquiryTransferBytes == srb.DataTransferLength) && - (requestedInquiryTransferBytes == (tmpInquiry->AdditionalLength + - RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, AdditionalLength))) ) - { - // device has only 36 bytes of INQUIRY data. do not need to resend the command. - needResendCommand = FALSE; - } - else - { - // workaround an ATAPI.SYS bug where additional length field is set to zero - if (tmpInquiry->AdditionalLength == 0) - { - tmpInquiry->AdditionalLength = minInquiryAdditionalLength; - portDriverHack = TRUE; - } - - requestedInquiryTransferBytes = - tmpInquiry->AdditionalLength + - RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, AdditionalLength); - - if (requestedInquiryTransferBytes >= MINIMUM_CDROM_INQUIRY_SIZE) - { - needResendCommand = TRUE; - } - else - { - needResendCommand = FALSE; - //Length is small than minimum length, error out. - status = STATUS_DEVICE_PROTOCOL_ERROR; - } - } - } - - // 2. retrieve the inquiry data if still needed. - - // 2.1 Clean up. - if (NT_SUCCESS(status) && needResendCommand) - { - FREE_POOL(tmpInquiry); - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - tmpInquiry = ExAllocatePool2(POOL_FLAG_NON_PAGED, - requestedInquiryTransferBytes, - CDROM_TAG_INQUIRY); - if (tmpInquiry == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - // 2.2 resend INQUIRY command - if (NT_SUCCESS(status) && needResendCommand) - { - srb.CdbLength = 6; - cdb->AsByte[0] = SCSIOP_INQUIRY; - cdb->AsByte[3] = (UCHAR)( requestedInquiryTransferBytes >> (8*1) ); - cdb->AsByte[4] = (UCHAR)( requestedInquiryTransferBytes >> (8*0) ); - - status = DeviceSendSrbSynchronously( DeviceExtension->Device, - &srb, - tmpInquiry, - requestedInquiryTransferBytes, - FALSE, - NULL); - - if (!NT_SUCCESS(status)) - { - // Workaround for drive reports that it has more INQUIRY data than reality. - if ((srb.SrbStatus == SRB_STATUS_DATA_OVERRUN) && - (srb.DataTransferLength < requestedInquiryTransferBytes) && - (srb.DataTransferLength >= MINIMUM_CDROM_INQUIRY_SIZE)) - { - //Port driver says buffer size mismatch (buffer underrun), - //retry with the real buffer size it could return. - requestedInquiryTransferBytes = srb.DataTransferLength; - - FREE_POOL(tmpInquiry); - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - tmpInquiry = ExAllocatePool2(POOL_FLAG_NON_PAGED, - requestedInquiryTransferBytes, - CDROM_TAG_INQUIRY); - if (tmpInquiry == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - srb.CdbLength = 6; - cdb->AsByte[0] = SCSIOP_INQUIRY; - cdb->AsByte[3] = (UCHAR)( requestedInquiryTransferBytes >> (8*1) ); - cdb->AsByte[4] = (UCHAR)( requestedInquiryTransferBytes >> (8*0) ); - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - tmpInquiry, - requestedInquiryTransferBytes, - FALSE, - NULL); - } - } - } - - //Check the transferred data length for safe. - if (NT_SUCCESS(status)) - { - requestedInquiryTransferBytes = srb.DataTransferLength; - - if (requestedInquiryTransferBytes < MINIMUM_CDROM_INQUIRY_SIZE) - { - // should never occur - status = STATUS_DEVICE_PROTOCOL_ERROR; - } - } - - // ensure we got some non-zero data.... - // This is done so we don't accidentally work around the - // ATAPI.SYS bug when no data was transferred. - if (NT_SUCCESS(status) && portDriverHack) - { - PULONG tmp = (PULONG)tmpInquiry; - ULONG i = MINIMUM_CDROM_INQUIRY_SIZE / sizeof(ULONG); - C_ASSERT( RTL_SIZEOF_THROUGH_FIELD(INQUIRYDATA, ProductRevisionLevel) % sizeof(ULONG) == 0 ); - - // wouldn't you know it -- there is no RtlIsMemoryZero() function; Make one up. - for ( ; i != 0; i--) - { - if (*tmp != 0) - { - break; // out of this inner FOR loop -- guarantees 'i != 0' - } - tmp++; - } - - if (i == 0) // all loop'd successfully - { - // should never occur to successfully get all zero'd data - status = STATUS_DEVICE_PROTOCOL_ERROR; - } - } - } - - // if everything succeeded, then (and only then) modify the device extension - if (NT_SUCCESS(status)) - { - DeviceExtension->DeviceAdditionalData.CachedInquiryData = tmpInquiry; - DeviceExtension->DeviceAdditionalData.CachedInquiryDataByteCount = requestedInquiryTransferBytes; - } - else - { - FREE_POOL(tmpInquiry); - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetMmcSupportInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN IsMmcDevice - ) -/*++ - -Routine Description: - - check if the device is MMC capable. - -Arguments: - - DeviceExtension - device extension. - -Return Value: - - NTSTATUS. - IsMmcDevice - TRUE (MMC capable); FALSE (not MMC device) - ---*/ -{ - NTSTATUS status; - ULONG size; - ULONG previouslyFailed; - - PAGED_CODE(); - - *IsMmcDevice = FALSE; - - // read the registry in case the drive failed previously, - // and a timeout is occurring. - previouslyFailed = FALSE; - DeviceGetParameter(DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_DRIVE_NAME, - &previouslyFailed); - - if (previouslyFailed) - { - SET_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_GET_CONFIG_SUPPORT); - } - - // read from the registry in case the drive reports bad profile lengths - previouslyFailed = FALSE; - DeviceGetParameter(DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_VENDOR_SPECIFIC_PROFILE, - &previouslyFailed); - - if (previouslyFailed) - { - SET_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_VENDOR_PROFILES); - } - - // check for the ProfileList feature to determine if the drive is MMC compliant - // and set the "size" local variable to total GetConfig data size available. - // NOTE: This will exit this function in some error paths. - { - GET_CONFIGURATION_HEADER localHeader = {0}; - ULONG usable = 0; - - status = DeviceGetConfiguration(DeviceExtension->Device, - &localHeader, - sizeof(GET_CONFIGURATION_HEADER), - &usable, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL); - - if (status == STATUS_INVALID_DEVICE_REQUEST || - status == STATUS_NO_MEDIA_IN_DEVICE || - status == STATUS_IO_DEVICE_ERROR || - status == STATUS_IO_TIMEOUT) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration Failed (%x), device %p not mmc-compliant\n", - status, DeviceExtension->DeviceObject - )); - - previouslyFailed = TRUE; - DeviceSetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_DRIVE_NAME, - previouslyFailed); - - return STATUS_SUCCESS; - } - else if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration Failed, status %x -- defaulting to -ROM\n", - status)); - - return STATUS_SUCCESS; - } - else if (usable < sizeof(GET_CONFIGURATION_HEADER)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration Failed, returned only %x bytes!\n", usable)); - previouslyFailed = TRUE; - DeviceSetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_DRIVE_NAME, - previouslyFailed); - - return STATUS_SUCCESS; - } - - size = (localHeader.DataLength[0] << 24) | - (localHeader.DataLength[1] << 16) | - (localHeader.DataLength[2] << 8) | - (localHeader.DataLength[3] << 0) ; - - - if ((size <= 4) || (size + 4 < size)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration Failed, claims MMC support but doesn't " - "correctly return config length! (%x)\n", - size - )); - previouslyFailed = TRUE; - DeviceSetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_DRIVE_NAME, - previouslyFailed); - - return STATUS_SUCCESS; - } - else if ((size % 4) != 0) - { - if ((size % 2) != 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration Failed, returned odd number of bytes %x!\n", - size - )); - previouslyFailed = TRUE; - DeviceSetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_DRIVE_NAME, - previouslyFailed); - - return STATUS_SUCCESS; - } - else - { - if (TEST_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_VENDOR_PROFILES)) - { - // we've already caught this and ASSERT'd once, so don't do it again - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "GetConfiguration returned a size that is not per spec (%x bytes), this is probably because of a vendor specific data header with a size not divisible by 4.\n", - size - )); - previouslyFailed = TRUE; - DeviceSetParameter(DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_NON_MMC_VENDOR_SPECIFIC_PROFILE, - previouslyFailed); - } - } - } - - size += 4; // sizeof the datalength fields - } - - *IsMmcDevice = TRUE; - - // This code doesn't handle total get config size over 64k - NT_ASSERT( size <= MAXUSHORT ); - - // Check for SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE support in the device. - // NOTE: This will exit this function in some error paths. - { - ULONG featureSize = sizeof(GET_CONFIGURATION_HEADER)+sizeof(FEATURE_HEADER); - ULONG usable = 0; - - PGET_CONFIGURATION_HEADER configBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, - featureSize, - CDROM_TAG_GET_CONFIG); - - if (configBuffer == NULL) - { - return STATUS_INSUFFICIENT_RESOURCES; - } - - // read the registry in case the drive failed previously, - // and a timeout is occurring. - previouslyFailed = FALSE; - DeviceGetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_TYPE_ONE_GET_CONFIG_NAME, - &previouslyFailed); - - if (previouslyFailed) - { - SET_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG); - FREE_POOL(configBuffer); - return STATUS_SUCCESS; - } - - // Get only the config and feature header - status = DeviceGetConfiguration(DeviceExtension->Device, - configBuffer, - featureSize, - &usable, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE); - - if (!NT_SUCCESS(status) || (usable < featureSize)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Type One GetConfiguration Failed. Usable buffer size: %d\n", usable)); - previouslyFailed = TRUE; - } - else - { - PFEATURE_HEADER featureHeader; - ULONG totalAvailableBytes = 0; - ULONG expectedAvailableBytes = 0; - - REVERSE_BYTES(&totalAvailableBytes, configBuffer->DataLength); - totalAvailableBytes += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - featureHeader = (PFEATURE_HEADER) ((PUCHAR)configBuffer + sizeof(GET_CONFIGURATION_HEADER)); - expectedAvailableBytes = sizeof(GET_CONFIGURATION_HEADER) + - sizeof(FEATURE_HEADER) + - featureHeader->AdditionalLength; - - if (totalAvailableBytes > expectedAvailableBytes) - { - // Device is returning more than required size. Most likely the device - // is returning TYPE ALL data. Set the flag to use TYPE ALL for TYPE ONE - // requets - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Type One GetConfiguration Failed. " - "Device returned %d bytes instead of %d bytes\n", - size, featureSize)); - - previouslyFailed = TRUE; - } - } - - FREE_POOL(configBuffer); - - if (previouslyFailed == TRUE) - { - DeviceSetParameter( DeviceExtension, - CDROM_SUBKEY_NAME, - CDROM_TYPE_ONE_GET_CONFIG_NAME, - previouslyFailed); - - SET_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG); - } - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceSetRawReadInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine reads the CDROM capabilities mode page and save information - in the device extension needed for raw reads. - NOTE: this function is only valid for MMC device - -Arguments: - - DeviceExtension - device context - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PUCHAR buffer = NULL; - ULONG count = 0; - - PAGED_CODE(); - - // Check whether the device can return C2 error flag bits and the block - // error byte. If so, save this info and fill in appropriate flag during - // raw read requests. - - // Start by checking the GET_CONFIGURATION data - { - PFEATURE_DATA_CD_READ cdReadHeader = NULL; - ULONG additionalLength = sizeof(FEATURE_DATA_CD_READ) - sizeof(FEATURE_HEADER); - - cdReadHeader = DeviceFindFeaturePage(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FeatureCdRead); - - if ((cdReadHeader != NULL) && - (cdReadHeader->Header.AdditionalLength >= additionalLength) && - (cdReadHeader->C2ErrorData) - ) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p GET_CONFIG shows ability to read C2 error bits\n", - DeviceExtension->DeviceObject - )); - DeviceExtension->DeviceAdditionalData.Mmc.ReadCdC2Pointers = TRUE; // Device returns C2 error info. - } - } - - // Unfortunately, the only way to check for the ability to read R-W subcode - // information is via MODE_SENSE. Do so here, and check the C2 bit as well - // in case the drive has a firmware bug where it fails to report this ability - // in GET_CONFIG (which some drives do). - for (count = 0; count < 6; count++) - { - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb = (PCDB)srb.Cdb; - ULONG bufferLength = 0; - - // Build the MODE SENSE CDB. Try 10-byte CDB first. - if ((count/3) == 0) - { - bufferLength = sizeof(CDVD_CAPABILITIES_PAGE) + - sizeof(MODE_PARAMETER_HEADER10) + - sizeof(MODE_PARAMETER_BLOCK); - - cdb->MODE_SENSE10.OperationCode = SCSIOP_MODE_SENSE10; - cdb->MODE_SENSE10.Dbd = 1; - cdb->MODE_SENSE10.PageCode = MODE_PAGE_CAPABILITIES; - cdb->MODE_SENSE10.AllocationLength[0] = (UCHAR)(bufferLength >> 8); - cdb->MODE_SENSE10.AllocationLength[1] = (UCHAR)(bufferLength >> 0); - srb.CdbLength = 10; - } - else - { - bufferLength = sizeof(CDVD_CAPABILITIES_PAGE) + - sizeof(MODE_PARAMETER_HEADER) + - sizeof(MODE_PARAMETER_BLOCK); - - cdb->MODE_SENSE.OperationCode = SCSIOP_MODE_SENSE; - cdb->MODE_SENSE.Dbd = 1; - cdb->MODE_SENSE.PageCode = MODE_PAGE_CAPABILITIES; - cdb->MODE_SENSE.AllocationLength = (UCHAR)bufferLength; - srb.CdbLength = 6; - } - - // Set timeout value from device extension. - srb.TimeOutValue = DeviceExtension->TimeOutValue; - - buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, bufferLength, CDROM_TAG_MODE_DATA); - - if (buffer == NULL) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: cannot allocate " - "buffer, so not setting raw read info for FDO %p\n", - DeviceExtension->DeviceObject - )); - status = STATUS_INSUFFICIENT_RESOURCES; - goto FnExit; - } - - RtlZeroMemory(buffer, bufferLength); - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - buffer, - bufferLength, - FALSE, - NULL); - - if (NT_SUCCESS(status) || - (status == STATUS_DATA_OVERRUN) || - (status == STATUS_BUFFER_OVERFLOW)) - { - PCDVD_CAPABILITIES_PAGE capabilities = NULL; - - // determine where the capabilities page really is - if ((count/3) == 0) - { - PMODE_PARAMETER_HEADER10 p = (PMODE_PARAMETER_HEADER10)buffer; - capabilities = (PCDVD_CAPABILITIES_PAGE)(buffer + - sizeof(MODE_PARAMETER_HEADER10) + - (p->BlockDescriptorLength[0] * 256) + - p->BlockDescriptorLength[1]); - } - else - { - PMODE_PARAMETER_HEADER p = (PMODE_PARAMETER_HEADER)buffer; - capabilities = (PCDVD_CAPABILITIES_PAGE)(buffer + - sizeof(MODE_PARAMETER_HEADER) + - p->BlockDescriptorLength); - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p CDVD Capabilities buffer %p\n", - DeviceExtension->DeviceObject, - buffer - )); - - if (capabilities->PageCode == MODE_PAGE_CAPABILITIES) - { - if (capabilities->C2Pointers) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p supports C2 error bits in READ_CD command\n", - DeviceExtension->DeviceObject - )); - DeviceExtension->DeviceAdditionalData.Mmc.ReadCdC2Pointers = TRUE; - } - - if (capabilities->RWSupported) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p supports raw subcode in READ_CD command\n", - DeviceExtension->DeviceObject - )); - DeviceExtension->DeviceAdditionalData.Mmc.ReadCdSubCode = TRUE; - } - - break; - } - } - - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p failed %x byte mode sense, status %x\n", - DeviceExtension->DeviceObject, - (((count/3) == 0) ? 10 : 6), - status - )); - - FREE_POOL(buffer); - } - - if (count == 6) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DeviceSetRawReadInfo: FDO %p couldn't get mode sense data\n", - DeviceExtension->DeviceObject - )); - } - -FnExit: - - if (buffer) - { - FREE_POOL(buffer); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceInitializeDvd( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine sets the region of DVD drive - NOTE: this routine uses ScratchBuffer, it must be called after ScratchBuffer allocated. - -Arguments: - - Device - device object - -Return Value: - - NTSTATUS - ---*/ - -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension; - PDVD_COPY_PROTECT_KEY copyProtectKey = NULL; - PDVD_RPC_KEY rpcKey = NULL; - ULONG bufferLen = 0; - size_t bytesReturned; - - PAGED_CODE(); - - deviceExtension = DeviceGetExtension(Device); - - // check to see if we have a DVD device - if (deviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - return STATUS_SUCCESS; - } - - // we got a DVD drive. - bufferLen = DVD_RPC_KEY_LENGTH; - copyProtectKey = (PDVD_COPY_PROTECT_KEY)ExAllocatePool2(POOL_FLAG_PAGED, - bufferLen, - DVD_TAG_RPC2_CHECK); - - if (copyProtectKey == NULL) - { - return STATUS_INSUFFICIENT_RESOURCES; - } - - // get the device region - RtlZeroMemory (copyProtectKey, bufferLen); - copyProtectKey->KeyLength = DVD_RPC_KEY_LENGTH; - copyProtectKey->KeyType = DvdGetRpcKey; - - // perform IOCTL_DVD_READ_KEY - status = DvdStartSessionReadKey(deviceExtension, - IOCTL_DVD_READ_KEY, - NULL, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - &bytesReturned); - - if (NT_SUCCESS(status)) - { - rpcKey = (PDVD_RPC_KEY)copyProtectKey->KeyData; - - // TypeCode of zero means that no region has been set. - if (rpcKey->TypeCode == 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_PNP, - "DVD Initialize (%p): must choose DVD region\n", - Device)); - deviceExtension->DeviceAdditionalData.PickDvdRegion = 1; - - // set the device region code to be the same as region code on media. - if (deviceExtension->DeviceAdditionalData.Mmc.IsCssDvd) - { - DevicePickDvdRegion(Device); - } - } - } - - FREE_POOL(copyProtectKey); - - // return status of IOCTL_DVD_READ_KEY will be ignored. - return STATUS_SUCCESS; -} - - -#if (NTDDI_VERSION >= NTDDI_WIN8) -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceIsPortable( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PBOOLEAN IsPortable - ) -/*++ - -Routine Description: - - This routine checks if the volume is on a portable storage device. - -Arguments: - - DeviceExtension - device context - IsPortable - device is portable - -Return Value: - - NTSTATUS. - ---*/ - -{ - DEVPROP_BOOLEAN isInternal = DEVPROP_FALSE; - BOOLEAN isPortable = FALSE; - ULONG size = 0; - NTSTATUS status = STATUS_SUCCESS; - DEVPROPTYPE type = DEVPROP_TYPE_EMPTY; - - PAGED_CODE(); - - *IsPortable = FALSE; - - // Check to see if the underlying device object is in local machine container - status = IoGetDevicePropertyData(DeviceExtension->LowerPdo, - &DEVPKEY_Device_InLocalMachineContainer, - 0, - 0, - sizeof(isInternal), - &isInternal, - &size, - &type); - - if (!NT_SUCCESS(status)) - { - goto Cleanup; - } - - NT_ASSERT(size == sizeof(isInternal)); - NT_ASSERT(type == DEVPROP_TYPE_BOOLEAN); - - // Volume is hot-pluggable if the disk pdo container id differs from that of root device - if (isInternal == DEVPROP_TRUE) - { - goto Cleanup; - } - - isPortable = TRUE; - - // Examine the bus type to ensure that this really is a fixed device - if (DeviceExtension->DeviceDescriptor->BusType == BusTypeFibre || - DeviceExtension->DeviceDescriptor->BusType == BusTypeiScsi || - DeviceExtension->DeviceDescriptor->BusType == BusTypeRAID) - { - isPortable = FALSE; - } - - *IsPortable = isPortable; - -Cleanup: - - return status; -} -#endif - - -#pragma warning(pop) // un-sets any local warning changes - diff --git a/storage/class/cdrom/src/ioctl.c b/storage/class/cdrom/src/ioctl.c deleted file mode 100644 index f0a540fcc..000000000 --- a/storage/class/cdrom/src/ioctl.c +++ /dev/null @@ -1,9132 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - ioctl.c - -Abstract: - - Include all funtions for processing IOCTLs - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "ioctl.h" -#include "scratch.h" -#include "mmc.h" - - -#ifdef DEBUG_USE_WPP -#include "ioctl.tmh" -#endif - - -#define FirstDriveLetter 'C' -#define LastDriveLetter 'Z' - -#if DBG - LPCSTR READ_DVD_STRUCTURE_FORMAT_STRINGS[DvdMaxDescriptor+1] = { - "Physical", - "Copyright", - "DiskKey", - "BCA", - "Manufacturer", - "Unknown" - }; -#endif // DBG - -_IRQL_requires_max_(APC_LEVEL) -VOID -GetConfigurationDataConversionTypeAllToTypeOne( - _In_ FEATURE_NUMBER RequestedFeature, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -GetConfigurationDataSynthesize( - _In_reads_bytes_(InputBufferSize) PVOID InputBuffer, - _In_ ULONG InputBufferSize, - _Out_writes_bytes_(OutputBufferSize) PVOID OutputBuffer, - _In_ size_t OutputBufferSize, - _In_ FEATURE_NUMBER StartingFeature, - _In_ ULONG RequestType, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -PCDB -RequestGetScsiPassThroughCdb( - _In_ PIRP Irp - ); - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceIsPlayActive) -#pragma alloc_text(PAGE, RequestHandleGetDvdRegion) -#pragma alloc_text(PAGE, RequestHandleReadTOC) -#pragma alloc_text(PAGE, RequestHandleReadTocEx) -#pragma alloc_text(PAGE, RequestHandleGetConfiguration) -#pragma alloc_text(PAGE, RequestHandleGetDriveGeometry) -#pragma alloc_text(PAGE, RequestHandleDiskVerify) -#pragma alloc_text(PAGE, RequestHandleCheckVerify) -#pragma alloc_text(PAGE, RequestHandleFakePartitionInfo) -#pragma alloc_text(PAGE, RequestHandleEjectionControl) -#pragma alloc_text(PAGE, RequestHandleEnableStreaming) -#pragma alloc_text(PAGE, RequestHandleSendOpcInformation) -#pragma alloc_text(PAGE, RequestHandleGetPerformance) -#pragma alloc_text(PAGE, RequestHandleMcnSyncFakeIoctl) -#pragma alloc_text(PAGE, RequestHandleLoadEjectMedia) -#pragma alloc_text(PAGE, RequestHandleReserveRelease) -#pragma alloc_text(PAGE, RequestHandlePersistentReserve) -#pragma alloc_text(PAGE, DeviceHandleRawRead) -#pragma alloc_text(PAGE, DeviceHandlePlayAudioMsf) -#pragma alloc_text(PAGE, DeviceHandleReadQChannel) -#pragma alloc_text(PAGE, ReadQChannel) -#pragma alloc_text(PAGE, DeviceHandlePauseAudio) -#pragma alloc_text(PAGE, DeviceHandleResumeAudio) -#pragma alloc_text(PAGE, DeviceHandleSeekAudioMsf) -#pragma alloc_text(PAGE, DeviceHandleStopAudio) -#pragma alloc_text(PAGE, DeviceHandleGetSetVolume) -#pragma alloc_text(PAGE, DeviceHandleReadDvdStructure) -#pragma alloc_text(PAGE, ReadDvdStructure) -#pragma alloc_text(PAGE, DeviceHandleDvdEndSession) -#pragma alloc_text(PAGE, DeviceHandleDvdStartSessionReadKey) -#pragma alloc_text(PAGE, DvdStartSessionReadKey) -#pragma alloc_text(PAGE, DeviceHandleDvdSendKey) -#pragma alloc_text(PAGE, DvdSendKey) -#pragma alloc_text(PAGE, DeviceHandleSetReadAhead) -#pragma alloc_text(PAGE, DeviceHandleSetSpeed) -#pragma alloc_text(PAGE, RequestHandleExclusiveAccessQueryLockState) -#pragma alloc_text(PAGE, RequestHandleExclusiveAccessLockDevice) -#pragma alloc_text(PAGE, RequestHandleExclusiveAccessUnlockDevice) -#pragma alloc_text(PAGE, RequestHandleScsiPassThrough) -#pragma alloc_text(PAGE, RequestGetScsiPassThroughCdb) -#pragma alloc_text(PAGE, GetConfigurationDataConversionTypeAllToTypeOne) -#pragma alloc_text(PAGE, GetConfigurationDataSynthesize) - -#endif - -NTSTATUS -RequestHandleUnknownIoctl( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - All unknown IOCTLs will be forward to lower level driver. - -Arguments: - - Device - device object - Request - request to be handled - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_UNSUCCESSFUL; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - BOOLEAN syncRequired = requestContext->SyncRequired; - - ULONG sendOptionsFlags = 0; - BOOLEAN requestSent = FALSE; - - WdfRequestFormatRequestUsingCurrentType(Request); - - if (syncRequired) - { - sendOptionsFlags = WDF_REQUEST_SEND_OPTION_SYNCHRONOUS; - } - else - { - WdfRequestSetCompletionRoutine(Request, RequestDummyCompletionRoutine, NULL); - } - - status = RequestSend(deviceExtension, - Request, - deviceExtension->IoTarget, - sendOptionsFlags, - &requestSent); - - if (requestSent) - { - if (syncRequired) - { - // the request needs to be completed here. - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - } - } - else - { - // failed to send the request to IoTarget - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -DeviceIsPlayActive( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine determines if the cd is currently playing music. - -Arguments: - - Device - Device object. - -Return Value: - - BOOLEAN - TRUE if the device is playing music. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PSUB_Q_CURRENT_POSITION currentBuffer; - size_t bytesRead = 0; - - PAGED_CODE (); - - // if we don't think it is playing audio, don't bother checking. - if (!deviceExtension->DeviceAdditionalData.PlayActive) - { - return FALSE; - } - - // Allocate the required memory - NT_ASSERT(sizeof(SUB_Q_CURRENT_POSITION) >= sizeof(CDROM_SUB_Q_DATA_FORMAT)); - currentBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - sizeof(SUB_Q_CURRENT_POSITION), - CDROM_TAG_PLAY_ACTIVE); - if (currentBuffer == NULL) - { - return FALSE; - } - - // set the options in the output buffer format - ((PCDROM_SUB_Q_DATA_FORMAT) currentBuffer)->Format = IOCTL_CDROM_CURRENT_POSITION; - ((PCDROM_SUB_Q_DATA_FORMAT) currentBuffer)->Track = 0; - - // Send SCSI command to read Q Channel information. - status = ReadQChannel(deviceExtension, - NULL, - currentBuffer, - sizeof(CDROM_SUB_Q_DATA_FORMAT), - currentBuffer, - sizeof(SUB_Q_CURRENT_POSITION), - &bytesRead); - - if (!NT_SUCCESS(status)) - { - ExFreePool(currentBuffer); - return FALSE; - } - - // update the playactive flag appropriately - if (currentBuffer->Header.AudioStatus == AUDIO_STATUS_IN_PROGRESS) - { - deviceExtension->DeviceAdditionalData.PlayActive = TRUE; - } - else - { - deviceExtension->DeviceAdditionalData.PlayActive = FALSE; - } - - ExFreePool(currentBuffer); - - return deviceExtension->DeviceAdditionalData.PlayActive; -} - -NTSTATUS -RequestHandleGetInquiryData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength) -/*++ - -Routine Description: - - Handler for IOCTL_CDROM_GET_INQUIRY_DATA - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength == 0) - { - status = STATUS_BUFFER_TOO_SMALL; - } - else - { - PVOID outputBuffer = NULL; - - *DataLength = min(cdData->CachedInquiryDataByteCount, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength); - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - - if (NT_SUCCESS(status) && - (outputBuffer != NULL)) - { - // Always copy as much data as possible - RtlCopyMemory(outputBuffer, - cdData->CachedInquiryData, - *DataLength); - } - - // and finally decide between two possible status values - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < cdData->CachedInquiryDataByteCount) - { - status = STATUS_BUFFER_OVERFLOW; - } - } - - return status; -} - - -NTSTATUS -RequestHandleGetMediaTypeEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handler for IOCTL_STORAGE_GET_MEDIA_TYPES_EX - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - PGET_MEDIA_TYPES mediaTypes = NULL; - PDEVICE_MEDIA_INFO mediaInfo = NULL; //&mediaTypes->MediaInfo[0]; - ULONG sizeNeeded = 0; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - *DataLength = 0; - - // Must run below dispatch level. - if (KeGetCurrentIrql() >= DISPATCH_LEVEL) - { - NT_ASSERT(FALSE); - return STATUS_INVALID_LEVEL; - } - - sizeNeeded = sizeof(GET_MEDIA_TYPES); - - // IsMmc is static... - if (cdData->Mmc.IsMmc) - { - sizeNeeded += sizeof(DEVICE_MEDIA_INFO) * 1; // return two media types - } - - status = WdfRequestRetrieveOutputBuffer(Request, - sizeNeeded, - (PVOID*)&mediaTypes, - NULL); - - if (NT_SUCCESS(status) && - (mediaTypes != NULL)) - { - mediaInfo = &mediaTypes->MediaInfo[0]; - - RtlZeroMemory(mediaTypes, sizeNeeded); - - // ISSUE-2000/5/11-henrygab - need to update GET_MEDIA_TYPES_EX - - mediaTypes->DeviceType = cdData->DriveDeviceType; - - mediaTypes->MediaInfoCount = 1; - mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = CD_ROM; - mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1; - mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = MEDIA_READ_ONLY; - mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = DeviceExtension->DiskGeometry.Cylinders.QuadPart; - mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = DeviceExtension->DiskGeometry.TracksPerCylinder; - mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = DeviceExtension->DiskGeometry.SectorsPerTrack; - mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = DeviceExtension->DiskGeometry.BytesPerSector; - - if (cdData->Mmc.IsMmc) - { - // also report a removable disk - mediaTypes->MediaInfoCount += 1; - - mediaInfo++; - mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = RemovableMedia; - mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1; - mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = MEDIA_READ_WRITE; - mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = DeviceExtension->DiskGeometry.Cylinders.QuadPart; - mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = DeviceExtension->DiskGeometry.TracksPerCylinder; - mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = DeviceExtension->DiskGeometry.SectorsPerTrack; - mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = DeviceExtension->DiskGeometry.BytesPerSector; - mediaInfo--; - - } - - // Status will either be success, if media is present, or no media. - // It would be optimal to base from density code and medium type, but not all devices - // have values for these fields. - - // Send a TUR to determine if media is present, only if the device is not in ZPODD mode. - if ((!EXCLUSIVE_MODE(cdData) || - EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) && - ((zpoddInfo == NULL) || - (zpoddInfo->InZeroPowerState == FALSE))) - { - SCSI_REQUEST_BLOCK srb; - PCDB cdb = (PCDB)srb.Cdb; - - RtlZeroMemory(&srb,sizeof(SCSI_REQUEST_BLOCK)); - - srb.CdbLength = 6; - cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY; - - srb.TimeOutValue = CDROM_TEST_UNIT_READY_TIMEOUT; - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - NULL, - 0, - FALSE, - Request); - - if (NT_SUCCESS(status)) - { - // set the disk's media as current if we can write to it. - if (cdData->Mmc.IsMmc && cdData->Mmc.WriteAllowed) - { - mediaInfo++; - SET_FLAG(mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics, - MEDIA_CURRENTLY_MOUNTED); - mediaInfo--; - } - else - { - SET_FLAG(mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics, - MEDIA_CURRENTLY_MOUNTED); - } - } - else - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestHandleGetMediaTypeEx: GET_MEDIA_TYPES status of TUR - %lx\n", status)); - } - } - - // per legacy cdrom behavior, always return success - status = STATUS_SUCCESS; - } - - *DataLength = sizeNeeded; - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetDvdRegion( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handler for IOCTL_DVD_GET_REGION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PVOID outputBuffer = NULL; - size_t bytesReturned = 0; - - PDVD_COPY_PROTECT_KEY copyProtectKey = NULL; - ULONG keyLength = 0; - PDVD_DESCRIPTOR_HEADER dvdHeader; - PDVD_COPYRIGHT_DESCRIPTOR copyRightDescriptor; - PDVD_REGION dvdRegion = NULL; - PDVD_READ_STRUCTURE readStructure = NULL; - PDVD_RPC_KEY rpcKey; - - PAGED_CODE (); - - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "RequestHandleGetDvdRegion: [%p] IOCTL_DVD_GET_REGION\n", Request)); - - *DataLength = 0; - - // reject the request if it's not a DVD device. - if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - sizeof(DVD_REGION), - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - // figure out how much data buffer we need - keyLength = max((sizeof(DVD_DESCRIPTOR_HEADER) + sizeof(DVD_COPYRIGHT_DESCRIPTOR)), - sizeof(DVD_READ_STRUCTURE)); - keyLength = max(keyLength, - DVD_RPC_KEY_LENGTH); - - // round the size to nearest ULONGLONG -- why? - // could this be to deal with device alignment issues? - keyLength += sizeof(ULONGLONG) - (keyLength & (sizeof(ULONGLONG) - 1)); - - readStructure = ExAllocatePool2(POOL_FLAG_NON_PAGED, - keyLength, - DVD_TAG_READ_KEY); - if (readStructure == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory (readStructure, keyLength); - readStructure->Format = DvdCopyrightDescriptor; - - // use READ_STRUCTURE to read copyright descriptor - status = ReadDvdStructure(DeviceExtension, - Request, - readStructure, - keyLength, - readStructure, - sizeof(DVD_DESCRIPTOR_HEADER) + sizeof(DVD_COPYRIGHT_DESCRIPTOR), - &bytesReturned); - } - - if (NT_SUCCESS(status)) - { - // we got the copyright descriptor, so now get the region if possible - dvdHeader = (PDVD_DESCRIPTOR_HEADER) readStructure; - copyRightDescriptor = (PDVD_COPYRIGHT_DESCRIPTOR) dvdHeader->Data; - - // the original irp's systembuffer has a copy of the info that - // should be passed down in the request - dvdRegion = outputBuffer; - - dvdRegion->CopySystem = copyRightDescriptor->CopyrightProtectionType; - dvdRegion->RegionData = copyRightDescriptor->RegionManagementInformation; - - // now reuse the buffer to request the copy protection info - copyProtectKey = (PDVD_COPY_PROTECT_KEY) readStructure; - RtlZeroMemory (copyProtectKey, DVD_RPC_KEY_LENGTH); - copyProtectKey->KeyLength = DVD_RPC_KEY_LENGTH; - copyProtectKey->KeyType = DvdGetRpcKey; - - // send a request for READ_KEY - status = DvdStartSessionReadKey(DeviceExtension, - IOCTL_DVD_READ_KEY, - Request, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - copyProtectKey, - DVD_RPC_KEY_LENGTH, - &bytesReturned); - } - - if (NT_SUCCESS(status)) - { - // the request succeeded. if a supported scheme is returned, - // then return the information to the caller - rpcKey = (PDVD_RPC_KEY) copyProtectKey->KeyData; - - if (rpcKey->RpcScheme == 1) - { - if (rpcKey->TypeCode) - { - dvdRegion->SystemRegion = ~rpcKey->RegionMask; - dvdRegion->ResetCount = rpcKey->UserResetsAvailable; - } - else - { - // the drive has not been set for any region - dvdRegion->SystemRegion = 0; - dvdRegion->ResetCount = rpcKey->UserResetsAvailable; - } - - *DataLength = sizeof(DVD_REGION); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestHandleGetDvdRegion => rpcKey->RpcScheme != 1\n")); - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - // Clean up - if (readStructure != NULL) - { - ExFreePool(readStructure); - } - - return status; -} - -NTSTATUS -RequestValidateRawRead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_RAW_READ - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - PVOID inputBuffer = NULL; - PIRP irp = NULL; - PIO_STACK_LOCATION currentStack = NULL; - - LARGE_INTEGER startingOffset = {0}; - ULONGLONG transferBytes = 0; - ULONGLONG endOffset; - ULONGLONG mdlBytes; - RAW_READ_INFO rawReadInfo = {0}; - - *DataLength = 0; - - irp = WdfRequestWdmGetIrp(Request); - currentStack = IoGetCurrentIrpStackLocation(irp); - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - // Check that ending sector is on disc and buffers are there and of - // correct size. - if (NT_SUCCESS(status) && - (RequestParameters.Parameters.DeviceIoControl.Type3InputBuffer == NULL)) - { - // This is a call from user space. This is the only time that we need to validate parameters. - // Validate the input and get the input buffer into Type3InputBuffer - // so the rest of the code will be uniform. - if (inputBuffer != NULL) - { - currentStack->Parameters.DeviceIoControl.Type3InputBuffer = inputBuffer; - RequestParameters.Parameters.DeviceIoControl.Type3InputBuffer = inputBuffer; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(RAW_READ_INFO)) - { - *DataLength = sizeof(RAW_READ_INFO); - status = STATUS_BUFFER_TOO_SMALL; - } - } - else - { - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // Since this ioctl is METHOD_OUT_DIRECT, we need to copy away the input buffer before interpreting it. - // This prevents a malicious app from messing with the input buffer while we are interpreting it. - rawReadInfo = *(PRAW_READ_INFO)RequestParameters.Parameters.DeviceIoControl.Type3InputBuffer; - - startingOffset.QuadPart = rawReadInfo.DiskOffset.QuadPart; - - if ((rawReadInfo.TrackMode == CDDA) || - (rawReadInfo.TrackMode == YellowMode2) || - (rawReadInfo.TrackMode == XAForm2) ) - { - transferBytes = (ULONGLONG)rawReadInfo.SectorCount * RAW_SECTOR_SIZE; - } - else if (rawReadInfo.TrackMode == RawWithSubCode) - { - transferBytes = (ULONGLONG)rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_SUBCODE_SIZE; - } - else if (rawReadInfo.TrackMode == RawWithC2) - { - transferBytes = (ULONGLONG)rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_C2_SIZE; - } - else if (rawReadInfo.TrackMode == RawWithC2AndSubCode) - { - transferBytes = (ULONGLONG)rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_C2_AND_SUBCODE_SIZE; - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid TrackMode type %x for XA read\n", - rawReadInfo.TrackMode - )); - } - - endOffset = (ULONGLONG)rawReadInfo.SectorCount * COOKED_SECTOR_SIZE; - endOffset += startingOffset.QuadPart; - - // check for overflows.... - if (rawReadInfo.SectorCount == 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for XA " - "Read (zero sectors requested)\n")); - status = STATUS_INVALID_PARAMETER; - } - else if (transferBytes < (ULONGLONG)(rawReadInfo.SectorCount)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for XA " - "Read (TransferBytes Overflow)\n")); - status = STATUS_INVALID_PARAMETER; - } - else if (endOffset < (ULONGLONG)startingOffset.QuadPart) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for XA " - "Read (EndingOffset Overflow)\n")); - status = STATUS_INVALID_PARAMETER; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < transferBytes) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for XA " - "Read (Bad buffer size)\n")); - status = STATUS_INVALID_PARAMETER; - } - else if (endOffset > (ULONGLONG)DeviceExtension->PartitionLength.QuadPart) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for XA " - "Read (Request Out of Bounds)\n")); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // cannot validate the MdlAddress, since it is not included in any - // other location per the DDK and file system calls. - - // validate the mdl describes at least the number of bytes - // requested from us. - mdlBytes = (ULONGLONG)MmGetMdlByteCount(irp->MdlAddress); - if (mdlBytes < transferBytes) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid MDL %s, Irp %p\n", - "size (5)", irp)); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // check the buffer for alignment - // This is important for x86 as some busses (ie ATAPI) - // require word-aligned buffers. - if ( ((ULONG_PTR)MmGetMdlVirtualAddress(irp->MdlAddress)) & - DeviceExtension->AdapterDescriptor->AlignmentMask ) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: Invalid I/O parameters for " - "XA Read (Buffer %p not aligned with mask %x\n", - RequestParameters.Parameters.DeviceIoControl.Type3InputBuffer, - DeviceExtension->AdapterDescriptor->AlignmentMask)); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // Validate the request is not too large for the adapter - BOOLEAN bufferIsPageAligned = FALSE; - ULONG maxLength = 0; - - // if buffer is not page-aligned, then subtract one as the - // transfer could cross a page boundary. - if ((((ULONG_PTR)MmGetMdlVirtualAddress(irp->MdlAddress)) & (PAGE_SIZE-1)) == 0) - { - bufferIsPageAligned = TRUE; - } - - if (bufferIsPageAligned) - { - maxLength = cdData->MaxPageAlignedTransferBytes; - } - else - { - maxLength = cdData->MaxUnalignedTransferBytes; - } - - if (transferBytes > maxLength) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestValidateRawRead: The XA Read (type %x) would require %I64x bytes, " - "but the adapter can only handle %x bytes (for a%saligned buffer)\n", - rawReadInfo.TrackMode, - transferBytes, - maxLength, - (bufferIsPageAligned ? " " : "n un") - )); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // - // HACKHACK - REF #0001 - // The retry count will be in this irp's IRP_MN function, - // as the new irp was freed, and we therefore cannot use - // this irp's next stack location for this function. - // This may be a good location to store this info for - // when we remove RAW_READ (mode switching), as we will - // no longer have the nextIrpStackLocation to play with - // when that occurs - // - currentStack->MinorFunction = MAXIMUM_RETRIES; // HACKHACK - REF #0001 - } - - return status; -} - -NTSTATUS -RequestValidateReadTocEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_READ_TOC_EX - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PCDROM_READ_TOC_EX inputBuffer = NULL; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_READ_TOC_EX)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - MINIMUM_CDROM_READ_TOC_EX_SIZE) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = MINIMUM_CDROM_READ_TOC_EX_SIZE; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > - ((USHORT)-1)) - { - status = STATUS_INVALID_PARAMETER; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - status = STATUS_INVALID_PARAMETER; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if ((inputBuffer->Reserved1 != 0) || - (inputBuffer->Reserved2 != 0) || - (inputBuffer->Reserved3 != 0)) - { - status = STATUS_INVALID_PARAMETER; - } - // NOTE: when adding new formats, ensure that first two bytes - // specify the amount of additional data available. - else if ((inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_TOC ) || - (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_FULL_TOC) || - (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_CDTEXT )) - { - // SessionTrack field is used - } - else if ((inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_SESSION) || - (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_PMA) || - (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_ATIP)) - { - // SessionTrack field is reserved - if (inputBuffer->SessionTrack != 0) - { - status = STATUS_INVALID_PARAMETER; - } - } - else - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateReadToc( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_READ_TOC - -Arguments: - - DeviceExtension - device context - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(CDROM_TOC)) - { - // they didn't request the entire TOC -- use _EX version - // for partial transfers and such. - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(CDROM_TOC); - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - status = STATUS_INVALID_PARAMETER; - } - - return status; -} - -NTSTATUS -RequestValidateGetLastSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_GET_LAST_SESSION - -Arguments: - - DeviceExtension - device context - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(CDROM_TOC_SESSION_DATA)) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(CDROM_TOC_SESSION_DATA); - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - status = STATUS_INVALID_PARAMETER; - } - - return status; -} - -NTSTATUS -RequestValidateReadQChannel( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_READ_Q_CHANNEL - -Arguments: - - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_SUB_Q_DATA_FORMAT inputBuffer = NULL; - ULONG transferByteCount = 0; - - *DataLength = 0; - - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_SUB_Q_DATA_FORMAT)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - // check for all valid types of request - if (inputBuffer->Format == IOCTL_CDROM_CURRENT_POSITION) - { - transferByteCount = sizeof(SUB_Q_CURRENT_POSITION); - } - else if (inputBuffer->Format == IOCTL_CDROM_MEDIA_CATALOG) - { - transferByteCount = sizeof(SUB_Q_MEDIA_CATALOG_NUMBER); - } - else if (inputBuffer->Format == IOCTL_CDROM_TRACK_ISRC) - { - transferByteCount = sizeof(SUB_Q_TRACK_ISRC); - } - else - { - // Format not valid - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - transferByteCount) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = transferByteCount; - } - } - - return status; -} - -NTSTATUS -RequestValidateDvdReadStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_DVD_READ_STRUCTURE - -Arguments: - - DeviceExtension - device context - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(DVD_READ_STRUCTURE)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestValidateDvdReadStructure - input buffer " - "length too small (was %d should be %d)\n", - (int)RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - sizeof(DVD_READ_STRUCTURE))); - status = STATUS_INVALID_PARAMETER; - } - else if(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(READ_DVD_STRUCTURES_HEADER)) - { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestValidateDvdReadStructure - output buffer " - "cannot hold header information\n")); - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(READ_DVD_STRUCTURES_HEADER); - } - else if(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > - MAXUSHORT) - { - // key length must fit in two bytes - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestValidateDvdReadStructure - output buffer " - "too large\n")); - status = STATUS_INVALID_PARAMETER; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - status = STATUS_INVALID_PARAMETER; - } - else if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - // reject the request if it's not a DVD device. - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - return status; -} - -NTSTATUS -RequestValidateDvdStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_DVD_START_SESSION - -Arguments: - - DeviceExtension - device context - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - if(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(DVD_SESSION_ID)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestValidateDvdStartSession: DVD_START_SESSION - output " - "buffer too small\n")); - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(DVD_SESSION_ID); - } - else if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - // reject the request if it's not a DVD device. - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - return status; -} - -NTSTATUS -RequestValidateDvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_DVD_SEND_KEY, IOCTL_DVD_SEND_KEY2 - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_COPY_PROTECT_KEY key = NULL; - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &key, - NULL); - - if (NT_SUCCESS(status)) - { - if((RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(DVD_COPY_PROTECT_KEY)) || - (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != key->KeyLength)) - { - - // - // Key is too small to have a header or the key length doesn't - // match the input buffer length. Key must be invalid - // - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestValidateDvdSendKey: [%p] IOCTL_DVD_SEND_KEY - " - "key is too small or does not match KeyLength\n", - Request)); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - // allow only certain key type (non-destructive) to go through - // IOCTL_DVD_SEND_KEY (which only requires READ access to the device) - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_DVD_SEND_KEY) - { - if ((key->KeyType != DvdChallengeKey) && - (key->KeyType != DvdBusKey2) && - (key->KeyType != DvdInvalidateAGID)) - { - status = STATUS_INVALID_PARAMETER; - } - } - else if ((key->KeyType != DvdChallengeKey) && - (key->KeyType != DvdBusKey1) && - (key->KeyType != DvdBusKey2) && - (key->KeyType != DvdTitleKey) && - (key->KeyType != DvdAsf) && - (key->KeyType != DvdSetRpcKey) && - (key->KeyType != DvdGetRpcKey) && - (key->KeyType != DvdDiskKey) && - (key->KeyType != DvdInvalidateAGID)) - { - status = STATUS_INVALID_PARAMETER; - } - else if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - // reject the request if it's not a DVD device. - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - return status; -} - -NTSTATUS -RequestValidateGetConfiguration( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_GET_CONFIGURATION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(GET_CONFIGURATION_HEADER)) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(GET_CONFIGURATION_HEADER); - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > 0xffff) - { - // output buffer is too large - status = STATUS_INVALID_BUFFER_SIZE; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - // buffer is not proper size multiple - status = STATUS_INVALID_PARAMETER; - } - - if (NT_SUCCESS(status)) - { - -#if BUILD_WOW64_ENABLED && defined(_WIN64) - - if (WdfRequestIsFrom32BitProcess(Request)) - { - PGET_CONFIGURATION_IOCTL_INPUT32 inputBuffer = NULL; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(GET_CONFIGURATION_IOCTL_INPUT32)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - // - // also verify the arguments are reasonable. - // - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->Feature > 0xffff) - { - status = STATUS_INVALID_PARAMETER; - } - else if ((inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) && - (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT) && - (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL)) - { - status = STATUS_INVALID_PARAMETER; - } - else if (inputBuffer->Reserved[0] || inputBuffer->Reserved[1]) - { - status = STATUS_INVALID_PARAMETER; - } - } - } - else - -#endif - - { - PGET_CONFIGURATION_IOCTL_INPUT inputBuffer = NULL; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(GET_CONFIGURATION_IOCTL_INPUT)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - // also verify the arguments are reasonable. - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->Feature > 0xffff) - { - status = STATUS_INVALID_PARAMETER; - } - else if ((inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) && - (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT) && - (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL)) - { - status = STATUS_INVALID_PARAMETER; - } - else if (inputBuffer->Reserved[0] || inputBuffer->Reserved[1]) - { - status = STATUS_INVALID_PARAMETER; - } - } - } - } - - return status; -} - -NTSTATUS -RequestValidateSetSpeed( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_SET_SPEED - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PCDROM_SET_SPEED inputBuffer = NULL; - ULONG requiredLength = 0; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(CDROM_SET_SPEED)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - // Get the request type using CDROM_SET_SPEED structure - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_SET_SPEED), - &inputBuffer, - NULL); - - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->RequestType > CdromSetStreaming) - { - // Unknown request type. - status = STATUS_INVALID_PARAMETER; - } - else if (inputBuffer->RequestType == CdromSetSpeed) - { - requiredLength = sizeof(CDROM_SET_SPEED); - } - else - { - // Don't send SET STREAMING command if this is not a MMC compliant device - if (cdData->Mmc.IsMmc == FALSE) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - - requiredLength = sizeof(CDROM_SET_STREAMING); - } - } - - if (NT_SUCCESS(status)) - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < requiredLength) - { - // Input buffer too small - status = STATUS_INFO_LENGTH_MISMATCH; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsReadMediaKeyBlock( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_READ_MEDIA_KEY_BLOCK - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PAACS_LAYER_NUMBER layerNumber = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(AACS_LAYER_NUMBER)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < 8) - { - // This is a variable-length structure, but we're pretty sure - // it can never be less than eight bytes... - *DataLength = 8; - status = STATUS_BUFFER_TOO_SMALL; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &layerNumber, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*layerNumber > 255) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_START_SESSION - -Arguments: - - DeviceExtension - device context - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(DVD_SESSION_ID)) - { - *DataLength = sizeof(DVD_SESSION_ID); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(DVD_SESSION_ID)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - return status; -} - -NTSTATUS -RequestValidateAacsSendCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_SEND_CERTIFICATE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PAACS_SEND_CERTIFICATE inputBuffer = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(AACS_SEND_CERTIFICATE)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->SessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsGetCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_GET_CERTIFICATE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PDVD_SESSION_ID sessionId = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_CERTIFICATE)) - { - *DataLength = sizeof(AACS_CERTIFICATE); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_CERTIFICATE)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*sessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsGetChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_GET_CHALLENGE_KEY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PDVD_SESSION_ID sessionId = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_CHALLENGE_KEY)) - { - *DataLength = sizeof(AACS_CHALLENGE_KEY); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_CHALLENGE_KEY)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*sessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsSendChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_SEND_CHALLENGE_KEY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PAACS_SEND_CHALLENGE_KEY inputBuffer = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(AACS_SEND_CHALLENGE_KEY)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->SessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsReadVolumeId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_READ_VOLUME_ID - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PDVD_SESSION_ID sessionId = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_VOLUME_ID)) - { - *DataLength = sizeof(AACS_VOLUME_ID); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_VOLUME_ID)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*sessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsReadSerialNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_READ_SERIAL_NUMBER - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PDVD_SESSION_ID sessionId = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_SERIAL_NUMBER)) - { - *DataLength = sizeof(AACS_SERIAL_NUMBER); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_SERIAL_NUMBER)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*sessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsReadMediaId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_READ_MEDIA_ID - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PDVD_SESSION_ID sessionId = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_MEDIA_ID)) - { - *DataLength = sizeof(AACS_MEDIA_ID); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_MEDIA_ID)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (*sessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateAacsBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_READ_BINDING_NONCE - IOCTL_AACS_GENERATE_BINDING_NONCE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PAACS_READ_BINDING_NONCE inputBuffer = NULL; - - *DataLength = 0; - - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(AACS_READ_BINDING_NONCE)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(AACS_BINDING_NONCE)) - { - *DataLength = sizeof(AACS_BINDING_NONCE); - status = STATUS_BUFFER_TOO_SMALL; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > sizeof(AACS_BINDING_NONCE)) - { - status = STATUS_INVALID_BUFFER_SIZE; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->SessionId > MAX_COPY_PROTECT_AGID) - { - status = STATUS_INVALID_PARAMETER; - } - else if (inputBuffer->NumberOfSectors > 255) - { - status = STATUS_INVALID_PARAMETER; - } - else if (inputBuffer->StartLba > MAXULONG) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - -NTSTATUS -RequestValidateExclusiveAccess( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_CDROM_EXCLUSIVE_ACCESS - -Arguments: - - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_EXCLUSIVE_ACCESS exclusiveAccess = NULL; - - *DataLength = 0; - - if (KeGetCurrentIrql() != PASSIVE_LEVEL) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "RequestValidateExclusiveAccess: IOCTL must be called at passive level.\n")); - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(CDROM_EXCLUSIVE_ACCESS)) - { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "RequestValidateExclusiveAccess: Input buffer too small\n")); - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &exclusiveAccess, - NULL); - } - - if (NT_SUCCESS(status)) - { - switch (exclusiveAccess->RequestType) - { - case ExclusiveAccessQueryState: - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(CDROM_EXCLUSIVE_LOCK_STATE)) - { - // - // Output buffer too small. - // - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "RequestValidateExclusiveAccess: Output buffer too small\n")); - *DataLength = sizeof(CDROM_EXCLUSIVE_LOCK_STATE); - status = STATUS_BUFFER_TOO_SMALL; - } - break; - } - - case ExclusiveAccessLockDevice: - { - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_EXCLUSIVE_LOCK)) - { - // - // Input buffer too small - // - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "RequestValidateExclusiveAccess: Input buffer too small\n")); - status = STATUS_INFO_LENGTH_MISMATCH; - } - break; - } - case ExclusiveAccessUnlockDevice: - { - // - // Nothing to check - // - break; - } - - default: - { - // - // Unknown request type. - // - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "RequestValidateExclusiveAccess: Invalid request type\n")); - status = STATUS_INVALID_PARAMETER; - } - } - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessQueryLockState( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_EXCLUSIVE_ACCESS with ExclusiveAccessQueryState - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cdData = &deviceExtension->DeviceAdditionalData; - PCDROM_EXCLUSIVE_LOCK_STATE exclusiveLockState = NULL; - - PAGED_CODE(); - - status = WdfRequestRetrieveOutputBuffer(Request, - sizeof(CDROM_EXCLUSIVE_LOCK_STATE), - &exclusiveLockState, - NULL); - NT_ASSERT(NT_SUCCESS(status)); - - RtlZeroMemory(exclusiveLockState, sizeof(CDROM_EXCLUSIVE_LOCK_STATE)); - - if (EXCLUSIVE_MODE(cdData)) - { - // Device is locked for exclusive use - exclusiveLockState->LockState = TRUE; - - RtlCopyMemory(&exclusiveLockState->CallerName, - &cdData->CallerName, - CDROM_EXCLUSIVE_CALLER_LENGTH); - - } - else - { - // Device is not locked - exclusiveLockState->LockState = FALSE; - } - - RequestCompletion(deviceExtension, Request, status, sizeof(CDROM_EXCLUSIVE_LOCK_STATE)); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessLockDevice( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_EXCLUSIVE_ACCESS with ExclusiveAccessLockDevice - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cdData = &deviceExtension->DeviceAdditionalData; - PCDROM_EXCLUSIVE_LOCK exclusiveLock = NULL; - PIO_ERROR_LOG_PACKET logEntry; - - WDFFILEOBJECT fileObject = NULL; - ULONG idx = 0; - ULONG nameLength = 0; - - PAGED_CODE(); - - fileObject = WdfRequestGetFileObject(Request); - - if (fileObject == NULL) - { - status = STATUS_INVALID_HANDLE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: FileObject is NULL, cannot grant exclusive access\n")); - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_EXCLUSIVE_LOCK), - &exclusiveLock, - NULL); - } - - if (NT_SUCCESS(status)) - { - // Validate the caller name string - for (idx = 0; (idx < CDROM_EXCLUSIVE_CALLER_LENGTH) && (exclusiveLock->CallerName[idx] != '\0'); idx++) - { - if (!ValidChar(exclusiveLock->CallerName[idx])) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: Invalid characters in caller name\n")); - // error out - status = STATUS_INVALID_PARAMETER; - break; - } - } - } - - if (NT_SUCCESS(status)) - { - if ((idx == 0) || (idx >= CDROM_EXCLUSIVE_CALLER_LENGTH)) - { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: Not a valid null terminated string.\n")); - //error out - status = STATUS_INVALID_PARAMETER; - } - else - { - nameLength = idx+1; // Add 1 for the NULL character - NT_ASSERT(nameLength <= CDROM_EXCLUSIVE_CALLER_LENGTH); - } - } - - // If the file system is still mounted on this device fail the request, - // unless the force lock flag is set. - if (NT_SUCCESS(status)) - { - if ((TEST_FLAG(exclusiveLock->Access.Flags, CDROM_LOCK_IGNORE_VOLUME) == FALSE) && - IsVolumeMounted(deviceExtension->DeviceObject)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: Unable to lock device, file system mounted\n")); - status = STATUS_INVALID_DEVICE_STATE; - } - } - - // Lock the device for exclusive access if the device is not already locked - if (NT_SUCCESS(status)) - { - if (InterlockedCompareExchangePointer((PVOID)&cdData->ExclusiveOwner, (PVOID)fileObject, NULL) == NULL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: Entering exclusive mode! Device locked by file object %p\n", fileObject)); - - // Zero out the CallerName before storing it in the extension - RtlZeroMemory(&cdData->CallerName, CDROM_EXCLUSIVE_CALLER_LENGTH); - RtlCopyMemory(&cdData->CallerName, - &exclusiveLock->CallerName, - nameLength); - - // Send Exclusive Lock notification - DeviceSendNotification(deviceExtension, - &GUID_IO_CDROM_EXCLUSIVE_LOCK, - 0, - NULL); - - // Log an informational event with the caller name - logEntry = IoAllocateErrorLogEntry( - deviceExtension->DeviceObject, - sizeof(IO_ERROR_LOG_PACKET) + CDROM_EXCLUSIVE_CALLER_LENGTH); - - if (logEntry != NULL) - { - PUCHAR dumpDataPtr = (PUCHAR) logEntry->DumpData; - - logEntry->FinalStatus = STATUS_SUCCESS; - logEntry->ErrorCode = IO_CDROM_EXCLUSIVE_LOCK; - logEntry->SequenceNumber = 0; - logEntry->MajorFunctionCode = IRP_MJ_DEVICE_CONTROL; - logEntry->IoControlCode = IOCTL_CDROM_EXCLUSIVE_ACCESS; - logEntry->RetryCount = 0; - logEntry->UniqueErrorValue = 0x1; - logEntry->DumpDataSize = CDROM_EXCLUSIVE_CALLER_LENGTH; - - RtlCopyMemory(dumpDataPtr, - (PUCHAR)&cdData->CallerName, - CDROM_EXCLUSIVE_CALLER_LENGTH); - - // Write the error log packet. - IoWriteErrorLogEntry(logEntry); - } - - } - else - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessLockDevice: Unable to lock device, device already locked.\n")); - - status = STATUS_ACCESS_DENIED; - } - } - - RequestCompletion(deviceExtension, Request, status, 0); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessUnlockDevice( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_EXCLUSIVE_ACCESS with ExclusiveAccessUnlockDevice - -Arguments: - - Device - device handle - Request - request to be handled - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_EXCLUSIVE_ACCESS exclusiveAccess = NULL; - WDFFILEOBJECT fileObject = NULL; - - PAGED_CODE(); - - fileObject = WdfRequestGetFileObject(Request); - - if (fileObject == NULL) - { - // The device can be unlocked from exclusive mode only via the file object which locked it. - status = STATUS_INVALID_HANDLE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleExclusiveAccessUnlockDevice: FileObject is NULL, cannot release exclusive access\n")); - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(PCDROM_EXCLUSIVE_ACCESS), - &exclusiveAccess, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = DeviceUnlockExclusive(deviceExtension, fileObject, - TEST_FLAG(exclusiveAccess->Flags, CDROM_NO_MEDIA_NOTIFICATIONS)); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "RequestHandleExclusiveAccessUnlockDevice: Device unlocked\n")); - } - - RequestCompletion(deviceExtension, Request, status, 0); - - return status; -} - -NTSTATUS -RequestHandleQueryPropertyRetrieveCachedData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_QUERY_PROPERTY when the required data is cached. - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSTORAGE_PROPERTY_QUERY inputBuffer = NULL; - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - if (inputBuffer->PropertyId == StorageDeviceProperty) - { - // check output buffer length - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength == 0) - { - // According to MSDN, an output buffer of size 0 can be used to determine if a property exists - // so this must be a success case with no data transferred - *DataLength = 0; - status = STATUS_SUCCESS; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_DESCRIPTOR_HEADER)) - { - // Buffer too small - *DataLength = DeviceExtension->DeviceDescriptor->Size; - status = STATUS_BUFFER_TOO_SMALL; - } - else - { - PSTORAGE_DEVICE_DESCRIPTOR outputDescriptor = NULL; - CHAR* localDescriptorBuffer = (CHAR*)DeviceExtension->DeviceDescriptor; - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputDescriptor, - NULL); - - if (NT_SUCCESS(status)) - { - // transfer as much data out as the buffer will allow - *DataLength = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DeviceExtension->DeviceDescriptor->Size); - - RtlCopyMemory(outputDescriptor, - DeviceExtension->DeviceDescriptor, - *DataLength); - - // walk through and update offset variables to reflect data that didn't make it into the output buffer - if ((*DataLength >= RTL_SIZEOF_THROUGH_FIELD(STORAGE_DEVICE_DESCRIPTOR, VendorIdOffset)) && - (DeviceExtension->DeviceDescriptor->VendorIdOffset != 0) && - (DeviceExtension->DeviceDescriptor->VendorIdOffset != 0xFFFFFFFF)) - { - // set VendorIdOffset appropriately - if (*DataLength < - (DeviceExtension->DeviceDescriptor->VendorIdOffset + strlen(localDescriptorBuffer + DeviceExtension->DeviceDescriptor->VendorIdOffset))) - { - outputDescriptor->VendorIdOffset = 0; - } - } - - if ((*DataLength >= RTL_SIZEOF_THROUGH_FIELD(STORAGE_DEVICE_DESCRIPTOR, ProductIdOffset)) && - (DeviceExtension->DeviceDescriptor->ProductIdOffset != 0) && - (DeviceExtension->DeviceDescriptor->ProductIdOffset != 0xFFFFFFFF)) - { - // set ProductIdOffset appropriately - if (*DataLength < - (DeviceExtension->DeviceDescriptor->ProductIdOffset + strlen(localDescriptorBuffer + DeviceExtension->DeviceDescriptor->ProductIdOffset))) - { - outputDescriptor->ProductIdOffset = 0; - } - } - - if ((*DataLength >= RTL_SIZEOF_THROUGH_FIELD(STORAGE_DEVICE_DESCRIPTOR, ProductRevisionOffset)) && - (DeviceExtension->DeviceDescriptor->ProductRevisionOffset != 0) && - (DeviceExtension->DeviceDescriptor->ProductRevisionOffset != 0xFFFFFFFF)) - { - // set ProductRevisionOffset appropriately - if (*DataLength < - (DeviceExtension->DeviceDescriptor->ProductRevisionOffset + strlen(localDescriptorBuffer + DeviceExtension->DeviceDescriptor->ProductRevisionOffset))) - { - outputDescriptor->ProductRevisionOffset = 0; - } - } - - if ((*DataLength >= RTL_SIZEOF_THROUGH_FIELD(STORAGE_DEVICE_DESCRIPTOR, SerialNumberOffset)) && - (DeviceExtension->DeviceDescriptor->SerialNumberOffset != 0) && - (DeviceExtension->DeviceDescriptor->SerialNumberOffset != 0xFFFFFFFF)) - { - // set SerialNumberOffset appropriately - if (*DataLength < - (DeviceExtension->DeviceDescriptor->SerialNumberOffset + strlen(localDescriptorBuffer + DeviceExtension->DeviceDescriptor->SerialNumberOffset))) - { - // NOTE: setting this to 0 since that is what most port drivers do - // [this could cause issues with SCSI port devices whose clients expect -1 in this field] - outputDescriptor->SerialNumberOffset = 0; - } - } - status = STATUS_SUCCESS; - } - } - } //end of StorageDeviceProperty - else if (inputBuffer->PropertyId == StorageAdapterProperty) - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength == 0) - { - // According to MSDN, an output buffer of size 0 can be used to determine if a property exists - // so this must be a success case with no data transferred - *DataLength = 0; - status = STATUS_SUCCESS; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_DESCRIPTOR_HEADER)) - { - // Buffer too small - *DataLength = DeviceExtension->AdapterDescriptor->Size; - status = STATUS_BUFFER_TOO_SMALL; - } - else - { - PSTORAGE_ADAPTER_DESCRIPTOR outputDescriptor = NULL; - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputDescriptor, - NULL); - if (NT_SUCCESS(status)) - { - // copy as much data out as the buffer will allow - *DataLength = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DeviceExtension->AdapterDescriptor->Size); - - RtlCopyMemory(outputDescriptor, - DeviceExtension->AdapterDescriptor, - *DataLength); - - // set status - status = STATUS_SUCCESS; - } - } - } - } - - return status; -} - -NTSTATUS -RequestHandleQueryPropertyDeviceUniqueId( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_QUERY_PROPERTY with StorageDeviceUniqueIdProperty. - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PSTORAGE_PROPERTY_QUERY inputBuffer = NULL; - PSTORAGE_DESCRIPTOR_HEADER descHeader = NULL; - size_t outLength = 0; - WDF_REQUEST_PARAMETERS requestParameters; - - // Get the Request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - status = WdfRequestRetrieveInputBuffer(Request, - requestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - BOOLEAN overflow = FALSE; - BOOLEAN infoFound = FALSE; - - // Must run at less then dispatch. - if (KeGetCurrentIrql() >= DISPATCH_LEVEL) - { - NT_ASSERT(FALSE); - outLength = 0; - status = STATUS_INVALID_LEVEL; - } - else if (inputBuffer->QueryType == PropertyExistsQuery) - { - outLength = 0; - status = STATUS_SUCCESS; - } - else if (inputBuffer->QueryType != PropertyStandardQuery) - { - outLength = 0; - status = STATUS_NOT_SUPPORTED; - } - else - { - // Check AdditionalParameters validity. - if (inputBuffer->AdditionalParameters[0] == DUID_INCLUDE_SOFTWARE_IDS) - { - // Do nothing - } - else if (inputBuffer->AdditionalParameters[0] == DUID_HARDWARE_IDS_ONLY) - { - // Do nothing - } - else - { - outLength = 0; - status = STATUS_INVALID_PARAMETER; - } - - if (NT_SUCCESS(status) && - (outLength < sizeof(STORAGE_DESCRIPTOR_HEADER))) - { - outLength = 0; - status = STATUS_INFO_LENGTH_MISMATCH; - } - } - - // From this point forward the status depends on the overflow - // and infoFound flags. - if (NT_SUCCESS(status)) - { - outLength = requestParameters.Parameters.DeviceIoControl.OutputBufferLength; - status = WdfRequestRetrieveOutputBuffer(Request, - requestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &descHeader, - NULL); - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(descHeader, outLength); - - descHeader->Version = DUID_VERSION_1; - descHeader->Size = sizeof(STORAGE_DEVICE_UNIQUE_IDENTIFIER); - - // Try to build device unique id from StorageDeviceIdProperty. - status = RequestDuidGetDeviceIdProperty(deviceExtension, - Request, - requestParameters, - &outLength); - - if (status == STATUS_BUFFER_OVERFLOW) - { - overflow = TRUE; - } - - if (NT_SUCCESS(status)) - { - infoFound = TRUE; - } - - // Try to build device unique id from StorageDeviceProperty. - status = RequestDuidGetDeviceProperty(deviceExtension, - Request, - requestParameters, - &outLength); - - if (status == STATUS_BUFFER_OVERFLOW) - { - overflow = TRUE; - } - - if (NT_SUCCESS(status)) - { - infoFound = TRUE; - } - - // Return overflow, success, or a generic error. - if (overflow) - { - // If output buffer is STORAGE_DESCRIPTOR_HEADER, then return - // success to the user. Otherwise, send an error so the user - // knows a larger buffer is required. - if (outLength == sizeof(STORAGE_DESCRIPTOR_HEADER)) - { - status = STATUS_SUCCESS; - } - else - { - outLength = (ULONG)WdfRequestGetInformation(Request); - status = STATUS_BUFFER_OVERFLOW; - } - - } - else if (infoFound) - { - status = STATUS_SUCCESS; - - // Exercise the compare routine. This should always succeed. - NT_ASSERT(DuidExactMatch == CompareStorageDuids((PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader, - (PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader)); - - } - else - { - status = STATUS_NOT_FOUND; - } - } - } - - RequestCompletion(deviceExtension, Request, status, outLength); - - return status; -} - -NTSTATUS -RequestHandleQueryPropertyWriteCache( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_QUERY_PROPERTY with StorageDeviceWriteCacheProperty. - -Arguments: - - DeviceExtension - device context - Request - request to be handled - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PSTORAGE_PROPERTY_QUERY query = NULL; - PSTORAGE_WRITE_CACHE_PROPERTY writeCache = NULL; - PMODE_PARAMETER_HEADER modeData = NULL; - PMODE_CACHING_PAGE pageData = NULL; - size_t length = 0; - ULONG information = 0; - PSCSI_REQUEST_BLOCK srb = NULL; - WDF_REQUEST_PARAMETERS requestParameters; - - // Get the Request parameters - WDF_REQUEST_PARAMETERS_INIT(&requestParameters); - WdfRequestGetParameters(Request, &requestParameters); - - status = WdfRequestRetrieveInputBuffer(Request, - requestParameters.Parameters.DeviceIoControl.InputBufferLength, - &query, - NULL); - - if (NT_SUCCESS(status)) - { - - // Must run at less then dispatch. - if (KeGetCurrentIrql() >= DISPATCH_LEVEL) - { - NT_ASSERT(FALSE); - status = STATUS_INVALID_LEVEL; - } - else if (query->QueryType == PropertyExistsQuery) - { - information = 0; - status = STATUS_SUCCESS; - } - else if (query->QueryType != PropertyStandardQuery) - { - status = STATUS_NOT_SUPPORTED; - } - } - - if (NT_SUCCESS(status)) - { - length = requestParameters.Parameters.DeviceIoControl.OutputBufferLength; - - if (length < sizeof(STORAGE_DESCRIPTOR_HEADER)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - requestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &writeCache, - NULL); - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(writeCache, length); - - // Set version and required size. - writeCache->Version = sizeof(STORAGE_WRITE_CACHE_PROPERTY); - writeCache->Size = sizeof(STORAGE_WRITE_CACHE_PROPERTY); - - if (length < sizeof(STORAGE_WRITE_CACHE_PROPERTY)) - { - // caller only wants header information, bail out. - information = sizeof(STORAGE_DESCRIPTOR_HEADER); - status = STATUS_SUCCESS; - - RequestCompletion(deviceExtension, Request, status, information); - return status; - } - } - - if (NT_SUCCESS(status)) - { - srb = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SCSI_REQUEST_BLOCK) + - (sizeof(ULONG_PTR) * 2), - CDROM_TAG_SRB); - - if (srb == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK)); - - // Set known values - writeCache->NVCacheEnabled = FALSE; - writeCache->UserDefinedPowerProtection = TEST_FLAG(deviceExtension->DeviceFlags, DEV_POWER_PROTECTED); - - // Check for flush cache support by sending a sync cache command - // to the device. - - // Set timeout value and mark the request as not being a tagged request. - srb->Length = SCSI_REQUEST_BLOCK_SIZE; - srb->TimeOutValue = TimeOutValueGetCapValue(deviceExtension->TimeOutValue, 4); - srb->QueueTag = SP_UNTAGGED; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - srb->SrbFlags = deviceExtension->SrbFlags; - - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->CdbLength = 10; - - srb->Cdb[0] = SCSIOP_SYNCHRONIZE_CACHE; - - status = DeviceSendSrbSynchronously(Device, - srb, - NULL, - 0, - TRUE, //flush drive cache - Request); - - if (NT_SUCCESS(status)) - { - writeCache->FlushCacheSupported = TRUE; - } - else - { - // Device does not support sync cache - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "RequestHandleQueryPropertyWriteCache: Synchronize cache failed with status 0x%X\n", status)); - writeCache->FlushCacheSupported = FALSE; - - // Reset the status if there was any failure - status = STATUS_SUCCESS; - } - - modeData = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - MODE_PAGE_DATA_SIZE, - CDROM_TAG_MODE_DATA); - - if (modeData == NULL) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "RequestHandleQueryPropertyWriteCache: Unable to allocate mode data buffer\n")); - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(modeData, MODE_PAGE_DATA_SIZE); - - length = DeviceRetrieveModeSenseUsingScratch(deviceExtension, - (PCHAR)modeData, - MODE_PAGE_DATA_SIZE, - MODE_PAGE_CACHING, - MODE_SENSE_CURRENT_VALUES); - - if (length < sizeof(MODE_PARAMETER_HEADER)) - { - // Retry the request in case of a check condition. - length = DeviceRetrieveModeSenseUsingScratch(deviceExtension, - (PCHAR)modeData, - MODE_PAGE_DATA_SIZE, - MODE_PAGE_CACHING, - MODE_SENSE_CURRENT_VALUES); - - if (length < sizeof(MODE_PARAMETER_HEADER)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "RequestHandleQueryPropertyWriteCache: Mode Sense failed\n")); - status = STATUS_IO_DEVICE_ERROR; - } - } - } - - if (NT_SUCCESS(status)) - { - // If the length is greater than length indicated by the mode data reset - // the data to the mode data. - if (length > (ULONG) (modeData->ModeDataLength + 1)) - { - length = modeData->ModeDataLength + 1; - } - - // Look for caching page in the returned mode page data. - pageData = ModeSenseFindSpecificPage((PCHAR)modeData, - length, - MODE_PAGE_CACHING, - TRUE); - - // Check if valid caching page exists. - if (pageData == NULL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "RequestHandleQueryPropertyWriteCache: Unable to find caching mode page.\n")); - - // Set write cache value as unknown. - writeCache->WriteCacheEnabled = WriteCacheEnableUnknown; - writeCache->WriteCacheType = WriteCacheTypeUnknown; - } - else - { - writeCache->WriteCacheEnabled = pageData->WriteCacheEnable - ? WriteCacheEnabled - : WriteCacheDisabled; - - writeCache->WriteCacheType = pageData->WriteCacheEnable - ? WriteCacheTypeWriteBack - : WriteCacheTypeUnknown; - } - - // Check write through support. - if (modeData->DeviceSpecificParameter & MODE_DSP_FUA_SUPPORTED) - { - writeCache->WriteThroughSupported = WriteThroughSupported; - } - else - { - writeCache->WriteThroughSupported = WriteThroughNotSupported; - } - - // Get the changeable caching mode page and check write cache is changeable. - RtlZeroMemory(modeData, MODE_PAGE_DATA_SIZE); - - length = DeviceRetrieveModeSenseUsingScratch(deviceExtension, - (PCHAR) modeData, - MODE_PAGE_DATA_SIZE, - MODE_PAGE_CACHING, - MODE_SENSE_CHANGEABLE_VALUES); - - if (length < sizeof(MODE_PARAMETER_HEADER)) - { - // Retry the request in case of a check condition. - length = DeviceRetrieveModeSenseUsingScratch(deviceExtension, - (PCHAR) modeData, - MODE_PAGE_DATA_SIZE, - MODE_PAGE_CACHING, - MODE_SENSE_CHANGEABLE_VALUES); - - if (length < sizeof(MODE_PARAMETER_HEADER)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "RequestHandleQueryPropertyWriteCache: Mode Sense failed\n")); - - // If the device fails to return changeable pages, then - // set the write cache changeable value to unknown. - writeCache->WriteCacheChangeable = WriteCacheChangeUnknown; - information = sizeof(STORAGE_WRITE_CACHE_PROPERTY); - } - } - } - - if (NT_SUCCESS(status)) - { - // If the length is greater than length indicated by the mode data reset - // the data to the mode data. - if (length > (ULONG) (modeData->ModeDataLength + 1)) - { - length = modeData->ModeDataLength + 1; - } - - // Look for caching page in the returned mode page data. - pageData = ModeSenseFindSpecificPage((PCHAR)modeData, - length, - MODE_PAGE_CACHING, - TRUE); - // Check if valid caching page exists. - if (pageData == NULL) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "RequestHandleQueryPropertyWriteCache: Unable to find caching mode page.\n")); - - // Set write cache changeable value to unknown. - writeCache->WriteCacheChangeable = WriteCacheChangeUnknown; - } - else - { - writeCache->WriteCacheChangeable = pageData->WriteCacheEnable - ? WriteCacheChangeable - : WriteCacheNotChangeable; - } - - information = sizeof(STORAGE_WRITE_CACHE_PROPERTY); - - } - - FREE_POOL(srb); - FREE_POOL(modeData); - - RequestCompletion(deviceExtension, Request, status, information); - - return status; -} - -NTSTATUS -RequestValidateDvdReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_DVD_READ_KEY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_COPY_PROTECT_KEY keyParameters = NULL; - ULONG keyLength = 0; - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &keyParameters, - NULL); - - if (NT_SUCCESS(status)) - { - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(DVD_COPY_PROTECT_KEY)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DvdDeviceControl: EstablishDriveKey - challenge " - "key buffer too small\n")); - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - switch(keyParameters->KeyType) - { - - case DvdChallengeKey: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_CHALLENGE_KEY_LENGTH); - keyLength = DVD_CHALLENGE_KEY_LENGTH; - break; - } - case DvdBusKey1: - case DvdBusKey2: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_BUS_KEY_LENGTH); - keyLength = DVD_BUS_KEY_LENGTH; - break; - } - case DvdTitleKey: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_TITLE_KEY_LENGTH); - keyLength = DVD_TITLE_KEY_LENGTH; - break; - } - case DvdAsf: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_ASF_LENGTH); - keyLength = DVD_ASF_LENGTH; - break; - } - case DvdDiskKey: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_DISK_KEY_LENGTH); - keyLength = DVD_DISK_KEY_LENGTH; - break; - } - case DvdGetRpcKey: - { - C_ASSERT(sizeof(DVD_COPY_PROTECT_KEY) <= DVD_RPC_KEY_LENGTH); - keyLength = DVD_RPC_KEY_LENGTH; - break; - } - default: - { - keyLength = sizeof(DVD_COPY_PROTECT_KEY); - break; - } - } - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < keyLength) - { - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DvdDeviceControl: EstablishDriveKey - output " - "buffer too small\n")); - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = keyLength; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength & - DeviceExtension->AdapterDescriptor->AlignmentMask) - { - status = STATUS_INVALID_PARAMETER; - } - else if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - // reject the request if it's not a DVD device. - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - return status; -} - - -NTSTATUS -RequestValidateDvdEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DVD_END_SESSION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID sessionId = NULL; - - UNREFERENCED_PARAMETER(DeviceExtension); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - - if (NT_SUCCESS(status)) - { - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(DVD_SESSION_ID)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DvdDeviceControl: EndSession - input buffer too " - "small\n")); - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - - -NTSTATUS -RequestValidateAacsEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_AACS_END_SESSION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID sessionId = NULL; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &sessionId, - NULL); - - if (NT_SUCCESS(status)) - { - if (!cdData->Mmc.IsAACS) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength != sizeof(DVD_SESSION_ID)) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - - -NTSTATUS -RequestValidateEnableStreaming( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validates an IOCTL_CDROM_ENABLE_STREAMING request - -Arguments: - - Request - request to be handled - RequestParameters - request parameters - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PCDROM_STREAMING_CONTROL inputBuffer = NULL; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_STREAMING_CONTROL)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - // Get the request type using CDROM_STREAMING_CONTROL structure - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_STREAMING_CONTROL), - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->RequestType != CdromStreamingDisable && - inputBuffer->RequestType != CdromStreamingEnableForReadOnly && - inputBuffer->RequestType != CdromStreamingEnableForWriteOnly && - inputBuffer->RequestType != CdromStreamingEnableForReadWrite) - { - // Unknown request type - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - - -NTSTATUS -RequestValidateSendOpcInformation( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validates an IOCTL_CDROM_SEND_OPC_INFORMATION request - -Arguments: - - Request - request to be handled - RequestParameters - request parameters - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PCDROM_SIMPLE_OPC_INFO inputBuffer = NULL; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_SIMPLE_OPC_INFO)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - // Get the request type using CDROM_SIMPLE_OPC_INFO structure - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_SIMPLE_OPC_INFO), - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->RequestType != SimpleOpcInfo) - { - // Unknown request type - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - - -NTSTATUS -RequestValidateGetPerformance( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validates an IOCTL_CDROM_GET_PERFORMANCE request - -Arguments: - - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_WRITE_SPEED_REQUEST writeSpeedRequest = NULL; - PCDROM_PERFORMANCE_REQUEST performanceRequest = NULL; - - *DataLength = 0; - - // CDROM_WRITE_SPEED_REQUEST is the smallest performance request that we support. - // We use it to retrieve request type and then check input length more carefully - // on a per request type basis. - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_WRITE_SPEED_REQUEST)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_WRITE_SPEED_REQUEST), - (PVOID*)&writeSpeedRequest, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (writeSpeedRequest->RequestType == CdromPerformanceRequest) - { - // CDROM_PERFORMANCE_REQUEST is bigger than CDROM_WRITE_SPEED_REQUEST, - // so we perform more checks and retrieve more bytes through WDF. - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(CDROM_PERFORMANCE_REQUEST)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_PERFORMANCE_REQUEST), - &performanceRequest, - NULL); - } - - if (!NT_SUCCESS(status)) - { - // just pass the status code from above - } - // validate all enum-type fields of CDROM_PERFORMANCE_REQUEST - else if (performanceRequest->PerformanceType != CdromReadPerformance && - performanceRequest->PerformanceType != CdromWritePerformance) - { - status = STATUS_INVALID_PARAMETER; - } - else if (performanceRequest->Exceptions != CdromReadPerformance && - performanceRequest->Exceptions != CdromEntirePerformanceList && - performanceRequest->Exceptions != CdromPerformanceExceptionsOnly) - { - status = STATUS_INVALID_PARAMETER; - } - else if (performanceRequest->Tolerance != Cdrom10Nominal20Exceptions) - { - status = STATUS_INVALID_PARAMETER; - } - } - else if (writeSpeedRequest->RequestType == CdromWriteSpeedRequest) - { - // No additional checks here: all remaining fields are ignored - // if RequestType == CdromWriteSpeedRequest. - } - else - { - status = STATUS_INVALID_PARAMETER; - } - } - - // finally, check output buffer length - if (NT_SUCCESS(status)) - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(CDROM_PERFORMANCE_HEADER)) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(CDROM_PERFORMANCE_HEADER); - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength > - ((USHORT)-1)) - { - status = STATUS_INVALID_PARAMETER; - } - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -PCDB -RequestGetScsiPassThroughCdb( - _In_ PIRP Irp - ) -/*++ - -Routine Description: - - Get the CDB structure from the SCSI pass through - -Arguments: - - Irp - request to be handled - -Return Value: - - PCDB - ---*/ -{ - PCDB cdb = NULL; - PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(Irp); - ULONG inputBufferLength = 0; - PVOID inputBuffer = NULL; - BOOLEAN legacyPassThrough = FALSE; - - PAGED_CODE(); - - if (((currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH) || - (currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT) || - (currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH_EX) || - (currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT_EX)) && - (Irp->AssociatedIrp.SystemBuffer != NULL)) - { - inputBufferLength = currentIrpStack->Parameters.DeviceIoControl.InputBufferLength; - inputBuffer = Irp->AssociatedIrp.SystemBuffer; - legacyPassThrough = TRUE; - - if ((currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH_EX) || - (currentIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT_EX)) - { - legacyPassThrough = FALSE; - } - - // - // If this is a 32 bit application running on 64 bit then thunk the - // input structures to grab the cdb. - // - -#if BUILD_WOW64_ENABLED && defined(_WIN64) - - if (IoIs32bitProcess(Irp)) - { - if (legacyPassThrough) - { - if (inputBufferLength >= sizeof(SCSI_PASS_THROUGH32)) - { - cdb = (PCDB)((PSCSI_PASS_THROUGH32)inputBuffer)->Cdb; - } - } - else - { - if (inputBufferLength >= sizeof(SCSI_PASS_THROUGH32_EX)) - { - cdb = (PCDB)((PSCSI_PASS_THROUGH32_EX)inputBuffer)->Cdb; - } - } - - } - else - -#endif - - { - if (legacyPassThrough) - { - if (inputBufferLength >= sizeof(SCSI_PASS_THROUGH)) - { - cdb = (PCDB)((PSCSI_PASS_THROUGH)inputBuffer)->Cdb; - } - } - else - { - if (inputBufferLength >= sizeof(SCSI_PASS_THROUGH_EX)) - { - cdb = (PCDB)((PSCSI_PASS_THROUGH_EX)inputBuffer)->Cdb; - } - } - } - } - - return cdb; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleScsiPassThrough( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Handle request of IOCTL_SCSI_PASS_THROUGH - IOCTL_SCSI_PASS_THROUGH_DIRECT - - The function sets the MinorFunction field of irpStack, - and pass the request to lower level driver. - -Arguments: - - Device - device object - Request - request to be handled - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_UNSUCCESSFUL; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PIRP irp = WdfRequestWdmGetIrp(Request); - PZERO_POWER_ODD_INFO zpoddInfo = deviceExtension->ZeroPowerODDInfo; - PCDB cdb = NULL; - BOOLEAN isSoftEject = FALSE; - -#if DBG - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); -#endif - - - PAGED_CODE(); - -#if DBG - // SPTI is always processed in sync manner. - NT_ASSERT(requestContext->SyncRequired); -#endif - - if ((zpoddInfo != NULL) && - (zpoddInfo->LoadingMechanism == LOADING_MECHANISM_TRAY) && - (zpoddInfo->Load == 0)) // Drawer - { - cdb = RequestGetScsiPassThroughCdb(irp); - - if ((cdb != NULL) && - (cdb->AsByte[0] == SCSIOP_START_STOP_UNIT) && - (cdb->START_STOP.LoadEject == 1) && - (cdb->START_STOP.Start == 0)) - { - isSoftEject = TRUE; - } - } - - WdfRequestFormatRequestUsingCurrentType(Request); - - // Special for SPTI, set the MinorFunction. - { - PIO_STACK_LOCATION nextStack = IoGetNextIrpStackLocation(irp); - - nextStack->MinorFunction = 1; - } - - - status = RequestSend(deviceExtension, - Request, - deviceExtension->IoTarget, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - NULL); - - - if (!NT_SUCCESS(status) && - (isSoftEject != FALSE)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "RequestHandleScsiPassThrough: soft eject detected, device marked as active\n")); - - DeviceMarkActive(deviceExtension, TRUE, FALSE); - } - - RequestCompletion(deviceExtension, Request, status, WdfRequestGetInformation(Request)); - - return status; -} - -NTSTATUS -RequestHandleMountQueryUniqueId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_MOUNTDEV_QUERY_UNIQUE_ID - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMOUNTDEV_UNIQUE_ID uniqueId = NULL; - - *DataLength = 0; - - if (!DeviceExtension->MountedDeviceInterfaceName.Buffer) - { - status = STATUS_INVALID_PARAMETER; - } - else if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(MOUNTDEV_UNIQUE_ID)) - { - *DataLength = sizeof(MOUNTDEV_UNIQUE_ID); - status = STATUS_BUFFER_TOO_SMALL; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &uniqueId, - NULL); - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(uniqueId, RequestParameters.Parameters.DeviceIoControl.OutputBufferLength); - - uniqueId->UniqueIdLength = DeviceExtension->MountedDeviceInterfaceName.Length; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - (sizeof(USHORT) + DeviceExtension->MountedDeviceInterfaceName.Length)) - { - *DataLength = sizeof(MOUNTDEV_UNIQUE_ID); - status = STATUS_BUFFER_OVERFLOW; - } - } - - if (NT_SUCCESS(status)) - { - RtlCopyMemory(uniqueId->UniqueId, - DeviceExtension->MountedDeviceInterfaceName.Buffer, - uniqueId->UniqueIdLength); - - *DataLength = sizeof(USHORT) + uniqueId->UniqueIdLength; - status = STATUS_SUCCESS; - } - - return status; -} - -NTSTATUS -RequestHandleMountQueryDeviceName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_MOUNTDEV_QUERY_DEVICE_NAME - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMOUNTDEV_NAME name = NULL; - - *DataLength = 0; - - NT_ASSERT(DeviceExtension->DeviceName.Buffer); - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < sizeof(MOUNTDEV_NAME)) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(MOUNTDEV_NAME); - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &name, - NULL); - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(name, RequestParameters.Parameters.DeviceIoControl.OutputBufferLength); - name->NameLength = DeviceExtension->DeviceName.Length; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - (sizeof(USHORT) + DeviceExtension->DeviceName.Length)) - { - status = STATUS_BUFFER_OVERFLOW; - *DataLength = sizeof(MOUNTDEV_NAME); - } - } - - if (NT_SUCCESS(status)) - { - RtlCopyMemory(name->Name, - DeviceExtension->DeviceName.Buffer, - name->NameLength); - - status = STATUS_SUCCESS; - *DataLength = sizeof(USHORT) + name->NameLength; - } - - return status; -} - -NTSTATUS -RequestHandleMountQuerySuggestedLinkName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PMOUNTDEV_SUGGESTED_LINK_NAME suggestedName = NULL; - - WCHAR driveLetterNameBuffer[10] = {0}; - RTL_QUERY_REGISTRY_TABLE queryTable[2] = {0}; - PWSTR valueName = NULL; - UNICODE_STRING driveLetterName = {0}; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < - sizeof(MOUNTDEV_SUGGESTED_LINK_NAME)) - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(MOUNTDEV_SUGGESTED_LINK_NAME); - } - - if (NT_SUCCESS(status)) - { - valueName = ExAllocatePool2(POOL_FLAG_PAGED, - DeviceExtension->DeviceName.Length + sizeof(WCHAR), - CDROM_TAG_STRINGS); - if (valueName == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - RtlCopyMemory(valueName, - DeviceExtension->DeviceName.Buffer, - DeviceExtension->DeviceName.Length); - valueName[DeviceExtension->DeviceName.Length/sizeof(WCHAR)] = 0; - - driveLetterName.Buffer = driveLetterNameBuffer; - driveLetterName.MaximumLength = sizeof(driveLetterNameBuffer); - driveLetterName.Length = 0; - - queryTable[0].Flags = RTL_QUERY_REGISTRY_REQUIRED | RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK; - queryTable[0].Name = valueName; - queryTable[0].EntryContext = &driveLetterName; - queryTable[0].DefaultType = (REG_SZ << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_NONE; - - status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, - L"\\Registry\\Machine\\System\\DISK", // why hard coded? - queryTable, NULL, NULL); - } - - if (NT_SUCCESS(status)) - { - if ((driveLetterName.Length == 4) && - (driveLetterName.Buffer[0] == '%') && - (driveLetterName.Buffer[1] == ':')) - { - driveLetterName.Buffer[0] = 0xFF; - } - else if ((driveLetterName.Length != 4) || - (driveLetterName.Buffer[0] < FirstDriveLetter) || - (driveLetterName.Buffer[0] > LastDriveLetter) || - (driveLetterName.Buffer[1] != ':')) - { - status = STATUS_NOT_FOUND; - } - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &suggestedName, - NULL); - } - - if (NT_SUCCESS(status)) - { - RtlZeroMemory(suggestedName, RequestParameters.Parameters.DeviceIoControl.OutputBufferLength); - suggestedName->UseOnlyIfThereAreNoOtherLinks = TRUE; - suggestedName->NameLength = 28; - - *DataLength = FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME, Name) + 28; - - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < *DataLength) - { - *DataLength = sizeof(MOUNTDEV_SUGGESTED_LINK_NAME); - status = STATUS_BUFFER_OVERFLOW; - } - } - - if (NT_SUCCESS(status)) - { - RtlDeleteRegistryValue(RTL_REGISTRY_ABSOLUTE, - L"\\Registry\\Machine\\System\\DISK", - valueName); - - RtlCopyMemory(suggestedName->Name, L"\\DosDevices\\", 24); - suggestedName->Name[12] = driveLetterName.Buffer[0]; - suggestedName->Name[13] = ':'; - } - - FREE_POOL(valueName); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleReadTOC( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_READ_TOC - IOCTL_CDROM_GET_LAST_SESSION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - VOID* outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if (DeviceIsPlayActive(DeviceExtension->Device)) - { - status = STATUS_DEVICE_BUSY; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - // handle the request - if (NT_SUCCESS(status)) - { - size_t transferSize; - CDB cdb; - - transferSize = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, sizeof(CDROM_TOC)); - - RtlZeroMemory(outputBuffer, transferSize); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_GET_LAST_SESSION) - { - // Set format to return first and last session numbers. - cdb.READ_TOC.Format2 = CDROM_READ_TOC_EX_FORMAT_SESSION; - } - else - { - // Use MSF addressing - cdb.READ_TOC.Msf = 1; - } - - cdb.READ_TOC.OperationCode = SCSIOP_READ_TOC; - cdb.READ_TOC.AllocationLength[0] = (UCHAR)(transferSize >> 8); - cdb.READ_TOC.AllocationLength[1] = (UCHAR)(transferSize & 0xFF); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, (ULONG)transferSize, TRUE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - *DataLength = DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - RtlCopyMemory(outputBuffer, - DeviceExtension->ScratchContext.ScratchBuffer, - *DataLength); - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleReadTocEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_READ_TOC_EX - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_READ_TOC_EX inputBuffer = NULL; - VOID* outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if (DeviceIsPlayActive(DeviceExtension->Device)) - { - status = STATUS_DEVICE_BUSY; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - // handle the request - if (NT_SUCCESS(status)) - { - size_t transferSize; - CDB cdb; - - transferSize = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, MAXUSHORT); - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_TOC.OperationCode = SCSIOP_READ_TOC; - cdb.READ_TOC.Msf = inputBuffer->Msf; - cdb.READ_TOC.Format2 = inputBuffer->Format; - cdb.READ_TOC.StartingTrack = inputBuffer->SessionTrack; - cdb.READ_TOC.AllocationLength[0] = (UCHAR)(transferSize >> 8); - cdb.READ_TOC.AllocationLength[1] = (UCHAR)(transferSize & 0xFF); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, (ULONG)transferSize, TRUE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - if (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength < MINIMUM_CDROM_READ_TOC_EX_SIZE) - { - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - else - { - *DataLength = DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - RtlCopyMemory(outputBuffer, - DeviceExtension->ScratchContext.ScratchBuffer, - *DataLength); - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -VOID -GetConfigurationDataConversionTypeAllToTypeOne( - _In_ FEATURE_NUMBER RequestedFeature, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Some CDROM devices do not handle the GET CONFIGURATION commands with - TYPE ONE request. The command will time out causing a bus reset. - To avoid this problem we set a device flag during start device if the device - fails a TYPE ONE request. If this flag is set the TYPE ONE requests will be - tried as TYPE ALL request and the data will be converted to TYPE ONE format - in this routine. - -Arguments: - - RequestedFeature - device context - Srb - request to be handled - DataLength - transfer data length - -Return Value: - - NTSTATUS - ---*/ -{ - PFEATURE_HEADER featureHeader = NULL; - FEATURE_NUMBER thisFeature; - ULONG totalLength = 0; - ULONG featureLength = 0; - ULONG headerLength = 0; - - PGET_CONFIGURATION_HEADER header = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if (Srb->DataTransferLength < RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength)) - { - // do not have valid data. - return; - } - - // Calculate the length of valid data available in the - // capabilities buffer from the DataLength field - header = (PGET_CONFIGURATION_HEADER) Srb->DataBuffer; - REVERSE_BYTES(&totalLength, header->DataLength); - - totalLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - // Make sure the we have enough data in the SRB - totalLength = min(totalLength, Srb->DataTransferLength); - - // If we have received enough data from the device - // check for the given feature. - if (totalLength >= (sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER))) - { - // Feature information is present. Verify the feature. - featureHeader = (PFEATURE_HEADER)((PUCHAR)Srb->DataBuffer + sizeof(GET_CONFIGURATION_HEADER)); - - thisFeature = (featureHeader->FeatureCode[0] << 8) | (featureHeader->FeatureCode[1]); - - if (thisFeature == RequestedFeature) - { - // Calculate the feature length - featureLength = sizeof(FEATURE_HEADER) + featureHeader->AdditionalLength; - } - } - - // Calculate the total size - totalLength = sizeof(GET_CONFIGURATION_HEADER) + featureLength; - - headerLength = totalLength - - RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - REVERSE_BYTES(header->DataLength, &headerLength); - - *DataLength = totalLength; - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -VOID -GetConfigurationDataSynthesize( - _In_reads_bytes_(InputBufferSize) PVOID InputBuffer, - _In_ ULONG InputBufferSize, - _Out_writes_bytes_(OutputBufferSize) PVOID OutputBuffer, - _In_ size_t OutputBufferSize, - _In_ FEATURE_NUMBER StartingFeature, - _In_ ULONG RequestType, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Get Configuration is a frequently used command, and we don't want it to wake - up the device in case it is in Zero Power state. Before entering Zero Power state, - the complete response of the command is saved in cache, and since the response - is always the same in case there is no media, we can synthesize the response - based on the user request. - -Arguments: - - InputBuffer - buffer containing cached command response - InputBufferSize - size of above buffer - OutputBuffer - buffer to fill in result - OutputBufferSize - size of above buffer - StartingFeature - requested Starting Feature Number - RequestType - requested Request Type - DataLength - transfer data length - -Return Value: - ---*/ -{ - PFEATURE_HEADER featureHeader = NULL; - ULONG validLength = 0; - ULONG featureLength = 0; - ULONG headerLength = 0; - PUCHAR buffer = NULL; - ULONG bytesRemaining = 0; - FEATURE_NUMBER featureCode = 0; - BOOLEAN shouldCopy = FALSE; - size_t copyLength = 0; - size_t transferedLength = 0; - size_t requiredLength = 0; - - PGET_CONFIGURATION_HEADER header = NULL; - - PAGED_CODE (); - - if (InputBufferSize < sizeof (GET_CONFIGURATION_HEADER)) - { - // do not have valid data. - *DataLength = 0; - - return; - } - - // Calculate the length of valid data available in the - // capabilities buffer from the DataLength field - header = (PGET_CONFIGURATION_HEADER) InputBuffer; - REVERSE_BYTES(&validLength, header->DataLength); - - validLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - // Make sure we have enough data - validLength = min(validLength, InputBufferSize); - - // Copy the header first - copyLength = min(OutputBufferSize, sizeof (GET_CONFIGURATION_HEADER)); - - RtlMoveMemory(OutputBuffer, - InputBuffer, - copyLength); - - transferedLength = copyLength; - requiredLength = sizeof (GET_CONFIGURATION_HEADER); - - if (validLength > sizeof (GET_CONFIGURATION_HEADER)) - { - buffer = header->Data; - bytesRemaining = validLength - sizeof (GET_CONFIGURATION_HEADER); - - // Ignore incomplete feature descriptor - while (bytesRemaining >= sizeof (FEATURE_HEADER)) - { - featureHeader = (PFEATURE_HEADER) buffer; - shouldCopy = FALSE; - - featureCode = (featureHeader->FeatureCode[0] << 8) | (featureHeader->FeatureCode[1]); - featureLength = sizeof (FEATURE_HEADER) + featureHeader->AdditionalLength; - - if (featureCode >= StartingFeature) - { - switch (RequestType) { - - case SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL: - - shouldCopy = TRUE; - break; - - case SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT: - - if (featureHeader->Current) - { - shouldCopy = TRUE; - } - break; - - case SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE: - - if (featureCode == StartingFeature) - { - shouldCopy = TRUE; - } - break; - - default: - - break; - } - } - - if (shouldCopy != FALSE) - { - copyLength = min(featureLength, bytesRemaining); - copyLength = min(copyLength, OutputBufferSize - transferedLength); - - RtlMoveMemory((PUCHAR) OutputBuffer + transferedLength, - buffer, - copyLength); - - transferedLength += copyLength; - requiredLength += featureLength; - } - - buffer += min(featureLength, bytesRemaining); - bytesRemaining -= min(featureLength, bytesRemaining); - } - } - - // Adjust Data Length field in header - if (transferedLength >= RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength)) - { - headerLength = (ULONG) requiredLength - RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - header = (PGET_CONFIGURATION_HEADER) OutputBuffer; - REVERSE_BYTES(header->DataLength, &headerLength); - } - - *DataLength = transferedLength; - - return; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetConfiguration( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_GET_CONFIGURATION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PGET_CONFIGURATION_IOCTL_INPUT inputBuffer = NULL; - VOID* outputBuffer = NULL; - size_t transferByteCount = 0; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - BOOLEAN inZeroPowerState = FALSE; - - PAGED_CODE (); - - *DataLength = 0; - - // - if (!cdData->Mmc.IsMmc) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - else - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - // If device is Zero Power state, there should be no media in device, thus we can synthesize the response - // from our cache. Avoid waking up the device in this case. - if ((zpoddInfo != NULL) && - (zpoddInfo->InZeroPowerState != FALSE)) - { - inZeroPowerState = TRUE; - } - - if ((inZeroPowerState == FALSE) || - (zpoddInfo->GetConfigurationBuffer == NULL)) - { - CDB cdb; - - //The maximum number of bytes that a Drive may return - //to describe its Features in one GET CONFIGURATION Command is 65,534 - transferByteCount = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, (MAXUSHORT - 1)); - - // If this is a TYPE ONE request and if this device can't handle this - // request, then we need to send TYPE ALL request to the device and - // convert the data in the completion routine. If required allocate a big - // buffer to get both configuration and feature header. - if ((inputBuffer->RequestType == SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) && - TEST_FLAG(cdData->HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG)) - { - transferByteCount = max(transferByteCount, - sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER)); - } - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.GET_CONFIGURATION.OperationCode = SCSIOP_GET_CONFIGURATION; - cdb.GET_CONFIGURATION.AllocationLength[0] = (UCHAR)(transferByteCount >> 8); - cdb.GET_CONFIGURATION.AllocationLength[1] = (UCHAR)(transferByteCount & 0xff); - - cdb.GET_CONFIGURATION.StartingFeature[0] = (UCHAR)(inputBuffer->Feature >> 8); - cdb.GET_CONFIGURATION.StartingFeature[1] = (UCHAR)(inputBuffer->Feature & 0xff); - cdb.GET_CONFIGURATION.RequestType = (UCHAR)(inputBuffer->RequestType); - - // If the device does not support TYPE ONE get configuration commands - // then change the request type to TYPE ALL. Convert the returned data to - // TYPE ONE format in the completion routine. - if ((inputBuffer->RequestType == SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) && - TEST_FLAG(cdData->HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG)) - { - - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "DeviceHandleGetConfiguration: Changing TYPE_ONE Get Config to TYPE_ALL\n")); - cdb.GET_CONFIGURATION.RequestType = SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL; - } - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, (ULONG)transferByteCount, TRUE, &cdb, 12); - - if (NT_SUCCESS(status)) - { - if ((inputBuffer->RequestType == SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) && - TEST_FLAG(cdData->HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG)) - { - - if (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength < sizeof(GET_CONFIGURATION_HEADER)) - { - // Not enough data to calculate the data length. - // So assume feature is not present - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, "DeviceHandleGetConfiguration: No get config header!\n")); - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - else - { - //Some CDROM devices do not handle the GET CONFIGURATION commands with - //TYPE ONE request. The command will time out causing a bus reset. - //To avoid this problem we set a device flag during start device if the device - //fails a TYPE ONE request. If this flag is set the TYPE ONE requests will be - //tried as TYPE ALL request and the data will be converted to TYPE ONE format - //in this routine. - GetConfigurationDataConversionTypeAllToTypeOne(inputBuffer->Feature, DeviceExtension->ScratchContext.ScratchSrb, DataLength); - *DataLength = min(*DataLength, RequestParameters.Parameters.DeviceIoControl.OutputBufferLength); - } - } - else - { - *DataLength = DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - } - - // copy data to output buffer - if (NT_SUCCESS(status)) - { - RtlMoveMemory(outputBuffer, - DeviceExtension->ScratchContext.ScratchBuffer, - *DataLength); - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - else - { - // We are in Zero Power state, and our cached response is available. - // Synthesize the requested data. - GetConfigurationDataSynthesize(zpoddInfo->GetConfigurationBuffer, - zpoddInfo->GetConfigurationBufferSize, - outputBuffer, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - inputBuffer->Feature, - inputBuffer->RequestType, - DataLength - ); - } - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleGetDriveGeometry( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DISK_GET_LENGTH_INFO - IOCTL_DISK_GET_DRIVE_GEOMETRY - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX - IOCTL_CDROM_GET_DRIVE_GEOMETRY - IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX - IOCTL_STORAGE_READ_CAPACITY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - VOID* outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - - // Issue ReadCapacity to update device extension - // with information for current media. - if (NT_SUCCESS(status)) - { - status = MediaReadCapacity(DeviceExtension->Device); - } - - if (NT_SUCCESS(status)) - { - switch(RequestParameters.Parameters.DeviceIoControl.IoControlCode) - { - case IOCTL_DISK_GET_LENGTH_INFO: - { - PGET_LENGTH_INFORMATION lengthInfo = (PGET_LENGTH_INFORMATION)outputBuffer; - - lengthInfo->Length = DeviceExtension->PartitionLength; - *DataLength = sizeof(GET_LENGTH_INFORMATION); - break; - } - case IOCTL_DISK_GET_DRIVE_GEOMETRY: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY: - { - PDISK_GEOMETRY geometry = (PDISK_GEOMETRY)outputBuffer; - - *geometry = DeviceExtension->DiskGeometry; - *DataLength = sizeof(DISK_GEOMETRY); - break; - } - case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: - case IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX: - { - PDISK_GEOMETRY_EX geometryEx = (PDISK_GEOMETRY_EX)outputBuffer; - - geometryEx->DiskSize = DeviceExtension->PartitionLength; - geometryEx->Geometry = DeviceExtension->DiskGeometry; - *DataLength = FIELD_OFFSET(DISK_GEOMETRY_EX, Data); - break; - } - case IOCTL_STORAGE_READ_CAPACITY: - { - PSTORAGE_READ_CAPACITY readCapacity = (PSTORAGE_READ_CAPACITY)outputBuffer; - - readCapacity->Version = sizeof(STORAGE_READ_CAPACITY); - readCapacity->Size = sizeof(STORAGE_READ_CAPACITY); - - readCapacity->BlockLength = DeviceExtension->DiskGeometry.BytesPerSector; - if (readCapacity->BlockLength > 0) - { - readCapacity->NumberOfBlocks.QuadPart = DeviceExtension->PartitionLength.QuadPart/readCapacity->BlockLength; - } - else - { - readCapacity->NumberOfBlocks.QuadPart = 0; - } - - readCapacity->DiskLength = DeviceExtension->PartitionLength; - - *DataLength = sizeof(STORAGE_READ_CAPACITY); - break; - } - default: - { - NT_ASSERT(FALSE); - break; - } - } // end of switch() - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleDiskVerify( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DISK_VERIFY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PVERIFY_INFORMATION verifyInfo = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if (!cdData->Mmc.WriteAllowed) - { - status = STATUS_MEDIA_WRITE_PROTECTED; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &verifyInfo, - NULL); - } - - // handle the request - if (NT_SUCCESS(status)) - { - LARGE_INTEGER byteOffset = {0}; - - // Add disk offset to starting sector. - byteOffset.QuadPart = DeviceExtension->StartingOffset.QuadPart + - verifyInfo->StartingOffset.QuadPart; - - // prevent overflow returning success but only validating small area - if (((DeviceExtension->StartingOffset.QuadPart + verifyInfo->StartingOffset.QuadPart) < DeviceExtension->StartingOffset.QuadPart) || - ((verifyInfo->Length >> DeviceExtension->SectorShift) > MAXUSHORT) || - ((byteOffset.QuadPart >> DeviceExtension->SectorShift) > MAXULONG) ) - { - status = STATUS_INVALID_PARAMETER; - } - else - { - ULONG transferSize = 0; - ULONG timeoutValue = 0; - CDB cdb; - ULONG sectorOffset; - USHORT sectorCount; - - ScratchBuffer_BeginUse(DeviceExtension); - - // Convert byte offset to sector offset. - sectorOffset = (ULONG)(byteOffset.QuadPart >> DeviceExtension->SectorShift); - - // Convert ULONG byte count to USHORT sector count. - sectorCount = (USHORT)(verifyInfo->Length >> DeviceExtension->SectorShift); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.CDB10.OperationCode = SCSIOP_VERIFY; - - // Move little endian values into CDB in big endian format. - cdb.CDB10.LogicalBlockByte0 = ((PFOUR_BYTE)§orOffset)->Byte3; - cdb.CDB10.LogicalBlockByte1 = ((PFOUR_BYTE)§orOffset)->Byte2; - cdb.CDB10.LogicalBlockByte2 = ((PFOUR_BYTE)§orOffset)->Byte1; - cdb.CDB10.LogicalBlockByte3 = ((PFOUR_BYTE)§orOffset)->Byte0; - - cdb.CDB10.TransferBlocksMsb = ((PFOUR_BYTE)§orCount)->Byte1; - cdb.CDB10.TransferBlocksLsb = ((PFOUR_BYTE)§orCount)->Byte0; - - // The verify command is used by the NT FORMAT utility and - // requests are sent down for 5% of the volume size. The - // request timeout value is calculated based on the number of - // sectors verified. - if (sectorCount != 0) - { - // sectorCount is a USHORT, so no overflow here... - timeoutValue = TimeOutValueGetCapValue(DeviceExtension->TimeOutValue, ((sectorCount + 128) / 128)); - } - - status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, Request, transferSize, FALSE, &cdb, 10, timeoutValue); - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleCheckVerify( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_CHECK_VERIFY2 - IOCTL_STORAGE_CHECK_VERIFY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY; - - status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, Request, transferSize, FALSE, &cdb, 6, CDROM_TEST_UNIT_READY_TIMEOUT); - - if (NT_SUCCESS(status)) - { - if((RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_STORAGE_CHECK_VERIFY) && - (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength)) - { - PULONG outputBuffer = NULL; - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - - if (outputBuffer != NULL) - { - *outputBuffer = DeviceExtension->MediaChangeCount; - *DataLength = sizeof(ULONG); - } - } - else - { - *DataLength = 0; - } - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleFakePartitionInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DISK_GET_DRIVE_LAYOUT - IOCTL_DISK_GET_DRIVE_LAYOUT_EX - IOCTL_DISK_GET_PARTITION_INFO - IOCTL_DISK_GET_PARTITION_INFO_EX - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - VOID* outputBuffer = NULL; - ULONG ioctl = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - if ((ioctl != IOCTL_DISK_GET_DRIVE_LAYOUT) && - (ioctl != IOCTL_DISK_GET_DRIVE_LAYOUT_EX) && - (ioctl != IOCTL_DISK_GET_PARTITION_INFO) && - (ioctl != IOCTL_DISK_GET_PARTITION_INFO_EX)) - { - status = STATUS_INTERNAL_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - // handle the request - if (NT_SUCCESS(status)) - { - switch (ioctl) - { - case IOCTL_DISK_GET_DRIVE_LAYOUT: - *DataLength = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION, PartitionEntry[1]); - RtlZeroMemory(outputBuffer, *DataLength); - break; - case IOCTL_DISK_GET_DRIVE_LAYOUT_EX: - *DataLength = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION_EX, PartitionEntry[1]); - RtlZeroMemory(outputBuffer, *DataLength); - break; - case IOCTL_DISK_GET_PARTITION_INFO: - *DataLength = sizeof(PARTITION_INFORMATION); - RtlZeroMemory(outputBuffer, *DataLength); - break; - case IOCTL_DISK_GET_PARTITION_INFO_EX: - *DataLength = sizeof(PARTITION_INFORMATION_EX); - RtlZeroMemory(outputBuffer, *DataLength); - break; - default: - NT_ASSERT(!"Invalid ioctl should not have reached this point\n"); - break; - } - - // if we are getting the drive layout, then we need to start by - // adding some of the non-partition stuff that says we have - // exactly one partition available. - if (ioctl == IOCTL_DISK_GET_DRIVE_LAYOUT) - { - PDRIVE_LAYOUT_INFORMATION layout; - layout = (PDRIVE_LAYOUT_INFORMATION)outputBuffer; - layout->PartitionCount = 1; - layout->Signature = 1; - outputBuffer = (PVOID)(layout->PartitionEntry); - ioctl = IOCTL_DISK_GET_PARTITION_INFO; - } - else if (ioctl == IOCTL_DISK_GET_DRIVE_LAYOUT_EX) - { - PDRIVE_LAYOUT_INFORMATION_EX layoutEx; - layoutEx = (PDRIVE_LAYOUT_INFORMATION_EX)outputBuffer; - layoutEx->PartitionStyle = PARTITION_STYLE_MBR; - layoutEx->PartitionCount = 1; - layoutEx->Mbr.Signature = 1; - outputBuffer = (PVOID)(layoutEx->PartitionEntry); - ioctl = IOCTL_DISK_GET_PARTITION_INFO_EX; - } - - // NOTE: the local var 'ioctl' is now modified to either EX or - // non-EX version. the local var 'systemBuffer' is now pointing - // to the partition information structure. - if (ioctl == IOCTL_DISK_GET_PARTITION_INFO) - { - PPARTITION_INFORMATION partitionInfo; - partitionInfo = (PPARTITION_INFORMATION)outputBuffer; - partitionInfo->RewritePartition = FALSE; - partitionInfo->RecognizedPartition = TRUE; - partitionInfo->PartitionType = PARTITION_FAT32; - partitionInfo->BootIndicator = FALSE; - partitionInfo->HiddenSectors = 0; - partitionInfo->StartingOffset.QuadPart = 0; - partitionInfo->PartitionLength = DeviceExtension->PartitionLength; - partitionInfo->PartitionNumber = 0; - } - else - { - PPARTITION_INFORMATION_EX partitionInfo; - partitionInfo = (PPARTITION_INFORMATION_EX)outputBuffer; - partitionInfo->PartitionStyle = PARTITION_STYLE_MBR; - partitionInfo->RewritePartition = FALSE; - partitionInfo->Mbr.RecognizedPartition = TRUE; - partitionInfo->Mbr.PartitionType = PARTITION_FAT32; - partitionInfo->Mbr.BootIndicator = FALSE; - partitionInfo->Mbr.HiddenSectors = 0; - partitionInfo->StartingOffset.QuadPart = 0; - partitionInfo->PartitionLength = DeviceExtension->PartitionLength; - partitionInfo->PartitionNumber = 0; - } - } - - return status; -} - -NTSTATUS -RequestHandleGetDeviceNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_GET_DEVICE_NUMBER - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength >= - sizeof(STORAGE_DEVICE_NUMBER)) - { - PSTORAGE_DEVICE_NUMBER deviceNumber = NULL; - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &deviceNumber, - NULL); - if (NT_SUCCESS(status)) - { - deviceNumber->DeviceType = DeviceExtension->DeviceObject->DeviceType; - deviceNumber->DeviceNumber = DeviceExtension->DeviceNumber; - deviceNumber->PartitionNumber = (ULONG)-1; // legacy reason, return (-1) for this IOCTL. - - status = STATUS_SUCCESS; - *DataLength = sizeof(STORAGE_DEVICE_NUMBER); - } - } - else - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(STORAGE_DEVICE_NUMBER); - } - - return status; -} - -NTSTATUS -RequestHandleGetHotPlugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_GET_HOTPLUG_INFO - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - *DataLength = 0; - - if(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength >= - sizeof(STORAGE_HOTPLUG_INFO)) - { - PSTORAGE_HOTPLUG_INFO info = NULL; - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &info, - NULL); - if (NT_SUCCESS(status)) - { - *info = DeviceExtension->PrivateFdoData->HotplugInfo; - - status = STATUS_SUCCESS; - *DataLength = sizeof(STORAGE_HOTPLUG_INFO); - } - } - else - { - status = STATUS_BUFFER_TOO_SMALL; - *DataLength = sizeof(STORAGE_HOTPLUG_INFO); - } - - return status; -} - -NTSTATUS -RequestHandleSetHotPlugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_SET_HOTPLUG_INFO - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSTORAGE_HOTPLUG_INFO info = NULL; - - *DataLength = 0; - - if (RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(STORAGE_HOTPLUG_INFO)) - { - // Indicate unsuccessful status and no data transferred. - status = STATUS_INFO_LENGTH_MISMATCH; - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &info, - NULL); - } - - if (NT_SUCCESS(status)) - { - if (info->Size != DeviceExtension->PrivateFdoData->HotplugInfo.Size) - { - status = STATUS_INVALID_PARAMETER_1; - } - - if (info->MediaRemovable != DeviceExtension->PrivateFdoData->HotplugInfo.MediaRemovable) - { - status = STATUS_INVALID_PARAMETER_2; - } - - if (info->MediaHotplug != DeviceExtension->PrivateFdoData->HotplugInfo.MediaHotplug) - { - status = STATUS_INVALID_PARAMETER_3; - } - - if (info->WriteCacheEnableOverride != DeviceExtension->PrivateFdoData->HotplugInfo.WriteCacheEnableOverride) - { - status = STATUS_INVALID_PARAMETER_5; - } - } - - if (NT_SUCCESS(status)) - { - DeviceExtension->PrivateFdoData->HotplugInfo.DeviceHotplug = info->DeviceHotplug; - - // Store the user-defined override in the registry - DeviceSetParameter(DeviceExtension, - CLASSP_REG_SUBKEY_NAME, - CLASSP_REG_REMOVAL_POLICY_VALUE_NAME, - (info->DeviceHotplug) ? RemovalPolicyExpectSurpriseRemoval : RemovalPolicyExpectOrderlyRemoval); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleEventNotification( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST Request, - _In_opt_ PWDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - This routine handles the process of IOCTL_STORAGE_EVENT_NOTIFICATION - -Arguments: - - DeviceExtension - device context - - Request - request to be handled - - RequestParameters - request parameter - - DataLength - data transferred - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMEDIA_CHANGE_DETECTION_INFO info = NULL; - LONG requestInUse; - PSTORAGE_EVENT_NOTIFICATION eventBuffer = NULL; - - *DataLength = 0; - - info = DeviceExtension->MediaChangeDetectionInfo; - - // Since AN is ASYNCHRONOUS and can happen at any time, - // make certain not to do anything before properly initialized. - if ((!DeviceExtension->IsInitialized) || (info == NULL)) - { - status = STATUS_UNSUCCESSFUL; - } - - if (NT_SUCCESS(status) && (Request != NULL) && (RequestParameters != NULL)) { - - // - // Validate IOCTL parameters - // - if (RequestParameters->Parameters.DeviceIoControl.InputBufferLength < - sizeof(STORAGE_EVENT_NOTIFICATION)) { - status = STATUS_INFO_LENGTH_MISMATCH; - } - - // - // Check for an supported event - // - if (NT_SUCCESS(status)) { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters->Parameters.DeviceIoControl.InputBufferLength, - &eventBuffer, - NULL); - if (NT_SUCCESS(status)) { - if ((eventBuffer->Version != STORAGE_EVENT_NOTIFICATION_VERSION_V1) || - (eventBuffer->Size != sizeof(STORAGE_EVENT_NOTIFICATION))) { - status = STATUS_INVALID_PARAMETER; - } else if ((eventBuffer->Events & - (STORAGE_EVENT_MEDIA_STATUS | STORAGE_EVENT_DEVICE_STATUS | STORAGE_EVENT_DEVICE_OPERATION)) == 0) { - status = STATUS_NOT_SUPPORTED; - } - } - } - - } - - if (NT_SUCCESS(status)) - { - if (info->MediaChangeDetectionDisableCount != 0) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_MCN, - "RequestHandleEventNotification: device %p has detection disabled \n", - DeviceExtension->DeviceObject)); - status = STATUS_UNSUCCESSFUL; - } - } - - if (NT_SUCCESS(status)) - { - // if the request is not in use, mark it as such. - requestInUse = InterlockedCompareExchange((PLONG)&info->MediaChangeRequestInUse, 1, 0); - - if (requestInUse != 0) - { - status = STATUS_UNSUCCESSFUL; - } - } - - if (NT_SUCCESS(status)) - { - // The last MCN finished. ok to issue the new one. - RequestSetupMcnSyncIrp(DeviceExtension); - - // The irp will go into KMDF framework and a request will be created there to represent it. - IoCallDriver(DeviceExtension->DeviceObject, info->MediaChangeSyncIrp); - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleEjectionControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_MEDIA_REMOVAL - IOCTL_STORAGE_EJECTION_CONTROL - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PPREVENT_MEDIA_REMOVAL mediaRemoval = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if(RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - sizeof(PREVENT_MEDIA_REMOVAL)) - { - status = STATUS_INFO_LENGTH_MISMATCH; - } - else - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &mediaRemoval, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = PerformEjectionControl(DeviceExtension, - Request, - ((RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_STORAGE_EJECTION_CONTROL) - ? SecureMediaLock - : SimpleMediaLock), - mediaRemoval->PreventMediaRemoval); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleEnableStreaming( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handles an IOCTL_CDROM_ENABLE_STREAMING request - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Notes: - - This IOCTL is serialized because it changes read/write - behavior and we want to make sure that all previous - reads/writes have been completed before we change the - behavior. - -Return Value: - - NTSTATUS - ---*/ -{ - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PCDROM_PRIVATE_FDO_DATA fdoData = DeviceExtension->PrivateFdoData; - - WDFFILEOBJECT fileObject = NULL; - PFILE_OBJECT_CONTEXT fileObjectContext = NULL; - - NTSTATUS status = STATUS_SUCCESS; - PCDROM_STREAMING_CONTROL inputBuffer = NULL; - - BOOLEAN enforceStreamingRead = FALSE; - BOOLEAN enforceStreamingWrite = FALSE; - BOOLEAN streamingReadSupported, streamingWriteSupported; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_STREAMING_CONTROL), - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - // get file object context - fileObject = WdfRequestGetFileObject(Request); - if (fileObject != NULL) { - fileObjectContext = FileObjectGetContext(fileObject); - } - NT_ASSERT(fileObjectContext != NULL); - - if (fileObjectContext == NULL) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleEnableStreaming: cannot find file object context\n")); - status = STATUS_INVALID_HANDLE; - } - } - - if (NT_SUCCESS(status)) - { - if (inputBuffer->RequestType == CdromStreamingDisable) - { - enforceStreamingRead = FALSE; - enforceStreamingWrite = FALSE; - } - else if (inputBuffer->RequestType == CdromStreamingEnableForReadOnly) - { - enforceStreamingRead = TRUE; - enforceStreamingWrite = FALSE; - } - else if (inputBuffer->RequestType == CdromStreamingEnableForWriteOnly) - { - enforceStreamingRead = FALSE; - enforceStreamingWrite = TRUE; - } - else if (inputBuffer->RequestType == CdromStreamingEnableForReadWrite) - { - enforceStreamingRead = TRUE; - enforceStreamingWrite = TRUE; - } - - streamingReadSupported = cdData->Mmc.StreamingReadSupported && !TEST_FLAG(fdoData->HackFlags, FDO_HACK_NO_STREAMING); - streamingWriteSupported = cdData->Mmc.StreamingWriteSupported && !TEST_FLAG(fdoData->HackFlags, FDO_HACK_NO_STREAMING); - if ((enforceStreamingRead && !streamingReadSupported) || - (enforceStreamingWrite && !streamingWriteSupported)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "RequestHandleEnableStreaming: requested Streaming mode is not supported\n")); - status = STATUS_INVALID_DEVICE_REQUEST; - } - else - { - fileObjectContext->EnforceStreamingRead = enforceStreamingRead; - fileObjectContext->EnforceStreamingWrite = enforceStreamingWrite; - } - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleSendOpcInformation( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handles an IOCTL_CDROM_SEND_OPC_INFORMATION request - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_SIMPLE_OPC_INFO inputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(CDROM_SIMPLE_OPC_INFO), - (PVOID*)&inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - - // we support only the simplest version for now - cdb.SEND_OPC_INFORMATION.OperationCode = SCSIOP_SEND_OPC_INFORMATION; - cdb.SEND_OPC_INFORMATION.DoOpc = 1; - cdb.SEND_OPC_INFORMATION.Exclude0 = (inputBuffer->Exclude0 ? 1 : 0); - cdb.SEND_OPC_INFORMATION.Exclude1 = (inputBuffer->Exclude1 ? 1 : 0); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, 0, FALSE, &cdb, sizeof(cdb.SEND_OPC_INFORMATION)); - - // nothing to do after the command finishes - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetPerformance( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handles an IOCTL_CDROM_GET_PERFORMANCE request - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_PERFORMANCE_REQUEST inputBuffer = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - // Retrieve pointers to input/output data. The size has been validated earlier - // in RequestValidateGetPerformance, so we do not check it again. - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&inputBuffer, - NULL); - } - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - USHORT descriptorSize = 0; - USHORT descriptorCount = 0; - size_t transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - // Set up the CDB - RtlZeroMemory(&cdb, sizeof(CDB)); - - if (inputBuffer->RequestType == CdromPerformanceRequest) - { - cdb.GET_PERFORMANCE.Type = 0; - - // 10b is the only defined tolerance in MMCr6 - cdb.GET_PERFORMANCE.Tolerance = 2; - - switch (inputBuffer->Exceptions) { - case CdromNominalPerformance: - cdb.GET_PERFORMANCE.Except = 0; - descriptorSize = sizeof(CDROM_NOMINAL_PERFORMANCE_DESCRIPTOR); - break; - case CdromEntirePerformanceList: - cdb.GET_PERFORMANCE.Except = 1; - descriptorSize = sizeof(CDROM_NOMINAL_PERFORMANCE_DESCRIPTOR); - break; - case CdromPerformanceExceptionsOnly: - cdb.GET_PERFORMANCE.Except = 2; - descriptorSize = sizeof(CDROM_EXCEPTION_PERFORMANCE_DESCRIPTOR); - break; - } - - switch (inputBuffer->PerformanceType) { - case CdromReadPerformance: - cdb.GET_PERFORMANCE.Write = 0; break; - case CdromWritePerformance: - cdb.GET_PERFORMANCE.Write = 1; break; - } - - REVERSE_BYTES(&cdb.GET_PERFORMANCE.StartingLBA, &inputBuffer->StaringLba); - } - else if (inputBuffer->RequestType == CdromWriteSpeedRequest) - { - cdb.GET_PERFORMANCE.Type = 3; - descriptorSize = sizeof(CDROM_WRITE_SPEED_DESCRIPTOR); - } - - cdb.GET_PERFORMANCE.OperationCode = SCSIOP_GET_PERFORMANCE; - - // calculate how many descriptors can fit into the output buffer - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength >= - sizeof(CDROM_PERFORMANCE_HEADER) && - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength <= - MAXUSHORT && - descriptorSize > 0) - { - descriptorCount = (USHORT)(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength - sizeof(CDROM_PERFORMANCE_HEADER)); - descriptorCount /= descriptorSize; - } - else - { - status = STATUS_INVALID_PARAMETER; - } - - REVERSE_BYTES_SHORT(&cdb.GET_PERFORMANCE.MaximumNumberOfDescriptors, &descriptorCount); - - // Calculate transfer size. We round it up to meet adapter requirements. - // Extra bytes are discarded later, when we copy data to the output buffer. - transferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - transferSize += DeviceExtension->AdapterDescriptor->AlignmentMask; - transferSize &= ~DeviceExtension->AdapterDescriptor->AlignmentMask; - - if (NT_SUCCESS(status)) - { - status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, Request, (ULONG)transferSize, TRUE, &cdb, sizeof(cdb.GET_PERFORMANCE), CDROM_GET_PERFORMANCE_TIMEOUT); - } - - if (NT_SUCCESS(status)) - { - if (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength < sizeof(CDROM_PERFORMANCE_HEADER)) - { - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - else - { - *DataLength = min(RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength); - RtlCopyMemory(outputBuffer, - DeviceExtension->ScratchContext.ScratchBuffer, - *DataLength); - } - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleMcnSyncFakeIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handles an IOCTL_MCN_SYNC_FAKE_IOCTL request - -Arguments: - - DeviceExtension - device context - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo; - BOOLEAN shouldRetry = TRUE; - BOOLEAN requestSent = FALSE; - - PAGED_CODE (); - - *DataLength = 0; - - // - // Try to acquire the media change event. If we can't do it immediately - // then bail out and assume the caller will try again later. - // - while (shouldRetry) - { - status = RequestSetupMcnRequest(DeviceExtension, - info->Gesn.Supported); - - if (!NT_SUCCESS(status)) - { - shouldRetry = FALSE; - } - - if (NT_SUCCESS(status)) - { - requestSent = RequestSendMcnRequest(DeviceExtension); - - if (requestSent) - { - shouldRetry = RequestPostWorkMcnRequest(DeviceExtension); - } - else - { - shouldRetry = FALSE; - } - } - } - - // If there were any media change notifications that were not delivered - // for some reason, make an attempt to do so at this time. - DeviceSendDelayedMediaChangeNotifications(DeviceExtension); - - // Set the status and then complete the original request. - // The timer handler will be able to send the next request. - status = STATUS_SUCCESS; - - return status; -} - -BOOLEAN -RequestIsRealtimeStreaming( - _In_ WDFREQUEST Request, - _In_ BOOLEAN IsReadRequest - ) -/*++ - -Routine Description: - - Checks whether a given read/write request should - be performed in Real-Time Streaming mode. - -Arguments: - - Request - request to be checked - IsReadRequest - TRUE = read request; FALSE = write request - -Return Value: - - TRUE - a Real-Time Streaming operation has to be performed - FALSE - a normal (non-Streaming) operation has to be performed - ---*/ -{ - BOOLEAN useStreaming = FALSE; - - if (!useStreaming) { - // - // Check if we're required to use Streaming via I/O Stack Location flags - // - UCHAR currentStackLocationFlags = 0; - currentStackLocationFlags = RequestGetCurrentStackLocationFlags(Request); - - useStreaming = TEST_FLAG(currentStackLocationFlags, SL_REALTIME_STREAM); - } - - if (!useStreaming) { - // - // Check if we were previously requested to enforce Streaming for - // the file handle through which this request was sent. - // - - WDFFILEOBJECT fileObject; - PFILE_OBJECT_CONTEXT fileObjectContext; - - fileObject = WdfRequestGetFileObject(Request); - - if (fileObject != NULL) { - fileObjectContext = FileObjectGetContext(fileObject); - NT_ASSERT(fileObjectContext != NULL); - - if (IsReadRequest && fileObjectContext->EnforceStreamingRead) - { - useStreaming = TRUE; - } - - if (!IsReadRequest && fileObjectContext->EnforceStreamingWrite) - { - useStreaming = TRUE; - } - } - } - - return useStreaming; -} - - -NTSTATUS -RequestValidateReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ - -Routine Description: - - Validate Read/Write request - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - BOOLEAN isValid = TRUE; - LONGLONG startingOffset = 0; - size_t transferByteCount = 0; - PIRP irp = NULL; - PIO_STACK_LOCATION currentStack = NULL; - - irp = WdfRequestWdmGetIrp(Request); - currentStack = IoGetCurrentIrpStackLocation(irp); - - if (TEST_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME) && - (currentStack->MinorFunction != CDROM_VOLUME_VERIFY_CHECKED) && - !TEST_FLAG(currentStack->Flags, SL_OVERRIDE_VERIFY_VOLUME)) - { - // DO_VERIFY_VOLUME is set for the device object, - // but this request is not itself a verify request. - // So fail this request. - - //set the status for volume verification. - status = STATUS_VERIFY_REQUIRED; - } - - if (NT_SUCCESS(status)) - { - if (PLAY_ACTIVE(DeviceExtension)) - { - status = STATUS_DEVICE_BUSY; - } - } - - if (NT_SUCCESS(status)) - { - // If the device is in exclusive mode, check whether the request is from - // the handle that locked the device. - if (EXCLUSIVE_MODE(cdData) && !EXCLUSIVE_OWNER(cdData, WdfRequestGetFileObject(Request))) - { - // This request is not from the owner. We can't let the operation go. - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, "RequestValidateReadWrite: Access Denied! Device in exclusive mode.\n")); - - status = STATUS_ACCESS_DENIED; - } - } - - // Validate the request alignment. - if (NT_SUCCESS(status)) - { - if (RequestParameters.Type == WdfRequestTypeRead) - { - startingOffset = RequestParameters.Parameters.Read.DeviceOffset; - transferByteCount = RequestParameters.Parameters.Read.Length; - } - else - { - startingOffset = RequestParameters.Parameters.Write.DeviceOffset; - transferByteCount = RequestParameters.Parameters.Write.Length; - } - - if (!DeviceExtension->DiskGeometry.BytesPerSector) - { - DeviceExtension->DiskGeometry.BytesPerSector = 2048; - } - - if (!DeviceExtension->SectorShift) - { - DeviceExtension->SectorShift = 11; - } - - // Perform some basic validation up front - if (TEST_FLAG(startingOffset, DeviceExtension->DiskGeometry.BytesPerSector - 1) || - TEST_FLAG(transferByteCount, DeviceExtension->DiskGeometry.BytesPerSector - 1)) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - // validate the request against the current mmc schema - if (NT_SUCCESS(status)) - { - FEATURE_NUMBER schema = cdData->Mmc.ValidationSchema; - - // We validate read requests according to the RandomWritable schema, except in the - // case of IncrementalStreamingWritable, wherein the drive is responsible for all - // of the verification - if (RequestParameters.Type == WdfRequestTypeRead) - { - if (!cdData->Mmc.WriteAllowed) - { - // standard legacy validation of read irps - // if writing is not allowed on the media - schema = FeatureRandomWritable; - } - else if (schema != FeatureIncrementalStreamingWritable) - { - // standard legacy validation of read irps - // if not using streaming writes on writable media - schema = FeatureRandomWritable; - } - } - - // Fail write requests to read-only media - if ((RequestParameters.Type == WdfRequestTypeWrite) && - !(cdData->Mmc.WriteAllowed)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, "RequestValidateReadWrite: Write request to read-only media\n")); - isValid = FALSE; - } - - if (isValid) - { - switch (schema) - { - case FeatureDefectManagement: - case FeatureRandomWritable: - // Ensure that the request is within bounds for ROM drives. - // Writer drives do not need to have bounds as outbounds request should not damage the drive. - if(!cdData->Mmc.IsWriter) - { - if ((startingOffset >= DeviceExtension->PartitionLength.QuadPart) || - startingOffset < 0) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, "RequestValidateReadWrite: Request is out of bounds\n")); - isValid = FALSE; - - } - else - { - ULONGLONG bytesRemaining = DeviceExtension->PartitionLength.QuadPart - startingOffset; - - if ((ULONGLONG)transferByteCount > bytesRemaining) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, "RequestValidateReadWrite: Request is out of bounds\n")); - isValid = FALSE; - } - } - } - break; - - case FeatureRigidRestrictedOverwrite: - // Ensure that the number of blocks is a multiple of the blocking size - if (((transferByteCount >> DeviceExtension->SectorShift) % cdData->Mmc.Blocking) != 0) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, - "RequestValidateReadWrite: Number of blocks is not a multiple of the blocking size (%x)\n", - cdData->Mmc.Blocking)); - - isValid = FALSE; - } - // Fall through - case FeatureRestrictedOverwrite: - // Ensure that the request begins on a blocking boundary - if ((Int64ShrlMod32(startingOffset, DeviceExtension->SectorShift) % cdData->Mmc.Blocking) != 0) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, - "RequestValidateReadWrite: Starting block is not a multiple of the blocking size (%x)\n", - cdData->Mmc.Blocking)); - - isValid = FALSE; - } - break; - - case FeatureIncrementalStreamingWritable: - // Let the drive handle the verification - break; - - default: - // Unknown schema. Fail the request - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, - "RequestValidateReadWrite: Unknown validation schema (%x)\n", - schema)); - - isValid = FALSE; - break; - } //end of switch (schema) - } // end of if (isValid) - - if (!isValid) - { - status = STATUS_INVALID_DEVICE_REQUEST; - } - } // end of mmc schema validation - - // validate that the Real-Time Streaming requests meet device capabilties - if (NT_SUCCESS(status)) - { - // We do not check for FDO_HACK_NO_STREAMING in DeviceExtension->PrivateFdoData->HackFlags here, - // because we're going to hide device failures related to streaming reads/writes from the sender - // of the request. FDO_HACK_NO_STREAMING is going to be taken into account later during actual - // processing of the request. - if (RequestIsRealtimeStreaming(Request, RequestParameters.Type == WdfRequestTypeRead)) - { - if (RequestParameters.Type == WdfRequestTypeRead && !cdData->Mmc.StreamingReadSupported) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, - "RequestValidateReadWrite: Streaming reads are not supported.\n")); - - status = STATUS_INVALID_DEVICE_REQUEST; - } - if (RequestParameters.Type == WdfRequestTypeWrite && !cdData->Mmc.StreamingWriteSupported) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_RW, - "RequestValidateReadWrite: Streaming writes are not supported.\n")); - - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - } - - return status; -} - -NTSTATUS -RequestHandleReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ) -/*++ - -Routine Description: - - Handle a read/write request - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - - size_t transferByteCount = 0; - PIRP irp = NULL; - PIO_STACK_LOCATION currentStack = NULL; - - PUCHAR dataBuffer; - - - irp = WdfRequestWdmGetIrp(Request); - currentStack = IoGetCurrentIrpStackLocation(irp); - dataBuffer = MmGetMdlVirtualAddress(irp->MdlAddress); - - if (NT_SUCCESS(status)) - { - if (RequestParameters.Type == WdfRequestTypeRead) - { - transferByteCount = RequestParameters.Parameters.Read.Length; - } - else - { - transferByteCount = RequestParameters.Parameters.Write.Length; - } - - if (transferByteCount == 0) - { - // Several parts of the code turn 0 into 0xffffffff, - // so don't process a zero-length request any further. - status = STATUS_SUCCESS; - RequestCompletion(DeviceExtension, Request, status, 0); - return status; - } - - // Add partition byte offset to make starting byte relative to - // beginning of disk. - currentStack->Parameters.Read.ByteOffset.QuadPart += (DeviceExtension->StartingOffset.QuadPart); - - //not very necessary as the starting offset for CD/DVD device is always 0. - if (RequestParameters.Type == WdfRequestTypeRead) - { - RequestParameters.Parameters.Read.DeviceOffset = currentStack->Parameters.Read.ByteOffset.QuadPart; - } - else - { - RequestParameters.Parameters.Write.DeviceOffset = currentStack->Parameters.Write.ByteOffset.QuadPart; - } - } - - if (NT_SUCCESS(status)) - { - ULONG entireXferLen = currentStack->Parameters.Read.Length; - ULONG maxLength = 0; - ULONG packetsCount = 0; - - PCDROM_SCRATCH_READ_WRITE_CONTEXT readWriteContext; - PCDROM_REQUEST_CONTEXT requestContext; - PCDROM_REQUEST_CONTEXT originalRequestContext; - - // get the count of packets we need to send. - if ((((ULONG_PTR)dataBuffer) & (PAGE_SIZE-1)) == 0) - { - maxLength = cdData->MaxPageAlignedTransferBytes; - } - else - { - maxLength = cdData->MaxUnalignedTransferBytes; - } - - packetsCount = entireXferLen / maxLength; - - if (entireXferLen % maxLength != 0) - { - packetsCount++; - } - - originalRequestContext = RequestGetContext(Request); - - - ScratchBuffer_BeginUse(DeviceExtension); - - readWriteContext = &DeviceExtension->ScratchContext.ScratchReadWriteContext; - requestContext = RequestGetContext(DeviceExtension->ScratchContext.ScratchRequest); - - readWriteContext->PacketsCount = packetsCount; - readWriteContext->EntireXferLen = entireXferLen; - readWriteContext->MaxLength = maxLength; - readWriteContext->StartingOffset = currentStack->Parameters.Read.ByteOffset; - readWriteContext->DataBuffer = dataBuffer; - readWriteContext->TransferedBytes = 0; - readWriteContext->IsRead = (RequestParameters.Type == WdfRequestTypeRead); - - requestContext->OriginalRequest = Request; - requestContext->DeviceExtension = DeviceExtension; - - // - // Setup the READ/WRITE fields in the original request which is what - // we use to properly synchronize cancellation logic between the - // cancel callback and the timer routine. - // - - originalRequestContext->ReadWriteIsCompleted = FALSE; - originalRequestContext->ReadWriteRetryInitialized = FALSE; - originalRequestContext->DeviceExtension = DeviceExtension; - - status = ScratchBuffer_PerformNextReadWrite(DeviceExtension, TRUE); - - // We do not call ScratchBuffer_EndUse here, because we're not releasing the scratch SRB. - // It will be released in the completion routine. - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleLoadEjectMedia( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_EJECT_MEDIA - IOCTL_STORAGE_LOAD_MEDIA - IOCTL_STORAGE_LOAD_MEDIA2 - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - // Synchronize with ejection control and ejection cleanup code as - // well as other eject/load requests. - WdfWaitLockAcquire(DeviceExtension->EjectSynchronizationLock, NULL); - - if(DeviceExtension->ProtectedLockCount != 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "RequestHandleLoadEjectMedia: call to eject protected locked " - "device - failure\n")); - status = STATUS_DEVICE_BUSY; - } - - if (NT_SUCCESS(status)) - { - SCSI_REQUEST_BLOCK srb; - PCDB cdb = (PCDB)srb.Cdb; - - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - srb.CdbLength = 6; - - cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT; - cdb->START_STOP.LoadEject = 1; - - if(RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_STORAGE_EJECT_MEDIA) - { - cdb->START_STOP.Start = 0; - - // We are sending down a soft eject, and in this case we should take an active ref - // if the command succeeds. - if ((zpoddInfo != NULL) && - (zpoddInfo->LoadingMechanism == LOADING_MECHANISM_TRAY) && - (zpoddInfo->Load == 0)) // Drawer - { - zpoddInfo->MonitorStartStopUnit = TRUE; - } - } - else - { - cdb->START_STOP.Start = 1; - } - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - NULL, - 0, - FALSE, - Request); - - if (zpoddInfo != NULL) - { - zpoddInfo->MonitorStartStopUnit = FALSE; - } - } - - WdfWaitLockRelease(DeviceExtension->EjectSynchronizationLock); - } - - return status; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleReserveRelease( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_RESERVE - IOCTL_STORAGE_RELEASE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSCSI_REQUEST_BLOCK srb = NULL; - PCDB cdb = NULL; - ULONG ioctlCode = 0; - - PAGED_CODE (); - - *DataLength = 0; - - srb = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SCSI_REQUEST_BLOCK) + - (sizeof(ULONG_PTR) * 2), - CDROM_TAG_SRB); - - if (srb == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - - if (NT_SUCCESS(status)) - { - ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - cdb = (PCDB)srb->Cdb; - - if (TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_NO_RESERVE6)) - { - srb->CdbLength = 10; - cdb->CDB10.OperationCode = (ioctlCode == IOCTL_STORAGE_RESERVE) ? SCSIOP_RESERVE_UNIT10 : SCSIOP_RELEASE_UNIT10; - } - else - { - srb->CdbLength = 6; - cdb->CDB6GENERIC.OperationCode = (ioctlCode == IOCTL_STORAGE_RESERVE) ? SCSIOP_RESERVE_UNIT : SCSIOP_RELEASE_UNIT; - } - - // Set timeout value. - srb->TimeOutValue = DeviceExtension->TimeOutValue; - - // Send reserves as tagged requests. - if (ioctlCode == IOCTL_STORAGE_RESERVE) - { - SET_FLAG(srb->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE); - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - } - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - srb, - NULL, - 0, - FALSE, - Request); - // no data transfer. - *DataLength = 0; - - FREE_POOL(srb); - } - - return status; -} // end RequestHandleReserveRelease() - -__inline -BOOLEAN -ValidPersistentReserveScope( - UCHAR Scope) -{ - switch (Scope) { - case RESERVATION_SCOPE_LU: - case RESERVATION_SCOPE_ELEMENT: - - return TRUE; - - default: - - return FALSE; - } -} - -__inline -BOOLEAN -ValidPersistentReserveType( - UCHAR Type) -{ - switch (Type) { - case RESERVATION_TYPE_WRITE_EXCLUSIVE: - case RESERVATION_TYPE_EXCLUSIVE: - case RESERVATION_TYPE_WRITE_EXCLUSIVE_REGISTRANTS: - case RESERVATION_TYPE_EXCLUSIVE_REGISTRANTS: - - return TRUE; - - default: - - return FALSE; - } -} - -NTSTATUS -RequestValidatePersistentReserve( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Validate request of IOCTL_STORAGE_PERSISTENT_RESERVE_IN - IOCTL_STORAGE_PERSISTENT_RESERVE_OUT - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - - PPERSISTENT_RESERVE_COMMAND reserveCommand = NULL; - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&reserveCommand, - NULL); - if (NT_SUCCESS(status)) - { - if ((RequestParameters.Parameters.DeviceIoControl.InputBufferLength < sizeof(PERSISTENT_RESERVE_COMMAND)) || - (reserveCommand->Size < sizeof(PERSISTENT_RESERVE_COMMAND))) - { - *DataLength = 0; - status = STATUS_INFO_LENGTH_MISMATCH; - } - else if ((ULONG_PTR)reserveCommand & DeviceExtension->AdapterDescriptor->AlignmentMask) - { - // Check buffer alignment. Only an issue if another kernel mode component - // (not the I/O manager) allocates the buffer. - *DataLength = 0; - status = STATUS_INVALID_USER_BUFFER; - } - } - - if (NT_SUCCESS(status)) - { - if (ioctlCode == IOCTL_STORAGE_PERSISTENT_RESERVE_IN) - { - if (RequestParameters.Parameters.DeviceIoControl.OutputBufferLength < reserveCommand->PR_IN.AllocationLength) - { - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - else - { - switch (reserveCommand->PR_IN.ServiceAction) - { - case RESERVATION_ACTION_READ_KEYS: - if (reserveCommand->PR_IN.AllocationLength < sizeof(PRI_REGISTRATION_LIST)) - { - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - break; - - case RESERVATION_ACTION_READ_RESERVATIONS: - if (reserveCommand->PR_IN.AllocationLength < sizeof(PRI_RESERVATION_LIST)) - { - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - break; - - default: - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - break; - } - } - } - else // case of IOCTL_STORAGE_PERSISTENT_RESERVE_OUT - { - // Verify ServiceAction, Scope, and Type - switch (reserveCommand->PR_OUT.ServiceAction) - { - case RESERVATION_ACTION_REGISTER: - case RESERVATION_ACTION_REGISTER_IGNORE_EXISTING: - case RESERVATION_ACTION_CLEAR: - // Scope and type ignored. - break; - - case RESERVATION_ACTION_RESERVE: - case RESERVATION_ACTION_RELEASE: - case RESERVATION_ACTION_PREEMPT: - case RESERVATION_ACTION_PREEMPT_ABORT: - if (!ValidPersistentReserveScope(reserveCommand->PR_OUT.Scope) || - !ValidPersistentReserveType(reserveCommand->PR_OUT.Type)) - { - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - break; - - default: - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - break; - } - - // Check input buffer for PR Out. - // Caller must include the PR parameter list. - if (NT_SUCCESS(status)) - { - if ((RequestParameters.Parameters.DeviceIoControl.InputBufferLength < - (sizeof(PERSISTENT_RESERVE_COMMAND) + sizeof(PRO_PARAMETER_LIST))) || - (reserveCommand->Size < RequestParameters.Parameters.DeviceIoControl.InputBufferLength)) - { - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - } - } // end of validation for IOCTL_STORAGE_PERSISTENT_RESERVE_OUT - } - - return status; -} // end RequestValidatePersistentReserve() - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandlePersistentReserve( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_PERSISTENT_RESERVE_IN - IOCTL_STORAGE_PERSISTENT_RESERVE_OUT - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG ioctlCode = RequestParameters.Parameters.DeviceIoControl.IoControlCode; - PSCSI_REQUEST_BLOCK srb = NULL; - PCDB cdb = NULL; - BOOLEAN writeToDevice; - - PPERSISTENT_RESERVE_COMMAND reserveCommand = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&reserveCommand, - NULL); - if (NT_SUCCESS(status)) - { - srb = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SCSI_REQUEST_BLOCK) + - (sizeof(ULONG_PTR) * 2), - CDROM_TAG_SRB); - - if (srb == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - cdb = (PCDB)srb->Cdb; - RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK)); - } - } - - if (NT_SUCCESS(status)) - { - size_t dataBufLen = 0; - - // Fill in the CDB. - if (ioctlCode == IOCTL_STORAGE_PERSISTENT_RESERVE_IN) - { - cdb->PERSISTENT_RESERVE_IN.OperationCode = SCSIOP_PERSISTENT_RESERVE_IN; - cdb->PERSISTENT_RESERVE_IN.ServiceAction = reserveCommand->PR_IN.ServiceAction; - - REVERSE_BYTES_SHORT(&(cdb->PERSISTENT_RESERVE_IN.AllocationLength), - &(reserveCommand->PR_IN.AllocationLength)); - - dataBufLen = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - writeToDevice = FALSE; - } - else - { - cdb->PERSISTENT_RESERVE_OUT.OperationCode = SCSIOP_PERSISTENT_RESERVE_OUT; - cdb->PERSISTENT_RESERVE_OUT.ServiceAction = reserveCommand->PR_OUT.ServiceAction; - cdb->PERSISTENT_RESERVE_OUT.Scope = reserveCommand->PR_OUT.Scope; - cdb->PERSISTENT_RESERVE_OUT.Type = reserveCommand->PR_OUT.Type; - - cdb->PERSISTENT_RESERVE_OUT.ParameterListLength[1] = (UCHAR)sizeof(PRO_PARAMETER_LIST); - - // Move the parameter list to the beginning of the data buffer (so it is aligned - // correctly and that the MDL describes it correctly). - RtlMoveMemory(reserveCommand, - reserveCommand->PR_OUT.ParameterList, - sizeof(PRO_PARAMETER_LIST)); - - dataBufLen = sizeof(PRO_PARAMETER_LIST); - writeToDevice = TRUE; - } - - srb->CdbLength = 10; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - srb, - reserveCommand, - (ULONG) dataBufLen, - writeToDevice, - Request); - - FREE_POOL(srb); - } - - return status; -} - -#if (NTDDI_VERSION >= NTDDI_WIN8) -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleAreVolumesReady( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DISK_ARE_VOLUMES_READY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - BOOLEAN completeRequest = TRUE; - NTSTATUS status = STATUS_SUCCESS; - - UNREFERENCED_PARAMETER(RequestParameters); - - *DataLength = 0; - - if (DeviceExtension->IsVolumeOnlinePending == FALSE) - { - status = STATUS_SUCCESS; - goto Cleanup; - } - - // - // Add to the volume ready queue. No worries about request cancellation, - // since KMDF will automatically handle that while request is in queue. - // - status = WdfRequestForwardToIoQueue(Request, - DeviceExtension->ManualVolumeReadyQueue - ); - - if(!NT_SUCCESS(status)) - { - goto Cleanup; - } - - status = STATUS_PENDING; - completeRequest = FALSE; - -Cleanup: - - if (completeRequest) - { - RequestCompletion(DeviceExtension, Request, status, 0); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleVolumeOnline( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_VOLUME_ONLINE / IOCTL_VOLUME_POST_ONLINE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFREQUEST request; - PIRP irp = NULL; - PIO_STACK_LOCATION nextStack = NULL; - - UNREFERENCED_PARAMETER(RequestParameters); - - *DataLength = 0; - - DeviceExtension->IsVolumeOnlinePending = FALSE; - - // Complete all parked volume ready requests. - for (;;) - { - status = WdfIoQueueRetrieveNextRequest(DeviceExtension->ManualVolumeReadyQueue, - &request); - - if (!NT_SUCCESS(status)) - { - break; - } - - RequestCompletion(DeviceExtension, request, STATUS_SUCCESS, 0); - } - - // Change the IOCTL code to IOCTL_DISK_VOLUMES_ARE_READY, and forward the request down, - // so that if the underlying port driver will also know that volume is ready. - WdfRequestFormatRequestUsingCurrentType(Request); - irp = WdfRequestWdmGetIrp(Request); - nextStack = IoGetNextIrpStackLocation(irp); - - irp->AssociatedIrp.SystemBuffer = &DeviceExtension->DeviceNumber; - nextStack->Parameters.DeviceIoControl.OutputBufferLength = 0; - nextStack->Parameters.DeviceIoControl.InputBufferLength = sizeof (DeviceExtension->DeviceNumber); - nextStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_DISK_VOLUMES_ARE_READY; - - // Send the request straight down (synchronously). - RequestSend(DeviceExtension, - Request, - DeviceExtension->IoTarget, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - NULL); - - return STATUS_SUCCESS; -} -#endif - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceHandleRawRead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_RAW_READ - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - // Determine whether the drive is currently in raw or cooked mode, - // and which command to use to read the data. - - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - RAW_READ_INFO rawReadInfo = {0}; - PVOID outputVirtAddr = NULL; - ULONG startingSector; - - PIRP irp = WdfRequestWdmGetIrp(Request); - PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(irp); - - VOID* outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - if (TEST_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME) && - (currentIrpStack->MinorFunction != CDROM_VOLUME_VERIFY_CHECKED) && - !TEST_FLAG(currentIrpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME)) - { - // DO_VERIFY_VOLUME is set for the device object, - // but this request is not itself a verify request. - // So fail this request. - (VOID) MediaReadCapacity(DeviceExtension->Device); - - *DataLength = 0; - //set the status for volume verification. - status = STATUS_VERIFY_REQUIRED; - } - - if (NT_SUCCESS(status)) - { - // Since this ioctl is METHOD_OUT_DIRECT, we need to copy away - // the input buffer before interpreting it. This prevents a - // malicious app from messing with the input buffer while we - // are interpreting it. This is done in dispacth. - // - // Here, we are going to get the input buffer out of saved place. - rawReadInfo = *(PRAW_READ_INFO)currentIrpStack->Parameters.DeviceIoControl.Type3InputBuffer; - - if (currentIrpStack->Parameters.DeviceIoControl.OutputBufferLength > 0) - { - // Make sure that any user buffer that we pass down to - // the hardware is properly aligned - NT_ASSERT(irp->MdlAddress); - outputVirtAddr = MmGetMdlVirtualAddress(irp->MdlAddress); - if ((ULONG_PTR)outputVirtAddr & DeviceExtension->AdapterDescriptor->AlignmentMask) - { - NT_ASSERT(!((ULONG_PTR)outputVirtAddr & DeviceExtension->AdapterDescriptor->AlignmentMask)); - *DataLength = 0; - status = STATUS_INVALID_PARAMETER; - } - } - else - { - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - switch (rawReadInfo.TrackMode) - { - case CDDA: - case YellowMode2: - case XAForm2: - // no check needed. - break; - - case RawWithC2AndSubCode: - if (!cdData->Mmc.ReadCdC2Pointers || !cdData->Mmc.ReadCdSubCode) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "Request to read C2 & Subcode rejected. " - "Is C2 supported: %d Is Subcode supported: %d\n", - cdData->Mmc.ReadCdC2Pointers, - cdData->Mmc.ReadCdSubCode - )); - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - break; - case RawWithC2: - if (!cdData->Mmc.ReadCdC2Pointers) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "Request to read C2 rejected because drive does not " - "report support for C2 pointers\n" - )); - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - break; - case RawWithSubCode: - - if (!cdData->Mmc.ReadCdSubCode) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "Request to read subcode rejected because drive does " - "not report support for reading the subcode data\n" - )); - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - break; - - default: - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - break; - } - } - - if (NT_SUCCESS(status)) - { - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PCDB cdb = (PCDB)(srb->Cdb); - - size_t transferByteCount; - BOOLEAN shouldRetry = TRUE; - ULONG timesAlreadyRetried = 0; - LONGLONG retryIn100nsUnits = 0; - - transferByteCount = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength; - - ScratchBuffer_BeginUse(DeviceExtension); - - while (shouldRetry) - { - // Setup cdb depending upon the sector type we want. - switch (rawReadInfo.TrackMode) - { - case CDDA: - transferByteCount = rawReadInfo.SectorCount * RAW_SECTOR_SIZE; - cdb->READ_CD.ExpectedSectorType = CD_DA_SECTOR; - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 3; - cdb->READ_CD.IncludeSyncData = 1; - break; - - case YellowMode2: - transferByteCount = rawReadInfo.SectorCount * RAW_SECTOR_SIZE; - cdb->READ_CD.ExpectedSectorType = YELLOW_MODE2_SECTOR; - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 1; - cdb->READ_CD.IncludeSyncData = 1; - break; - - case XAForm2: - transferByteCount = rawReadInfo.SectorCount * RAW_SECTOR_SIZE; - cdb->READ_CD.ExpectedSectorType = FORM2_MODE2_SECTOR; - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 3; - cdb->READ_CD.IncludeSyncData = 1; - break; - - case RawWithC2AndSubCode: - transferByteCount = rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_C2_AND_SUBCODE_SIZE; - cdb->READ_CD.ExpectedSectorType = 0; // Any sector type - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 3; // Header and subheader returned - cdb->READ_CD.IncludeSyncData = 1; - cdb->READ_CD.ErrorFlags = 2; // C2 and block error - cdb->READ_CD.SubChannelSelection = 1; // raw subchannel data - break; - - case RawWithC2: - transferByteCount = rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_C2_SIZE; - cdb->READ_CD.ExpectedSectorType = 0; // Any sector type - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 3; // Header and subheader returned - cdb->READ_CD.IncludeSyncData = 1; - cdb->READ_CD.ErrorFlags = 2; // C2 and block error - break; - - case RawWithSubCode: - transferByteCount = rawReadInfo.SectorCount * CD_RAW_SECTOR_WITH_SUBCODE_SIZE; - cdb->READ_CD.ExpectedSectorType = 0; // Any sector type - cdb->READ_CD.IncludeUserData = 1; - cdb->READ_CD.HeaderCode = 3; // Header and subheader returned - cdb->READ_CD.IncludeSyncData = 1; - cdb->READ_CD.SubChannelSelection = 1; // raw subchannel data - break; - - default: - // should already checked before coming in loop. - NT_ASSERT(FALSE); - break; - } - - ScratchBuffer_SetupSrb(DeviceExtension, Request, (ULONG)transferByteCount, TRUE); - // Restore the buffer, buffer size and MdlAddress. They got changed but we don't want to use the scratch buffer. - { - PIRP scratchIrp = WdfRequestWdmGetIrp(DeviceExtension->ScratchContext.ScratchRequest); - scratchIrp->MdlAddress = irp->MdlAddress; - srb->DataBuffer = outputVirtAddr; - srb->DataTransferLength = (ULONG)transferByteCount; - } - // Calculate starting offset. - startingSector = (ULONG)(rawReadInfo.DiskOffset.QuadPart >> DeviceExtension->SectorShift); - - // Fill in CDB fields. - srb->CdbLength = 12; - - cdb->READ_CD.OperationCode = SCSIOP_READ_CD; - cdb->READ_CD.TransferBlocks[2] = (UCHAR) (rawReadInfo.SectorCount & 0xFF); - cdb->READ_CD.TransferBlocks[1] = (UCHAR) (rawReadInfo.SectorCount >> 8 ); - cdb->READ_CD.TransferBlocks[0] = (UCHAR) (rawReadInfo.SectorCount >> 16); - - cdb->READ_CD.StartingLBA[3] = (UCHAR) (startingSector & 0xFF); - cdb->READ_CD.StartingLBA[2] = (UCHAR) ((startingSector >> 8)); - cdb->READ_CD.StartingLBA[1] = (UCHAR) ((startingSector >> 16)); - cdb->READ_CD.StartingLBA[0] = (UCHAR) ((startingSector >> 24)); - - ScratchBuffer_SendSrb(DeviceExtension, TRUE, NULL); - - if ((DeviceExtension->ScratchContext.ScratchSrb->SrbStatus == SRB_STATUS_ABORTED) && - (DeviceExtension->ScratchContext.ScratchSrb->InternalStatus == STATUS_CANCELLED)) - { - shouldRetry = FALSE; - status = STATUS_CANCELLED; - } - else - { - shouldRetry = RequestSenseInfoInterpretForScratchBuffer(DeviceExtension, - timesAlreadyRetried, - &status, - &retryIn100nsUnits); - if (shouldRetry) - { - LARGE_INTEGER t; - t.QuadPart = -retryIn100nsUnits; - timesAlreadyRetried++; - KeDelayExecutionThread(KernelMode, FALSE, &t); - // keep items clean - ScratchBuffer_ResetItems(DeviceExtension, FALSE); - } - } - } - - if (NT_SUCCESS(status)) - { - *DataLength = srb->DataTransferLength; - } - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandlePlayAudioMsf( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_PLAY_AUDIO_MSF - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_PLAY_AUDIO_MSF inputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&inputBuffer, - NULL); - - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.PLAY_AUDIO_MSF.OperationCode = SCSIOP_PLAY_AUDIO_MSF; - - cdb.PLAY_AUDIO_MSF.StartingM = inputBuffer->StartingM; - cdb.PLAY_AUDIO_MSF.StartingS = inputBuffer->StartingS; - cdb.PLAY_AUDIO_MSF.StartingF = inputBuffer->StartingF; - - cdb.PLAY_AUDIO_MSF.EndingM = inputBuffer->EndingM; - cdb.PLAY_AUDIO_MSF.EndingS = inputBuffer->EndingS; - cdb.PLAY_AUDIO_MSF.EndingF = inputBuffer->EndingF; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - PLAY_ACTIVE(DeviceExtension) = TRUE; - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadQChannel( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_READ_Q_CHANNEL - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PVOID inputBuffer = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = ReadQChannel(DeviceExtension, - Request, - inputBuffer, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - outputBuffer, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DataLength); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ReadQChannel( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - base function to handle request of IOCTL_CDROM_READ_Q_CHANNEL - -Arguments: - - DeviceExtension - device context - OriginalRequest - original request to be handled - InputBuffer - input buffer - InputBufferLength - length of input buffer - OutputBuffer - output buffer - OutputBufferLength - length of output buffer - -Return Value: - - NTSTATUS - DataLength - returned data length - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG transferByteCount = 0; - CDB cdb; - PCDROM_SUB_Q_DATA_FORMAT inputBuffer = (PCDROM_SUB_Q_DATA_FORMAT)InputBuffer; - PSUB_Q_CHANNEL_DATA userChannelData = (PSUB_Q_CHANNEL_DATA)OutputBuffer; - - PAGED_CODE (); - - UNREFERENCED_PARAMETER(InputBufferLength); - - *DataLength = 0; - - // Set size of channel data -- however, this is dependent on - // what information we are requesting (which Format) - switch( inputBuffer->Format ) - { - case IOCTL_CDROM_CURRENT_POSITION: - transferByteCount = sizeof(SUB_Q_CURRENT_POSITION); - break; - - case IOCTL_CDROM_MEDIA_CATALOG: - transferByteCount = sizeof(SUB_Q_MEDIA_CATALOG_NUMBER); - break; - - case IOCTL_CDROM_TRACK_ISRC: - transferByteCount = sizeof(SUB_Q_TRACK_ISRC); - break; - } - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - // Always logical unit 0, but only use MSF addressing - // for IOCTL_CDROM_CURRENT_POSITION - if (inputBuffer->Format==IOCTL_CDROM_CURRENT_POSITION) - { - cdb.SUBCHANNEL.Msf = CDB_USE_MSF; - } - - // Return subchannel data - cdb.SUBCHANNEL.SubQ = CDB_SUBCHANNEL_BLOCK; - - // Specify format of informatin to return - cdb.SUBCHANNEL.Format = inputBuffer->Format; - - // Specify which track to access (only used by Track ISRC reads) - if (inputBuffer->Format==IOCTL_CDROM_TRACK_ISRC) - { - cdb.SUBCHANNEL.TrackNumber = inputBuffer->Track; - } - - cdb.SUBCHANNEL.AllocationLength[0] = (UCHAR) (transferByteCount >> 8); - cdb.SUBCHANNEL.AllocationLength[1] = (UCHAR) (transferByteCount & 0xFF); - cdb.SUBCHANNEL.OperationCode = SCSIOP_READ_SUB_CHANNEL; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, OriginalRequest, transferByteCount, TRUE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - PSUB_Q_CHANNEL_DATA subQPtr = DeviceExtension->ScratchContext.ScratchSrb->DataBuffer; - -#if DBG - switch( inputBuffer->Format ) - { - case IOCTL_CDROM_CURRENT_POSITION: - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Audio Status is %u\n", subQPtr->CurrentPosition.Header.AudioStatus )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: ADR = 0x%x\n", subQPtr->CurrentPosition.ADR )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Control = 0x%x\n", subQPtr->CurrentPosition.Control )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Track = %u\n", subQPtr->CurrentPosition.TrackNumber )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Index = %u\n", subQPtr->CurrentPosition.IndexNumber )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Absolute Address = %x\n", *((PULONG)subQPtr->CurrentPosition.AbsoluteAddress) )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Relative Address = %x\n", *((PULONG)subQPtr->CurrentPosition.TrackRelativeAddress) )); - break; - - case IOCTL_CDROM_MEDIA_CATALOG: - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Audio Status is %u\n", subQPtr->MediaCatalog.Header.AudioStatus )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Mcval is %u\n", subQPtr->MediaCatalog.Mcval )); - break; - - case IOCTL_CDROM_TRACK_ISRC: - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Audio Status is %u\n", subQPtr->TrackIsrc.Header.AudioStatus )); - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,"ReadQChannel: Tcval is %u\n", subQPtr->TrackIsrc.Tcval )); - break; - } -#endif - - // Update the play active status. - if (subQPtr->CurrentPosition.Header.AudioStatus == AUDIO_STATUS_IN_PROGRESS) - { - PLAY_ACTIVE(DeviceExtension) = TRUE; - } - else - { - PLAY_ACTIVE(DeviceExtension) = FALSE; - } - - // Check if output buffer is large enough to contain - // the data. - if (OutputBufferLength < DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength) - { - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength = (ULONG)OutputBufferLength; - } - - // Copy our buffer into users. - RtlMoveMemory(userChannelData, - subQPtr, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength); - - *DataLength = DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandlePauseAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_PAUSE_AUDIO - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.PAUSE_RESUME.OperationCode = SCSIOP_PAUSE_RESUME; - cdb.PAUSE_RESUME.Action = CDB_AUDIO_PAUSE; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - PLAY_ACTIVE(DeviceExtension) = FALSE; - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleResumeAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_RESUME_AUDIO - -Arguments: - - DeviceExtension - device context - Request - request to be handled - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.PAUSE_RESUME.OperationCode = SCSIOP_PAUSE_RESUME; - cdb.PAUSE_RESUME.Action = CDB_AUDIO_RESUME; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - PLAY_ACTIVE(DeviceExtension) = TRUE; //not in original code. But we should set it. - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSeekAudioMsf( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_SEEK_AUDIO_MSF - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_SEEK_AUDIO_MSF inputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - ULONG logicalBlockAddress; - - logicalBlockAddress = MSF_TO_LBA(inputBuffer->M, inputBuffer->S, inputBuffer->F); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SEEK.OperationCode = SCSIOP_SEEK; - cdb.SEEK.LogicalBlockAddress[0] = ((PFOUR_BYTE)&logicalBlockAddress)->Byte3; - cdb.SEEK.LogicalBlockAddress[1] = ((PFOUR_BYTE)&logicalBlockAddress)->Byte2; - cdb.SEEK.LogicalBlockAddress[2] = ((PFOUR_BYTE)&logicalBlockAddress)->Byte1; - cdb.SEEK.LogicalBlockAddress[3] = ((PFOUR_BYTE)&logicalBlockAddress)->Byte0; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - *DataLength = 0; - } - - // nothing to do after the command finishes. - - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleStopAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ) -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.START_STOP.OperationCode = SCSIOP_START_STOP_UNIT; - cdb.START_STOP.Immediate = 1; - cdb.START_STOP.Start = 0; - cdb.START_STOP.LoadEject = 0; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 6); - - if (NT_SUCCESS(status)) - { - PLAY_ACTIVE(DeviceExtension) = FALSE; - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleGetSetVolume( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_GET_VOLUME - IOCTL_CDROM_SET_VOLUME - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - ULONG transferSize = MODE_DATA_SIZE; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.MODE_SENSE10.OperationCode = SCSIOP_MODE_SENSE10; - cdb.MODE_SENSE10.PageCode = CDROM_AUDIO_CONTROL_PAGE; - cdb.MODE_SENSE10.AllocationLength[0] = (UCHAR)(MODE_DATA_SIZE >> 8); - cdb.MODE_SENSE10.AllocationLength[1] = (UCHAR)(MODE_DATA_SIZE & 0xFF); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, TRUE, &cdb, 10); - - if (NT_SUCCESS(status)) - { - if (RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_GET_VOLUME) - { - PAUDIO_OUTPUT audioOutput; - PVOLUME_CONTROL volumeControl; - ULONG bytesTransferred; - - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - (PVOID*)&volumeControl, - NULL); - if (NT_SUCCESS(status)) - { - audioOutput = ModeSenseFindSpecificPage((PCHAR)DeviceExtension->ScratchContext.ScratchSrb->DataBuffer, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength, - CDROM_AUDIO_CONTROL_PAGE, - FALSE); - - // Verify the page is as big as expected. - bytesTransferred = (ULONG)((PCHAR)audioOutput - (PCHAR)DeviceExtension->ScratchContext.ScratchSrb->DataBuffer) + - sizeof(AUDIO_OUTPUT); - - if ((audioOutput != NULL) && - (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength >= bytesTransferred)) - { - ULONG i; - for (i=0; i<4; i++) - { - volumeControl->PortVolume[i] = audioOutput->PortOutput[i].Volume; - } - - // Set bytes transferred in IRP. - *DataLength = sizeof(VOLUME_CONTROL); - - } - else - { - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - } - else //IOCTL_CDROM_SET_VOLUME - { - PAUDIO_OUTPUT audioInput = NULL; - PAUDIO_OUTPUT audioOutput = NULL; - PVOLUME_CONTROL volumeControl = NULL; - ULONG i,bytesTransferred,headerLength; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&volumeControl, - NULL); - - if (NT_SUCCESS(status)) - { - audioInput = ModeSenseFindSpecificPage((PCHAR)DeviceExtension->ScratchContext.ScratchSrb->DataBuffer, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength, - CDROM_AUDIO_CONTROL_PAGE, - FALSE); - - // Check to make sure the mode sense data is valid before we go on - if(audioInput == NULL) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "Mode Sense Page %d not found\n", - CDROM_AUDIO_CONTROL_PAGE)); - - *DataLength = 0; - status = STATUS_INVALID_DEVICE_REQUEST; - } - } - - if (NT_SUCCESS(status)) - { - // keep items clean; clear the command history - ScratchBuffer_ResetItems(DeviceExtension, TRUE); - - headerLength = sizeof(MODE_PARAMETER_HEADER10); - bytesTransferred = sizeof(AUDIO_OUTPUT) + headerLength; - - // use the scratch buffer as input buffer. - // the content of this buffer will not be changed in the following loop. - audioOutput = (PAUDIO_OUTPUT)((PCHAR)DeviceExtension->ScratchContext.ScratchBuffer + headerLength); - - for (i=0; i<4; i++) - { - audioOutput->PortOutput[i].Volume = volumeControl->PortVolume[i]; - audioOutput->PortOutput[i].ChannelSelection = audioInput->PortOutput[i].ChannelSelection; - } - - audioOutput->CodePage = CDROM_AUDIO_CONTROL_PAGE; - audioOutput->ParameterLength = sizeof(AUDIO_OUTPUT) - 2; - audioOutput->Immediate = MODE_SELECT_IMMEDIATE; - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.MODE_SELECT10.OperationCode = SCSIOP_MODE_SELECT10; - cdb.MODE_SELECT10.ParameterListLength[0] = (UCHAR) (bytesTransferred >> 8); - cdb.MODE_SELECT10.ParameterListLength[1] = (UCHAR) (bytesTransferred & 0xFF); - cdb.MODE_SELECT10.PFBit = 1; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, bytesTransferred, FALSE, &cdb, 10); - - } - *DataLength = 0; - } - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadDvdStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DVD_READ_STRUCTURE - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PVOID inputBuffer = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = ReadDvdStructure(DeviceExtension, - Request, - inputBuffer, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - outputBuffer, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DataLength); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ReadDvdStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - base function to handle request of IOCTL_DVD_START_SESSION - IOCTL_DVD_READ_KEY - -Arguments: - - DeviceExtension - device context - OriginalRequest - original request to be handled - InputBuffer - input buffer - InputBufferLength - length of input buffer - OutputBuffer - output buffer - OutputBufferLength - length of output buffer - -Return Value: - - NTSTATUS - DataLength - returned data length - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_READ_STRUCTURE request = (PDVD_READ_STRUCTURE)InputBuffer; - PDVD_DESCRIPTOR_HEADER header = (PDVD_DESCRIPTOR_HEADER)OutputBuffer; - CDB cdb; - - USHORT dataLength; - ULONG blockNumber; - PFOUR_BYTE fourByte; - - PAGED_CODE (); - - UNREFERENCED_PARAMETER(InputBufferLength); - - if (DeviceExtension->DeviceAdditionalData.DriveDeviceType != FILE_DEVICE_DVD) - { - *DataLength = 0; - return STATUS_INVALID_DEVICE_REQUEST; - } - - dataLength = (USHORT)OutputBufferLength; - blockNumber = (ULONG)(request->BlockByteOffset.QuadPart >> DeviceExtension->SectorShift); - fourByte = (PFOUR_BYTE)&blockNumber; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE; - cdb.READ_DVD_STRUCTURE.RMDBlockNumber[0] = fourByte->Byte3; - cdb.READ_DVD_STRUCTURE.RMDBlockNumber[1] = fourByte->Byte2; - cdb.READ_DVD_STRUCTURE.RMDBlockNumber[2] = fourByte->Byte1; - cdb.READ_DVD_STRUCTURE.RMDBlockNumber[3] = fourByte->Byte0; - cdb.READ_DVD_STRUCTURE.LayerNumber = request->LayerNumber; - cdb.READ_DVD_STRUCTURE.Format = (UCHAR)request->Format; - -#if DBG - { - if ((UCHAR)request->Format > DvdMaxDescriptor) - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "READ_DVD_STRUCTURE format %x = %s (%x bytes)\n", - (UCHAR)request->Format, - READ_DVD_STRUCTURE_FORMAT_STRINGS[DvdMaxDescriptor], - dataLength - )); - } - else - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, - "READ_DVD_STRUCTURE format %x = %s (%x bytes)\n", - (UCHAR)request->Format, - READ_DVD_STRUCTURE_FORMAT_STRINGS[(UCHAR)request->Format], - dataLength - )); - } - } -#endif // DBG - - if (request->Format == DvdDiskKeyDescriptor) - { - cdb.READ_DVD_STRUCTURE.AGID = (UCHAR)request->SessionId; - } - - cdb.READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(dataLength >> 8); - cdb.READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(dataLength & 0xff); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, OriginalRequest, dataLength, TRUE, &cdb, 12); - - if (NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DvdDCCompletion - READ_STRUCTURE: descriptor format of %d\n", request->Format)); - - RtlMoveMemory(header, - DeviceExtension->ScratchContext.ScratchSrb->DataBuffer, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength); - - // Cook the data. There are a number of fields that really - // should be byte-swapped for the caller. - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DvdDCCompletion - READ_STRUCTURE:\n" - "\tHeader at %p\n" - "\tDvdDCCompletion - READ_STRUCTURE: data at %p\n" - "\tDataBuffer was at %p\n" - "\tDataTransferLength was %lx\n", - header, - header->Data, - DeviceExtension->ScratchContext.ScratchSrb->DataBuffer, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength)); - - // First the fields in the header - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "READ_STRUCTURE: header->Length %lx -> ", - header->Length)); - - REVERSE_SHORT(&header->Length); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "%lx\n", header->Length)); - - // Now the fields in the descriptor - if(request->Format == DvdPhysicalDescriptor) - { - ULONG tempLength = (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength > (ULONG)FIELD_OFFSET(DVD_DESCRIPTOR_HEADER, Data)) - ? (DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength - FIELD_OFFSET(DVD_DESCRIPTOR_HEADER, Data)) - : 0; - - PDVD_LAYER_DESCRIPTOR layer = (PDVD_LAYER_DESCRIPTOR)&(header->Data[0]); - - // Make sure the buffer size is good for swapping bytes. - if (tempLength >= RTL_SIZEOF_THROUGH_FIELD(DVD_LAYER_DESCRIPTOR, StartingDataSector)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "READ_STRUCTURE: StartingDataSector %lx -> ", - layer->StartingDataSector)); - REVERSE_LONG(&(layer->StartingDataSector)); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "%lx\n", layer->StartingDataSector)); - } - if (tempLength >= RTL_SIZEOF_THROUGH_FIELD(DVD_LAYER_DESCRIPTOR, EndDataSector)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "READ_STRUCTURE: EndDataSector %lx -> ", - layer->EndDataSector)); - REVERSE_LONG(&(layer->EndDataSector)); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "%lx\n", layer->EndDataSector)); - } - if (tempLength >= RTL_SIZEOF_THROUGH_FIELD(DVD_LAYER_DESCRIPTOR, EndLayerZeroSector)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "READ_STRUCTURE: EndLayerZeroSector %lx -> ", - layer->EndLayerZeroSector)); - REVERSE_LONG(&(layer->EndLayerZeroSector)); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "%lx\n", layer->EndLayerZeroSector)); - } - } - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "Status is %lx\n", status)); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "DvdDeviceControlCompletion - " - "IOCTL_DVD_READ_STRUCTURE: data transfer length of %d\n", - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength)); - } - - *DataLength = DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - } - - ScratchBuffer_EndUse(DeviceExtension); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DVD_END_SESSION - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_SESSION_ID sessionId = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&sessionId, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - DVD_SESSION_ID currentSession = 0; - DVD_SESSION_ID limitSession = 0; - - if(*sessionId == DVD_END_ALL_SESSIONS) - { - currentSession = 0; - limitSession = MAX_COPY_PROTECT_AGID - 1; - } - else - { - currentSession = *sessionId; - limitSession = *sessionId; - } - - ScratchBuffer_BeginUse(DeviceExtension); - - do - { - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SEND_KEY.OperationCode = SCSIOP_SEND_KEY; - cdb.SEND_KEY.AGID = (UCHAR)(currentSession); - cdb.SEND_KEY.KeyFormat = DVD_INVALIDATE_AGID; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 12); - - currentSession++; - } while ((currentSession <= limitSession) && NT_SUCCESS(status)); - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdStartSessionReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DVD_START_SESSION - IOCTL_DVD_READ_KEY - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_COPY_PROTECT_KEY keyParameters = NULL; - PVOID outputBuffer = NULL; - - PAGED_CODE (); - - if (NT_SUCCESS(status)) - { - status = WdfRequestRetrieveOutputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - &outputBuffer, - NULL); - } - - if (NT_SUCCESS(status) && RequestParameters.Parameters.DeviceIoControl.IoControlCode == IOCTL_DVD_READ_KEY) - { - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&keyParameters, - NULL); - } - - if (NT_SUCCESS(status)) - { - status = DvdStartSessionReadKey(DeviceExtension, - RequestParameters.Parameters.DeviceIoControl.IoControlCode, - Request, - keyParameters, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - outputBuffer, - RequestParameters.Parameters.DeviceIoControl.OutputBufferLength, - DataLength); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DvdStartSessionReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_opt_ WDFREQUEST OriginalRequest, - _In_opt_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _In_ PVOID OutputBuffer, - _In_ size_t OutputBufferLength, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - base function to handle request of IOCTL_DVD_START_SESSION - IOCTL_DVD_READ_KEY - -Arguments: - - DeviceExtension - device context - IoControlCode - IOCTL_DVD_READ_KEY or IOCTL_DVD_START_SESSION - OriginalRequest - original request to be handled - InputBuffer - input buffer - InputBufferLength - length of input buffer - OutputBuffer - output buffer - OutputBufferLength - length of output buffer - -Return Value: - - NTSTATUS - DataLength - returned data length - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG keyLength = 0; - ULONG result = 0; - ULONG allocationLength; - PFOUR_BYTE fourByte; - PDVD_COPY_PROTECT_KEY keyParameters = (PDVD_COPY_PROTECT_KEY)InputBuffer; - - PAGED_CODE (); - - UNREFERENCED_PARAMETER(InputBufferLength); - - *DataLength = 0; - - fourByte = (PFOUR_BYTE)&allocationLength; - - if (IoControlCode == IOCTL_DVD_READ_KEY) - { - if (keyParameters == NULL) - { - status = STATUS_INTERNAL_ERROR; - } - - // First of all, initialize the DVD region of the drive, if it has not been set yet - if (NT_SUCCESS(status) && - (keyParameters->KeyType == DvdGetRpcKey) && - DeviceExtension->DeviceAdditionalData.Mmc.IsCssDvd) - { - DevicePickDvdRegion(DeviceExtension->Device); - } - - if (NT_SUCCESS(status) && - (keyParameters->KeyType == DvdDiskKey)) - { - // Special case - need to use READ DVD STRUCTURE command to get the disk key. - PDVD_COPY_PROTECT_KEY keyHeader = NULL; - PDVD_READ_STRUCTURE readStructureRequest = (PDVD_READ_STRUCTURE)keyParameters; - - // save the key header so we can restore the interesting parts later - keyHeader = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(DVD_COPY_PROTECT_KEY), - DVD_TAG_READ_KEY); - - if(keyHeader == NULL) - { - // Can't save the context so return an error - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DvdDeviceControl - READ_KEY: unable to allocate context\n")); - status = STATUS_INSUFFICIENT_RESOURCES; - } - - if (NT_SUCCESS(status)) - { - PREAD_DVD_STRUCTURES_HEADER rawKey = OutputBuffer; - PDVD_COPY_PROTECT_KEY outputKey = OutputBuffer; - - // save input parameters - RtlCopyMemory(keyHeader, - InputBuffer, - sizeof(DVD_COPY_PROTECT_KEY)); - - readStructureRequest->Format = DvdDiskKeyDescriptor; - readStructureRequest->BlockByteOffset.QuadPart = 0; - readStructureRequest->LayerNumber = 0; - readStructureRequest->SessionId = keyHeader->SessionId; - - status = ReadDvdStructure(DeviceExtension, - OriginalRequest, - InputBuffer, - sizeof(DVD_READ_STRUCTURE), - OutputBuffer, - sizeof(READ_DVD_STRUCTURES_HEADER) + sizeof(DVD_DISK_KEY_DESCRIPTOR), - DataLength); - - // fill the output buffer, it's not touched in DeviceHandleReadDvdStructure() - // for this specific request type: DvdDiskKeyDescriptor - if (NT_SUCCESS(status)) - { - // Shift the data down to its new position. - RtlMoveMemory(outputKey->KeyData, - rawKey->Data, - sizeof(DVD_DISK_KEY_DESCRIPTOR)); - - RtlCopyMemory(outputKey, - keyHeader, - sizeof(DVD_COPY_PROTECT_KEY)); - - outputKey->KeyLength = DVD_DISK_KEY_LENGTH; - - *DataLength = DVD_DISK_KEY_LENGTH; - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, - "StartSessionReadKey Failed with status %x, %xI64 (%x) bytes\n", - status, - (unsigned int)*DataLength, - ((rawKey->Length[0] << 16) | rawKey->Length[1]) )); - } - - FREE_POOL(keyHeader); - } - - // special process finished. return from here. - return status; - } - - if (NT_SUCCESS(status)) - { - status = RtlULongSub((ULONG)OutputBufferLength, - (ULONG)sizeof(DVD_COPY_PROTECT_KEY), &result); - } - - if (NT_SUCCESS(status)) - { - status = RtlULongAdd(result, sizeof(CDVD_KEY_HEADER), &keyLength); - } - - if (NT_SUCCESS(status)) - { - //The data length field of REPORT KEY Command occupies two bytes - keyLength = min(keyLength, MAXUSHORT); - } - } - else //IOCTL_DVD_START_SESSION - { - keyParameters = NULL; - keyLength = sizeof(CDVD_KEY_HEADER) + sizeof(CDVD_REPORT_AGID_DATA); - status = STATUS_SUCCESS; - } - - if (NT_SUCCESS(status)) - { - CDB cdb; - - allocationLength = keyLength; - - // Defensive coding. Prefix cannot recognize this usage. - UNREFERENCED_PARAMETER(allocationLength); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY; - cdb.REPORT_KEY.AllocationLength[0] = fourByte->Byte1; - cdb.REPORT_KEY.AllocationLength[1] = fourByte->Byte0; - - // set the specific parameters.... - if(IoControlCode == IOCTL_DVD_READ_KEY) - { - if(keyParameters->KeyType == DvdTitleKey) - { - ULONG logicalBlockAddress; - - logicalBlockAddress = (ULONG)(keyParameters->Parameters.TitleOffset.QuadPart >> - DeviceExtension->SectorShift); - - fourByte = (PFOUR_BYTE)&(logicalBlockAddress); - - cdb.REPORT_KEY.LogicalBlockAddress[0] = fourByte->Byte3; - cdb.REPORT_KEY.LogicalBlockAddress[1] = fourByte->Byte2; - cdb.REPORT_KEY.LogicalBlockAddress[2] = fourByte->Byte1; - cdb.REPORT_KEY.LogicalBlockAddress[3] = fourByte->Byte0; - } - - cdb.REPORT_KEY.KeyFormat = (UCHAR)keyParameters->KeyType; - cdb.REPORT_KEY.AGID = (UCHAR)keyParameters->SessionId; - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DvdStartSessionReadKey => sending irp %p (%s)\n", - OriginalRequest, "READ_KEY")); - } - else - { - cdb.REPORT_KEY.KeyFormat = DVD_REPORT_AGID; - cdb.REPORT_KEY.AGID = 0; - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DvdStartSessionReadKey => sending irp %p (%s)\n", - OriginalRequest, "START_SESSION")); - } - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, OriginalRequest, keyLength, TRUE, &cdb, 12); - - if (NT_SUCCESS(status)) - { - if(IoControlCode == IOCTL_DVD_READ_KEY) - { - NTSTATUS tempStatus; - PDVD_COPY_PROTECT_KEY copyProtectKey = (PDVD_COPY_PROTECT_KEY)OutputBuffer; - PCDVD_KEY_HEADER keyHeader = DeviceExtension->ScratchContext.ScratchSrb->DataBuffer; - ULONG dataLength; - ULONG transferLength; - - tempStatus = RtlULongSub(DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength, - FIELD_OFFSET(CDVD_KEY_HEADER, Data), - &transferLength); - - dataLength = (keyHeader->DataLength[0] << 8) + keyHeader->DataLength[1]; - - if (NT_SUCCESS(tempStatus) && (dataLength >= 2)) - { - // Adjust the data length to ignore the two reserved bytes in the - // header. - dataLength -= 2; - - // take the minimum of the transferred length and the - // length as specified in the header. - if(dataLength < transferLength) - { - transferLength = dataLength; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DvdDeviceControlCompletion: [%p] - READ_KEY with " - "transfer length of (%d or %d) bytes\n", - OriginalRequest, - dataLength, - DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength - 2)); - - // Copy the key data into the return buffer - if(copyProtectKey->KeyType == DvdTitleKey) - { - RtlMoveMemory(copyProtectKey->KeyData, - keyHeader->Data + 1, - transferLength - 1); - - copyProtectKey->KeyData[transferLength - 1] = 0; - - // If this is a title key then we need to copy the CGMS flags - // as well. - copyProtectKey->KeyFlags = *(keyHeader->Data); - - } - else - { - RtlMoveMemory(copyProtectKey->KeyData, - keyHeader->Data, - transferLength); - } - - copyProtectKey->KeyLength = sizeof(DVD_COPY_PROTECT_KEY); - copyProtectKey->KeyLength += transferLength; - - *DataLength = copyProtectKey->KeyLength; - } - else - { - //There is no valid data from drive. - //This may happen when Key Format = 0x3f that does not require data back from drive. - status = STATUS_SUCCESS; - *DataLength = 0; - } - } - else - { - PDVD_SESSION_ID sessionId = (PDVD_SESSION_ID)OutputBuffer; - PCDVD_KEY_HEADER keyHeader = DeviceExtension->ScratchContext.ScratchSrb->DataBuffer; - PCDVD_REPORT_AGID_DATA keyData = (PCDVD_REPORT_AGID_DATA)keyHeader->Data; - - *sessionId = keyData->AGID; - - *DataLength = sizeof(DVD_SESSION_ID); - } - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_DVD_SEND_KEY - IOCTL_DVD_SEND_KEY2 - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PVOID inputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - &inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - status = DvdSendKey(DeviceExtension, - Request, - inputBuffer, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - DataLength); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ PVOID InputBuffer, - _In_ size_t InputBufferLength, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - base function to handle request of IOCTL_DVD_SEND_KEY(2) - NOTE: cdrom does not process this IOCTL if the input buffer length is bigger than Port transfer length. - -Arguments: - - DeviceExtension - device context - OriginalRequest - original request to be handled - InputBuffer - input buffer - InputBufferLength - length of input buffer - -Return Value: - - NTSTATUS - DataLength - returned data length - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PDVD_COPY_PROTECT_KEY key = (PDVD_COPY_PROTECT_KEY)InputBuffer; - - ULONG keyLength = 0; - ULONG result = 0; - PFOUR_BYTE fourByte; - - PAGED_CODE (); - - UNREFERENCED_PARAMETER(InputBufferLength); - - *DataLength = 0; - - if (NT_SUCCESS(status)) - { - if ((key->KeyLength < sizeof(DVD_COPY_PROTECT_KEY)) || - ((key->KeyLength - sizeof(DVD_COPY_PROTECT_KEY)) > DeviceExtension->ScratchContext.ScratchBufferSize)) - { - NT_ASSERT(FALSE); - status = STATUS_INTERNAL_ERROR; - } - } - - if (NT_SUCCESS(status)) - { - status = RtlULongSub(key->KeyLength, sizeof(DVD_COPY_PROTECT_KEY), &result); - } - - if (NT_SUCCESS(status)) - { - status = RtlULongAdd(result, sizeof(CDVD_KEY_HEADER), &keyLength); - } - - if (NT_SUCCESS(status)) - { - keyLength = min(keyLength, DeviceExtension->ScratchContext.ScratchBufferSize); - - if (keyLength < 2) - { - status = STATUS_INVALID_PARAMETER; - } - } - - if (NT_SUCCESS(status)) - { - PCDVD_KEY_HEADER keyBuffer = NULL; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - // prepare the input buffer - keyBuffer = (PCDVD_KEY_HEADER)DeviceExtension->ScratchContext.ScratchBuffer; - - // keylength is decremented here by two because the - // datalength does not include the header, which is two - // bytes. keylength is immediately incremented later - // by the same amount. - keyLength -= 2; - fourByte = (PFOUR_BYTE)&keyLength; - keyBuffer->DataLength[0] = fourByte->Byte1; - keyBuffer->DataLength[1] = fourByte->Byte0; - keyLength += 2; - - RtlMoveMemory(keyBuffer->Data, - key->KeyData, - key->KeyLength - sizeof(DVD_COPY_PROTECT_KEY)); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.REPORT_KEY.OperationCode = SCSIOP_SEND_KEY; - - cdb.SEND_KEY.ParameterListLength[0] = fourByte->Byte1; - cdb.SEND_KEY.ParameterListLength[1] = fourByte->Byte0; - cdb.SEND_KEY.KeyFormat = (UCHAR)key->KeyType; - cdb.SEND_KEY.AGID = (UCHAR)key->SessionId; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, OriginalRequest, keyLength, FALSE, &cdb, 12); - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSetReadAhead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_STORAGE_SET_READ_AHEAD - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSTORAGE_SET_READ_AHEAD readAhead = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&readAhead, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - ULONG blockAddress; - PFOUR_BYTE fourByte = (PFOUR_BYTE)&blockAddress; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SET_READ_AHEAD.OperationCode = SCSIOP_SET_READ_AHEAD; - - blockAddress = (ULONG)(readAhead->TriggerAddress.QuadPart >> - DeviceExtension->SectorShift); - - // Defensive coding. Prefix cannot recognize this usage. - UNREFERENCED_PARAMETER(blockAddress); - - cdb.SET_READ_AHEAD.TriggerLBA[0] = fourByte->Byte3; - cdb.SET_READ_AHEAD.TriggerLBA[1] = fourByte->Byte2; - cdb.SET_READ_AHEAD.TriggerLBA[2] = fourByte->Byte1; - cdb.SET_READ_AHEAD.TriggerLBA[3] = fourByte->Byte0; - - blockAddress = (ULONG)(readAhead->TargetAddress.QuadPart >> - DeviceExtension->SectorShift); - - cdb.SET_READ_AHEAD.ReadAheadLBA[0] = fourByte->Byte3; - cdb.SET_READ_AHEAD.ReadAheadLBA[1] = fourByte->Byte2; - cdb.SET_READ_AHEAD.ReadAheadLBA[2] = fourByte->Byte1; - cdb.SET_READ_AHEAD.ReadAheadLBA[3] = fourByte->Byte0; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 12); - - if (NT_SUCCESS(status)) - { - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSetSpeed( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ) -/*++ - -Routine Description: - - Handle request of IOCTL_CDROM_SET_SPEED - -Arguments: - - DeviceExtension - device context - Request - request to be handled - RequestParameters - request parameter - DataLength - transferred data length - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DATA cdData = &(DeviceExtension->DeviceAdditionalData); - PCDROM_SET_SPEED inputBuffer = NULL; - - PAGED_CODE (); - - *DataLength = 0; - - status = WdfRequestRetrieveInputBuffer(Request, - RequestParameters.Parameters.DeviceIoControl.InputBufferLength, - (PVOID*)&inputBuffer, - NULL); - - if (NT_SUCCESS(status)) - { - ULONG transferSize = 0; - CDB cdb; - CDROM_SPEED_REQUEST requestType = inputBuffer->RequestType; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - if (requestType == CdromSetSpeed) - { - PCDROM_SET_SPEED speed = inputBuffer; - - cdb.SET_CD_SPEED.OperationCode = SCSIOP_SET_CD_SPEED; - cdb.SET_CD_SPEED.RotationControl = speed->RotationControl; - REVERSE_BYTES_SHORT(&cdb.SET_CD_SPEED.ReadSpeed, &speed->ReadSpeed); - REVERSE_BYTES_SHORT(&cdb.SET_CD_SPEED.WriteSpeed, &speed->WriteSpeed); - } - else - { - PCDROM_SET_STREAMING stream = (PCDROM_SET_STREAMING)inputBuffer; - PPERFORMANCE_DESCRIPTOR perfDescriptor; - - transferSize = sizeof(PERFORMANCE_DESCRIPTOR); - - perfDescriptor = DeviceExtension->ScratchContext.ScratchBuffer; - RtlZeroMemory(perfDescriptor, transferSize); - - perfDescriptor->RandomAccess = stream->RandomAccess; - perfDescriptor->Exact = stream->SetExact; - perfDescriptor->RestoreDefaults = stream->RestoreDefaults; - perfDescriptor->WriteRotationControl = stream->RotationControl; - - REVERSE_BYTES(&perfDescriptor->StartLba, &stream->StartLba); - REVERSE_BYTES(&perfDescriptor->EndLba, &stream->EndLba); - REVERSE_BYTES(&perfDescriptor->ReadSize, &stream->ReadSize); - REVERSE_BYTES(&perfDescriptor->ReadTime, &stream->ReadTime); - REVERSE_BYTES(&perfDescriptor->WriteSize, &stream->WriteSize); - REVERSE_BYTES(&perfDescriptor->WriteTime, &stream->WriteTime); - - cdb.SET_STREAMING.OperationCode = SCSIOP_SET_STREAMING; - REVERSE_BYTES_SHORT(&cdb.SET_STREAMING.ParameterListLength, &transferSize); - - // set value in extension by user inputs. - cdData->RestoreDefaults = stream->Persistent ? FALSE : TRUE; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "DeviceHandleSetSpeed: Restore default speed on media change set to %s\n", - cdData->RestoreDefaults ? "true" : "false")); - } - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, Request, transferSize, FALSE, &cdb, 12); - - if (NT_SUCCESS(status)) - { - *DataLength = 0; - } - - // nothing to do after the command finishes. - ScratchBuffer_EndUse(DeviceExtension); - } - - return status; -} - - diff --git a/storage/class/cdrom/src/ioctl.h b/storage/class/cdrom/src/ioctl.h deleted file mode 100644 index 951561a9c..000000000 --- a/storage/class/cdrom/src/ioctl.h +++ /dev/null @@ -1,847 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - ioctl.h - -Abstract: - - Functions to handle IOCTLs. - -Author: - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#ifndef __IOCTL_H__ -#define __IOCTL_H__ - -BOOLEAN -RequestDispatchProcessDirectly( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -BOOLEAN -RequestDispatchToSequentialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -BOOLEAN -RequestDispatchSyncWithSequentialQueue( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -BOOLEAN -RequestDispatchSpecialIoctls( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -BOOLEAN -RequestDispatchUnknownRequests( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -// -// I/O Request Handlers -// - -// Handlers that are called directly in dispatch routine. - -NTSTATUS -RequestHandleGetInquiryData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleGetMediaTypeEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleMountQueryUniqueId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleMountQueryDeviceName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleMountQuerySuggestedLinkName( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleGetDeviceNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleGetHotPlugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleSetHotPlugInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleEventNotification( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST Request, - _In_opt_ PWDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -// Handlers that are called in RequestProcessSerializedIoctl in a work item. - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetDvdRegion( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestHandleQueryPropertyRetrieveCachedData( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleReadTOC( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleReadTocEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetConfiguration( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleGetDriveGeometry( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleDiskVerify( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleCheckVerify( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleFakePartitionInfo( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleEjectionControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleLoadEjectMedia( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleMcnControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandleReserveRelease( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -RequestHandlePersistentReserve( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -#if (NTDDI_VERSION >= NTDDI_WIN8) -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleAreVolumesReady( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleVolumeOnline( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); -#endif - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceHandleRawRead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandlePlayAudioMsf( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadQChannel( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandlePauseAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleResumeAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSeekAudioMsf( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleStopAudio( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleGetSetVolume( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadDvdStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdStartSessionReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleDvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSetReadAhead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSetSpeed( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadMediaKeyBlock( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsSendCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGetCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGetChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleSendChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleReadVolumeId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadSerialNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadMediaId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsReadBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -DeviceHandleAacsGenerateBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleEnableStreaming( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleSendOpcInformation( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleGetPerformance( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleMcnSyncFakeIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ size_t * DataLength - ); - -// Handlers that will be called by Sync process. - -// RequestHandleUnknownIoctl could be called at DISPATCH_LEVEL. -NTSTATUS -RequestHandleUnknownIoctl( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessQueryLockState( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessLockDevice( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleExclusiveAccessUnlockDevice( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -NTSTATUS -RequestHandleQueryPropertyDeviceUniqueId( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -NTSTATUS -RequestHandleQueryPropertyWriteCache( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -RequestHandleScsiPassThrough( - _In_ WDFDEVICE Device, - _In_ WDFREQUEST Request - ); - -// Read/write handler called possibly at DISPATCH_LEVEL. - -NTSTATUS -RequestHandleReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -// -// I/O Request Validation helpers -// - -NTSTATUS -RequestValidateRawRead( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateReadTocEx( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateReadToc( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateGetLastSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateReadQChannel( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateDvdReadStructure( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateDvdStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateDvdSendKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateDvdReadKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateGetConfiguration( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateSetSpeed( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsReadMediaKeyBlock( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsStartSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsSendCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsGetCertificate( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsGetChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsSendChallengeKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsReadVolumeId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsReadSerialNumber( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsReadMediaId( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsBindingNonce( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateExclusiveAccess( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateEnableStreaming( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateSendOpcInformation( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateGetPerformance( - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -BOOLEAN -RequestIsRealtimeStreaming( - _In_ WDFREQUEST Request, - _In_ BOOLEAN IsReadRequest - ); - -NTSTATUS -RequestValidateReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters - ); - -NTSTATUS -RequestValidatePersistentReserve( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateDvdEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - -NTSTATUS -RequestValidateAacsEndSession( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ WDF_REQUEST_PARAMETERS RequestParameters, - _Out_ size_t * DataLength - ); - - -// -// completion routines -// - - - - -#endif // __IOCTL_H__ diff --git a/storage/class/cdrom/src/localwpp.ini b/storage/class/cdrom/src/localwpp.ini deleted file mode 100644 index 0e793609d..000000000 --- a/storage/class/cdrom/src/localwpp.ini +++ /dev/null @@ -1,17 +0,0 @@ - -// this defines how to log a len/buffer pair. -// This function should be in trace.h -DEFINE_CPLX_TYPE(HEXDUMP, WPP_LOGHEXDUMP, xstr_t, ItemHEXDump,"s", _HEX_, 0,2); - -// DEFINE_CPLX_TYPE( -// name, // i.e. HEXDUMP // %!HEXDUMP! -// macro, // i.e. WPP_LOGHEXDUMP // Marshalling macro, defined in trace.h -// structure, // i.e. xstr_t // Argument type (structure to be created by above macro) -// item type, // i.e. ItemHEXDump // MOF type that TracePrt can understand -// format specifier, // i.e. "s" // a format specifier that TracePrt can understand -// ???? // i.e. _HEX_ // Type signature (becomes a part of function name) -// ???? // i.e. 0 // Weight (0 is variable data length) -// ???? // i.e. 2 // Slots used by this entry (optional, 1 default) -// ) - - diff --git a/storage/class/cdrom/src/mmc.c b/storage/class/cdrom/src/mmc.c deleted file mode 100644 index 5f96726c6..000000000 --- a/storage/class/cdrom/src/mmc.c +++ /dev/null @@ -1,1629 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - mmc.c - -Abstract: - - Include all funtions relate to MMC - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "mmc.h" -#include "scratch.h" - -#ifdef DEBUG_USE_WPP -#include "mmc.tmh" -#endif - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceDeallocateMmcResources) -#pragma alloc_text(PAGE, DeviceAllocateMmcResources) -#pragma alloc_text(PAGE, DeviceUpdateMmcCapabilities) -#pragma alloc_text(PAGE, DeviceGetConfigurationWithAlloc) -#pragma alloc_text(PAGE, DeviceGetConfiguration) -#pragma alloc_text(PAGE, DeviceUpdateMmcWriteCapability) -#pragma alloc_text(PAGE, MmcDataFindFeaturePage) -#pragma alloc_text(PAGE, MmcDataFindProfileInProfiles) -#pragma alloc_text(PAGE, DeviceRetryTimeGuessBasedOnProfile) -#pragma alloc_text(PAGE, DeviceRetryTimeDetectionBasedOnModePage2A) -#pragma alloc_text(PAGE, DeviceRetryTimeDetectionBasedOnGetPerformance) - -#endif - -#pragma warning(push) -#pragma warning(disable:4214) // nonstandard extension used : bit field types other than int - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceDeallocateMmcResources( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - release MMC resources - -Arguments: - - Device - device object - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cddata = &(deviceExtension->DeviceAdditionalData); - PCDROM_MMC_EXTENSION mmcData = &cddata->Mmc; - - PAGED_CODE(); - - if (mmcData->CapabilitiesIrp) - { - IoFreeIrp(mmcData->CapabilitiesIrp); - mmcData->CapabilitiesIrp = NULL; - } - if (mmcData->CapabilitiesMdl) - { - IoFreeMdl(mmcData->CapabilitiesMdl); - mmcData->CapabilitiesMdl = NULL; - } - if (mmcData->CapabilitiesBuffer) - { - ExFreePool(mmcData->CapabilitiesBuffer); - mmcData->CapabilitiesBuffer = NULL; - } - if (mmcData->CapabilitiesRequest) - { - WdfObjectDelete(mmcData->CapabilitiesRequest); - mmcData->CapabilitiesRequest = NULL; - } - mmcData->CapabilitiesBufferSize = 0; - mmcData->IsMmc = FALSE; - mmcData->WriteAllowed = FALSE; - - return; -} - - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceAllocateMmcResources( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - allocate all MMC resources needed - -Arguments: - - Device - device object - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cddata = &(deviceExtension->DeviceAdditionalData); - PCDROM_MMC_EXTENSION mmcData = &(cddata->Mmc); - WDF_OBJECT_ATTRIBUTES attributes = {0}; - - PAGED_CODE(); - - NT_ASSERT(mmcData->CapabilitiesBuffer == NULL); - NT_ASSERT(mmcData->CapabilitiesBufferSize == 0); - - // allocate the buffer and set the buffer size. - // retrieve drive configuration information. - status = DeviceGetConfigurationWithAlloc(Device, - &mmcData->CapabilitiesBuffer, - &mmcData->CapabilitiesBufferSize, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL); - if (!NT_SUCCESS(status)) - { - NT_ASSERT(mmcData->CapabilitiesBuffer == NULL); - NT_ASSERT(mmcData->CapabilitiesBufferSize == 0); - return status; - } - - NT_ASSERT(mmcData->CapabilitiesBuffer != NULL); - NT_ASSERT(mmcData->CapabilitiesBufferSize != 0); - - // Create an MDL over the new Buffer (allocated by DeviceGetConfiguration) - mmcData->CapabilitiesMdl = IoAllocateMdl(mmcData->CapabilitiesBuffer, - mmcData->CapabilitiesBufferSize, - FALSE, FALSE, NULL); - if (mmcData->CapabilitiesMdl == NULL) - { - ExFreePool(mmcData->CapabilitiesBuffer); - mmcData->CapabilitiesBuffer = NULL; - mmcData->CapabilitiesBufferSize = 0; - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Create an IRP from which we will create a WDFREQUEST - mmcData->CapabilitiesIrp = IoAllocateIrp(deviceExtension->DeviceObject->StackSize + 1, FALSE); - if (mmcData->CapabilitiesIrp == NULL) - { - IoFreeMdl(mmcData->CapabilitiesMdl); - mmcData->CapabilitiesMdl = NULL; - ExFreePool(mmcData->CapabilitiesBuffer); - mmcData->CapabilitiesBuffer = NULL; - mmcData->CapabilitiesBufferSize = 0; - return STATUS_INSUFFICIENT_RESOURCES; - } - - // create WDF request object - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - status = WdfRequestCreateFromIrp(&attributes, - mmcData->CapabilitiesIrp, - FALSE, - &mmcData->CapabilitiesRequest); - if (!NT_SUCCESS(status)) - { - return status; - } - - return STATUS_SUCCESS; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceUpdateMmcCapabilities( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - issue get congiguration command ans save result in device extension - -Arguments: - - Device - device object - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData); - PCDROM_MMC_EXTENSION mmcData = &(cdData->Mmc); - ULONG returnedBytes = 0; - LONG updateState; - - PAGED_CODE(); - - // first of all, check if we're still in the CdromMmcUpdateRequired state - // and, if yes, change it to CdromMmcUpdateStarted. - updateState = InterlockedCompareExchange((PLONG)&(cdData->Mmc.UpdateState), - CdromMmcUpdateStarted, - CdromMmcUpdateRequired); - if (updateState != CdromMmcUpdateRequired) { - // Mmc capabilities have been already updated or are in the process of - // being updated - just return STATUS_SUCCESS - return STATUS_SUCCESS; - } - - // default to read-only, no Streaming, non-blank - mmcData->WriteAllowed = FALSE; - mmcData->StreamingReadSupported = FALSE; - mmcData->StreamingWriteSupported = FALSE; - - // Issue command to update the drive capabilities. - // The failure of MMC update is not considered critical, - // so that we'll continue to process I/O even MMC update fails. - status = DeviceGetConfiguration(Device, - mmcData->CapabilitiesBuffer, - mmcData->CapabilitiesBufferSize, - &returnedBytes, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT); - - if (NT_SUCCESS(status) && // succeeded. - (mmcData->CapabilitiesBufferSize >= returnedBytes)) // not overflow. - { - // update whether or not writes are allowed - // this should be the *ONLY* place writes are set to allowed - { - BOOLEAN writeAllowed = FALSE; - FEATURE_NUMBER validationSchema = 0; - ULONG blockingFactor = 1; - - DeviceUpdateMmcWriteCapability(mmcData->CapabilitiesBuffer, - returnedBytes, - TRUE, - &writeAllowed, - &validationSchema, - &blockingFactor); - - mmcData->WriteAllowed = writeAllowed; - mmcData->ValidationSchema = validationSchema; - mmcData->Blocking = blockingFactor; - } - - // Check if Streaming reads/writes are supported and cache - // this information for later use. - { - PFEATURE_HEADER header; - ULONG minAdditionalLength; - - minAdditionalLength = FIELD_OFFSET(FEATURE_DATA_REAL_TIME_STREAMING, Reserved2) - - sizeof(FEATURE_HEADER); - - header = MmcDataFindFeaturePage(mmcData->CapabilitiesBuffer, - returnedBytes, - FeatureRealTimeStreaming); - - if ((header != NULL) && - (header->Current) && - (header->AdditionalLength >= minAdditionalLength)) - { - PFEATURE_DATA_REAL_TIME_STREAMING feature = (PFEATURE_DATA_REAL_TIME_STREAMING)header; - - // If Real-Time feature is current, then Streaming reads are supported for sure. - mmcData->StreamingReadSupported = TRUE; - - // Streaming writes are supported if an appropriate bit is set in the feature page. - mmcData->StreamingWriteSupported = (feature->StreamRecording == 1); - } - } - - // update the flag to reflect that if the media is CSS protected DVD or CPPM-protected DVDAudio - { - PFEATURE_HEADER header; - - header = DeviceFindFeaturePage(mmcData->CapabilitiesBuffer, - returnedBytes, - FeatureDvdCSS); - - mmcData->IsCssDvd = (header != NULL) && (header->Current); - } - - // Update the guesstimate for the drive's write speed - // Use the GetConfig profile first as a quick-guess based - // on media "type", then continue with media-specific - // queries for older media types, and use GET_PERFORMANCE - // for all unknown/future media types. - { - // pseudo-code: - // 1) Determine default based on profile (slowest for media) - // 2) Determine default based on MODE PAGE 2Ah - // 3) Determine default based on GET PERFORMANCE data - // 4) Choose fastest reported speed (-1 == none reported) - // 5) If all failed (returned -1), go with very safe (slow) default - // - // This ensures that the retries do not overload the drive's processor. - // Sending at highest possible speed for the media is OK, because the - // major downside is drive processor usage. (bus usage too, but most - // storage is becoming a point-to-point link.) - - FEATURE_PROFILE_TYPE const profile = - mmcData->CapabilitiesBuffer->CurrentProfile[0] << (8*1) | - mmcData->CapabilitiesBuffer->CurrentProfile[1] << (8*0) ; - LONGLONG t1 = (LONGLONG)-1; - LONGLONG t2 = (LONGLONG)-1; - LONGLONG t3 = (LONGLONG)-1; - LONGLONG t4 = (LONGLONG)-1; - LONGLONG final; - - t1 = DeviceRetryTimeGuessBasedOnProfile(profile); - t2 = DeviceRetryTimeDetectionBasedOnModePage2A(deviceExtension); - t3 = DeviceRetryTimeDetectionBasedOnGetPerformance(deviceExtension, TRUE); - t4 = DeviceRetryTimeDetectionBasedOnGetPerformance(deviceExtension, FALSE); - - // use the "fastest" value returned - final = MAXLONGLONG; - if (t4 != -1) - { - final = min(final, t4); - } - if (t3 != -1) - { - final = min(final, t3); - } - if (t2 != -1) - { - final = min(final, t2); - } - if (t1 != -1) - { - final = min(final, t1); - } - if (final == MAXLONGLONG) - { - // worst case -- use relatively slow default.... - final = WRITE_RETRY_DELAY_CD_4x; - } - - cdData->ReadWriteRetryDelay100nsUnits = final; - } - - } - else - { - // Rediscovery of MMC capabilities has failed - we'll need to retry - cdData->Mmc.UpdateState = CdromMmcUpdateRequired; - } - - // Change the state to CdromMmcUpdateComplete if it is CdromMmcUpdateStarted. - // If it is not, some error must have happened while this function was executed - // and the state is CdromMmcUpdateRequired now. In that case, we want to perform - // everything again, so we do not set CdromMmcUpdateComplete. - InterlockedCompareExchange((PLONG)&(cdData->Mmc.UpdateState), - CdromMmcUpdateComplete, - CdromMmcUpdateStarted); - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetConfigurationWithAlloc( - _In_ WDFDEVICE Device, - _Outptr_result_bytebuffer_all_(*BytesReturned) - PGET_CONFIGURATION_HEADER* Buffer, // this routine allocates this memory - _Out_ PULONG BytesReturned, - FEATURE_NUMBER const StartingFeature, - ULONG const RequestedType - ) -/*++ - -Routine Description: - - This function will allocates configuration buffer and set the size. - -Arguments: - - Device - device object - Buffer - to be allocated by this function - BytesReturned - size of the buffer - StartingFeature - the starting point of the feature list - RequestedType - - -Return Value: - - NTSTATUS - -NOTE: does not handle case where more than 65000 bytes are returned, - which requires multiple calls with different starting feature - numbers. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - GET_CONFIGURATION_HEADER header = {0}; // eight bytes, not a lot - PGET_CONFIGURATION_HEADER buffer = NULL; - ULONG returned = 0; - ULONG size = 0; - ULONG i = 0; - - PAGED_CODE(); - - *Buffer = NULL; - *BytesReturned = 0; - - // send the first request down to just get the header - status = DeviceGetConfiguration(Device, - &header, - sizeof(header), - &returned, - StartingFeature, - RequestedType); - - // now send command again, using information returned to allocate just enough memory - if (NT_SUCCESS(status)) - { - size = header.DataLength[0] << 24 | - header.DataLength[1] << 16 | - header.DataLength[2] << 8 | - header.DataLength[3] << 0 ; - - // the loop is in case that the retrieved data length is bigger than last time reported. - for (i = 0; (i < 4) && NT_SUCCESS(status); i++) - { - // the datalength field is the size *following* itself, so adjust accordingly - size += 4*sizeof(UCHAR); - - // make sure the size is reasonable - if (size <= sizeof(FEATURE_HEADER)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DeviceGetConfigurationWithAlloc: drive reports only %x bytes?\n", - size)); - status = STATUS_UNSUCCESSFUL; - } - - if (NT_SUCCESS(status)) - { - // allocate the memory - buffer = (PGET_CONFIGURATION_HEADER)ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - size, - CDROM_TAG_FEATURE); - - if (buffer == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - } - - if (NT_SUCCESS(status)) - { - // send the first request down to just get the header - status = DeviceGetConfiguration(Device, - buffer, - size, - &returned, - StartingFeature, - RequestedType); - - if (!NT_SUCCESS(status)) - { - ExFreePool(buffer); - } - else if (returned > size) - { - ExFreePool(buffer); - status = STATUS_INTERNAL_ERROR; - } - } - - // command succeeded. - if (NT_SUCCESS(status)) - { - returned = buffer->DataLength[0] << 24 | - buffer->DataLength[1] << 16 | - buffer->DataLength[2] << 8 | - buffer->DataLength[3] << 0 ; - returned += 4*sizeof(UCHAR); - - if (returned <= size) - { - *Buffer = buffer; - *BytesReturned = returned; // amount of 'safe' memory - // succes, get out of loop. - status = STATUS_SUCCESS; - break; - } - else - { - // the data size is bigger than the buffer size, retry using new size.... - size = returned; - ExFreePool(buffer); - buffer = NULL; - } - } - } // end of for() loop - } - - if (!NT_SUCCESS(status)) - { - // it failed after a number of attempts, so just fail. - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DeviceGetConfigurationWithAlloc: Failed %d attempts to get all feature " - "information\n", i)); - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetConfiguration( - _In_ WDFDEVICE Device, - _Out_writes_bytes_to_(BufferSize, *ValidBytes) - PGET_CONFIGURATION_HEADER Buffer, - _In_ ULONG const BufferSize, - _Out_ PULONG ValidBytes, - _In_ FEATURE_NUMBER const StartingFeature, - _In_ ULONG const RequestedType - ) -/*++ - -Routine Description: - - This function is used to get configuration data. - -Arguments: - - Device - device object - Buffer - buffer address to hold data. - BufferSize - size of the buffer - ValidBytes - valid data size in buffer - StartingFeature - the starting point of the feature list - RequestedType - - -Return Value: - - NTSTATUS - -NOTE: does not handle case where more than 64k bytes are returned, - which requires multiple calls with different starting feature - numbers. - ---*/ -{ - NTSTATUS status; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - SCSI_REQUEST_BLOCK srb; - PCDB cdb = (PCDB)srb.Cdb; - - PAGED_CODE(); - - NT_ASSERT(ValidBytes); - - // when system is low resources we can receive empty buffer - if (Buffer == NULL || BufferSize < sizeof(GET_CONFIGURATION_HEADER)) - { - return STATUS_BUFFER_TOO_SMALL; - } - - *ValidBytes = 0; - - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - RtlZeroMemory(Buffer, BufferSize); - - if (TEST_FLAG(deviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_GET_CONFIG_SUPPORT)) - { - return STATUS_INVALID_DEVICE_REQUEST; - } - -#pragma warning(push) -#pragma warning(disable: 6386) // OACR will complain buffer overrun: the writable size is 'BufferSize' bytes, but '65532' - // bytes might be written, which is impossible because BufferSize > 0xFFFC. - - if (BufferSize > 0xFFFC) - { - // cannot request more than 0xFFFC bytes in one request - // Eventually will "stitch" together multiple requests if needed - // Today, no drive has anywhere close to 4k..... - return DeviceGetConfiguration(Device, - Buffer, - 0xFFFC, - ValidBytes, - StartingFeature, - RequestedType); - } -#pragma warning(pop) - - //Start real work - srb.TimeOutValue = CDROM_GET_CONFIGURATION_TIMEOUT; - srb.CdbLength = 10; - - cdb->GET_CONFIGURATION.OperationCode = SCSIOP_GET_CONFIGURATION; - cdb->GET_CONFIGURATION.RequestType = (UCHAR)RequestedType; - cdb->GET_CONFIGURATION.StartingFeature[0] = (UCHAR)(StartingFeature >> 8); - cdb->GET_CONFIGURATION.StartingFeature[1] = (UCHAR)(StartingFeature & 0xff); - cdb->GET_CONFIGURATION.AllocationLength[0] = (UCHAR)(BufferSize >> 8); - cdb->GET_CONFIGURATION.AllocationLength[1] = (UCHAR)(BufferSize & 0xff); - - status = DeviceSendSrbSynchronously(Device, - &srb, - Buffer, - BufferSize, - FALSE, - NULL); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, - "DeviceGetConfiguration: Status was %x\n", status)); - - if (NT_SUCCESS(status) || - (status == STATUS_BUFFER_OVERFLOW) || - (status == STATUS_DATA_OVERRUN)) - { - ULONG returned = srb.DataTransferLength; - PGET_CONFIGURATION_HEADER header = (PGET_CONFIGURATION_HEADER)Buffer; - ULONG available = (header->DataLength[0] << (8*3)) | - (header->DataLength[1] << (8*2)) | - (header->DataLength[2] << (8*1)) | - (header->DataLength[3] << (8*0)) ; - - available += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - _Analysis_assume_(srb.DataTransferLength <= BufferSize); - - // The true usable amount of data returned is the lesser of - // * the returned data per the srb.DataTransferLength field - // * the total size per the GET_CONFIGURATION_HEADER - // This is because ATAPI can't tell how many bytes really - // were transferred on success when using DMA. - if (available < returned) - { - returned = available; - } - - NT_ASSERT(returned <= BufferSize); - *ValidBytes = (ULONG)returned; - - //This is succeed case - status = STATUS_SUCCESS; - } - else - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL, - "DeviceGetConfiguration: failed %x\n", status)); - } - - return status; -} - - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceUpdateMmcWriteCapability( - _In_reads_bytes_(BufferSize) - PGET_CONFIGURATION_HEADER Buffer, - ULONG const BufferSize, - BOOLEAN const CurrentOnly, // TRUE == can drive write now, FALSE == can drive ever write - _Out_ PBOOLEAN Writable, - _Out_ PFEATURE_NUMBER ValidationSchema, - _Out_ PULONG BlockingFactor - ) -/*++ - -Routine Description: - - This function will allocates configuration buffer and set the size. - -Arguments: - - Buffer - - BufferSize - size of the buffer - CurrentOnly - valid data size in buffer - Writable - the buffer is allocationed in non-paged pool. - validationSchema - the starting point of the feature list - BlockingFactor - - -Return Value: - - NTSTATUS - -NOTE: does not handle case where more than 64k bytes are returned, - which requires multiple calls with different starting feature - numbers. - ---*/ -{ - // - // this routine is used to check if the drive can currently (current==TRUE) - // or can ever (current==FALSE) write to media with the current CDROM.SYS - // driver. this check parses the GET_CONFIGURATION response data to search - // for the appropriate features and/or if they are current. - // - // this function should not allocate any resources, and thus may safely - // return from any point within the function. - // - PAGED_CODE(); - - *Writable = FALSE; - *ValidationSchema = 0; - *BlockingFactor = 1; - - // - // if the drive supports hardware defect management and random writes, that's - // sufficient to allow writes. - // - { - PFEATURE_HEADER defectHeader; - PFEATURE_HEADER writableHeader; - - defectHeader = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureDefectManagement); - writableHeader = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureRandomWritable); - - if (defectHeader == NULL || writableHeader == NULL) - { - // cannot write this way - } - else if (!CurrentOnly) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes supported (defect management)\n")); - *Writable = TRUE; - return; - } - else if (defectHeader->Current && writableHeader->Current) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes *allowed* (defect management)\n")); - *Writable = TRUE; - *ValidationSchema = FeatureDefectManagement; - return; - } - } - - // Certain validation schema require the blocking factor - // This is a best-effort attempt to ensure that illegal - // requests do not make it to drive - { - PFEATURE_HEADER header; - ULONG additionalLength; - - // Certain validation schema require the blocking factor - // This is a best-effort attempt to ensure that illegal - // requests do not make it to drive - additionalLength = RTL_SIZEOF_THROUGH_FIELD(FEATURE_DATA_RANDOM_READABLE, Blocking) - sizeof(FEATURE_HEADER); - - header = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureRandomReadable); - - if ((header != NULL) && - (header->Current) && - (header->AdditionalLength >= additionalLength)) - { - PFEATURE_DATA_RANDOM_READABLE feature = (PFEATURE_DATA_RANDOM_READABLE)header; - *BlockingFactor = (feature->Blocking[0] << 8) | feature->Blocking[1]; - } - } - - // the majority of features to indicate write capability - // indicate this by a single feature existance/current bit. - // thus, can use a table-based method for the majority - // of the detection.... - { - typedef struct { - FEATURE_NUMBER FeatureToFind; // the ones allowed - FEATURE_NUMBER ValidationSchema; // and their related schema - } FEATURE_TO_WRITE_SCHEMA_MAP; - - static FEATURE_TO_WRITE_SCHEMA_MAP const FeaturesToAllowWritesWith[] = { - { FeatureRandomWritable, FeatureRandomWritable }, - { FeatureRigidRestrictedOverwrite, FeatureRigidRestrictedOverwrite }, - { FeatureRestrictedOverwrite, FeatureRestrictedOverwrite }, - { FeatureIncrementalStreamingWritable, FeatureIncrementalStreamingWritable }, - }; - - ULONG count; - for (count = 0; count < RTL_NUMBER_OF(FeaturesToAllowWritesWith); count++) - { - PFEATURE_HEADER header = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeaturesToAllowWritesWith[count].FeatureToFind); - if (header == NULL) - { - // cannot write using this method - } - else if (!CurrentOnly) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n", - FeaturesToAllowWritesWith[count].FeatureToFind - )); - *Writable = TRUE; - return; - } - else if (header->Current) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n", - FeaturesToAllowWritesWith[count].FeatureToFind - )); - *Writable = TRUE; - *ValidationSchema = FeaturesToAllowWritesWith[count].ValidationSchema; - return; - } - } // end count loop - } - - // unfortunately, DVD+R media doesn't require IncrementalStreamingWritable feature - // to be explicitly set AND it has a seperate bit in the feature to indicate - // being able to write to this media type. Thus, use a special case of the above code. - { - PFEATURE_DATA_DVD_PLUS_R header; - ULONG additionalLength = FIELD_OFFSET(FEATURE_DATA_DVD_PLUS_R, Reserved2[0]) - sizeof(FEATURE_HEADER); - header = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureDvdPlusR); - - if (header == NULL || (header->Header.AdditionalLength < additionalLength) || (!header->Write)) - { - // cannot write this way - } - else if (!CurrentOnly) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n", - FeatureDvdPlusR - )); - *Writable = TRUE; - return; - } - else if (header->Header.Current) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n", - FeatureDvdPlusR - )); - *Writable = TRUE; - *ValidationSchema = FeatureIncrementalStreamingWritable; - return; - } - } - - // unfortunately, DVD+R DL media doesn't require IncrementalStreamingWritable feature - // to be explicitly set AND it has a seperate bit in the feature to indicate - // being able to write to this media type. Thus, use a special case of the above code. - { - PFEATURE_DATA_DVD_PLUS_R_DUAL_LAYER header; - ULONG additionalLength = FIELD_OFFSET(FEATURE_DATA_DVD_PLUS_R_DUAL_LAYER, Reserved2[0]) - sizeof(FEATURE_HEADER); - header = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureDvdPlusRDualLayer); - - if (header == NULL || (header->Header.AdditionalLength < additionalLength) || (!header->Write)) - { - // cannot write this way - } - else if (!CurrentOnly) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n", - FeatureDvdPlusRDualLayer - )); - *Writable = TRUE; - return; - } - else if (header->Header.Current) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n", - FeatureDvdPlusRDualLayer - )); - *Writable = TRUE; - *ValidationSchema = FeatureIncrementalStreamingWritable; - return; - } - } - - // There are currently a number of drives on the market - // that fail to report: - // (a) FeatureIncrementalStreamingWritable as current - // for CD-R / DVD-R profile. - // (b) FeatureRestrictedOverwrite as current for CD-RW - // profile - // (c) FeatureRigidRestrictedOverwrite as current for - // DVD-RW profile - // - // Thus, use the profiles also. - { - PFEATURE_HEADER header; - header = MmcDataFindFeaturePage(Buffer, - BufferSize, - FeatureProfileList); - - if (header != NULL && header->Current) - { - // verify buffer bounds -- the below routine presumes full profile list provided - PUCHAR bufferEnd = ((PUCHAR)Buffer) + BufferSize; - PUCHAR headerEnd = ((PUCHAR)header) + header->AdditionalLength + RTL_SIZEOF_THROUGH_FIELD(FEATURE_HEADER, AdditionalLength); - if (bufferEnd >= headerEnd) // this _should_ never occurr, but.... - { - // Profiles don't contain any data other than current/not current. - // thus, can generically loop through them to see if any of the - // below (in order of preference) are current. - typedef struct { - FEATURE_PROFILE_TYPE ProfileToFind; // the ones allowed - FEATURE_NUMBER ValidationSchema; // and their related schema - } PROFILE_TO_WRITE_SCHEMA_MAP; - - static PROFILE_TO_WRITE_SCHEMA_MAP const ProfilesToAllowWritesWith[] = { - { ProfileDvdRewritable, FeatureRigidRestrictedOverwrite }, - { ProfileCdRewritable, FeatureRestrictedOverwrite }, - { ProfileDvdRecordable, FeatureIncrementalStreamingWritable }, - { ProfileCdRecordable, FeatureIncrementalStreamingWritable }, - }; - - ULONG count; - for (count = 0; count < RTL_NUMBER_OF(ProfilesToAllowWritesWith); count++) - { - BOOLEAN exists = FALSE; - MmcDataFindProfileInProfiles((PFEATURE_DATA_PROFILE_LIST)header, - ProfilesToAllowWritesWith[count].ProfileToFind, - CurrentOnly, - &exists); - if (exists) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, - "DeviceUpdateMmcWriteCapability => Writes %s (profile %04x)\n", - (CurrentOnly ? "*allowed*" : "supported"), - FeatureDvdPlusR - )); - - *Writable = TRUE; - *ValidationSchema = ProfilesToAllowWritesWith[count].ValidationSchema; - return; - } - } // end count loop - } // end if (bufferEnd >= headerEnd) - - } // end if (header != NULL && header->Current) - } - - // nothing matched to say it's writable..... - return; -} - -_IRQL_requires_max_(APC_LEVEL) -PVOID -MmcDataFindFeaturePage( - _In_reads_bytes_(Length) - PGET_CONFIGURATION_HEADER FeatureBuffer, - ULONG const Length, - FEATURE_NUMBER const Feature - ) -/*++ - -Routine Description: - - search the specific feature from feature list buffer - -Arguments: - - FeatureBuffer - buffer of feature list - Length - size of the buffer - Feature - feature wanted to find - -Return Value: - - PVOID - if found, pointer of starting address of the specific feature. - otherwise, NULL. - ---*/ -{ - PUCHAR buffer; - PUCHAR limit; - ULONG validLength; - - PAGED_CODE(); - - if (Length < sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER)) { - return NULL; - } - - // Calculate the length of valid data available in the - // capabilities buffer from the DataLength field - REVERSE_BYTES(&validLength, FeatureBuffer->DataLength); - validLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength); - - // set limit to point to first illegal address - limit = (PUCHAR)FeatureBuffer; - limit += min(Length, validLength); - - // set buffer to point to first page - buffer = FeatureBuffer->Data; - - // loop through each page until we find the requested one, or - // until it's not safe to access the entire feature header - // (if equal, have exactly enough for the feature header) - while (buffer + sizeof(FEATURE_HEADER) <= limit) - { - PFEATURE_HEADER header = (PFEATURE_HEADER)buffer; - FEATURE_NUMBER thisFeature; - - thisFeature = (header->FeatureCode[0] << 8) | - (header->FeatureCode[1]); - - if (thisFeature == Feature) - { - PUCHAR temp; - - // if don't have enough memory to safely access all the feature - // information, return NULL - temp = buffer; - temp += sizeof(FEATURE_HEADER); - temp += header->AdditionalLength; - - if (temp > limit) - { - // this means the transfer was cut-off, an insufficiently - // small buffer was given, or other arbitrary error. since - // it's not safe to view the amount of data (even though - // the header is safe) in this feature, pretend it wasn't - // transferred at all... - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Feature %x exists, but not safe to access all its " - "data. returning NULL\n", Feature)); - return NULL; - } - else - { - return buffer; - } - } - - if ((header->AdditionalLength % 4) && - !(Feature >= 0xff00 && Feature <= 0xffff)) - { - return NULL; - } - - buffer += sizeof(FEATURE_HEADER); - buffer += header->AdditionalLength; - - } - return NULL; -} - -_IRQL_requires_max_(APC_LEVEL) -VOID -MmcDataFindProfileInProfiles( - _In_ FEATURE_DATA_PROFILE_LIST const* ProfileHeader, - _In_ FEATURE_PROFILE_TYPE const ProfileToFind, - _In_ BOOLEAN const CurrentOnly, - _Out_ PBOOLEAN Found - ) -/*++ - -Routine Description: - - search the specific feature from feature list buffer - -Arguments: - - ProfileHeader - buffer of profile list - ProfileToFind - profile to be found - CurrentOnly - - -Return Value: - - Found - found or not - ---*/ -{ - FEATURE_DATA_PROFILE_LIST_EX const * profile; - ULONG numberOfProfiles; - ULONG i; - - PAGED_CODE(); - - // initialize output - *Found = FALSE; - - // sanity check - if (ProfileHeader->Header.AdditionalLength % 2 != 0) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Profile total length %x is not integral multiple of 4\n", - ProfileHeader->Header.AdditionalLength)); - NT_ASSERT(FALSE); - return; - } - - // calculate number of profiles - numberOfProfiles = ProfileHeader->Header.AdditionalLength / 4; - profile = ProfileHeader->Profiles; // zero-sized array - - // loop through profiles - for (i = 0; i < numberOfProfiles; i++) - { - FEATURE_PROFILE_TYPE currentProfile; - - currentProfile = (profile->ProfileNumber[0] << 8) | - (profile->ProfileNumber[1] & 0xff); - - if (currentProfile == ProfileToFind) - { - if (profile->Current || (!CurrentOnly)) - { - *Found = TRUE; - } - } - - profile++; - } - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeGuessBasedOnProfile( - FEATURE_PROFILE_TYPE const Profile - ) -/*++ - -Routine Description: - - determine the retry time based on profile - -Arguments: - - Profile - - -Return Value: - - LONGLONG - retry time - ---*/ -{ - LONGLONG result = -1; // this means we have no idea - - PAGED_CODE(); - - switch (Profile) - { - case ProfileInvalid: // = 0x0000, - case ProfileNonRemovableDisk: // = 0x0001, - case ProfileRemovableDisk: // = 0x0002, - case ProfileMOErasable: // = 0x0003, - case ProfileMOWriteOnce: // = 0x0004, - case ProfileAS_MO: // = 0x0005, - // Reserved 0x0006 - 0x0007, - // Reserved 0x000b - 0x000f, - // Reserved 0x0017 - 0x0019 - // Reserved 0x001C - 001F - // Reserved 0x0023 - 0x0029 - // Reserved 0x002C - 0x003F - // Reserved 0x0044 - 0x004F - // Reserved 0x0053 - 0xfffe - case ProfileNonStandard: // = 0xffff - default: - { - NOTHING; // no default - break; - } - - case ProfileCdrom: // = 0x0008, - case ProfileCdRecordable: // = 0x0009, - case ProfileCdRewritable: // = 0x000a, - case ProfileDDCdrom: // = 0x0020, // obsolete - case ProfileDDCdRecordable: // = 0x0021, // obsolete - case ProfileDDCdRewritable: // = 0x0022, // obsolete - { - // 4x is ok as all CD drives have - // at least 64k*4 (256k) buffer - // and this is just a first-pass - // guess based only on profile - result = WRITE_RETRY_DELAY_CD_4x; - break; - } - case ProfileDvdRom: // = 0x0010, - case ProfileDvdRecordable: // = 0x0011, - case ProfileDvdRam: // = 0x0012, - case ProfileDvdRewritable: // = 0x0013, // restricted overwrite - case ProfileDvdRWSequential: // = 0x0014, - case ProfileDvdDashRLayerJump: // = 0x0016, - case ProfileDvdPlusRW: // = 0x001A, - case ProfileDvdPlusR: // = 0x001B, - { - result = WRITE_RETRY_DELAY_DVD_1x; - break; - } - case ProfileDvdDashRDualLayer: // = 0x0015, - case ProfileDvdPlusRWDualLayer: // = 0x002A, - case ProfileDvdPlusRDualLayer: // = 0x002B, - { - result = WRITE_RETRY_DELAY_DVD_1x; - break; - } - - case ProfileBDRom: // = 0x0040, - case ProfileBDRSequentialWritable: // = 0x0041, // BD-R 'SRM' - case ProfileBDRRandomWritable: // = 0x0042, // BD-R 'RRM' - case ProfileBDRewritable: // = 0x0043, - { - // I could not find specifications for the - // minimal 1x data rate for BD media. Use - // HDDVD values for now, since they are - // likely to be similar. Also, all media - // except for CD, DVD, and AS-MO should - // already fully support GET_CONFIG, so - // this guess is only used if we fail to - // get a performance descriptor.... - result = WRITE_RETRY_DELAY_HDDVD_1x; - break; - } - - case ProfileHDDVDRom: // = 0x0050, - case ProfileHDDVDRecordable: // = 0x0051, - case ProfileHDDVDRam: // = 0x0052, - { - // All HDDVD drives support GET_PERFORMANCE - // so this guess is fine at 1x.... - result = WRITE_RETRY_DELAY_HDDVD_1x; - break; - } - - // addition of any further profile types is not - // technically required as GET PERFORMANCE - // should succeed for all future drives. However, - // it is useful in case GET PERFORMANCE does - // fail for other reasons (i.e. bus resets, etc) - - } // end switch(Profile) - - return result; -} - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeDetectionBasedOnModePage2A( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - determine the retry time based on mode sense data - -Arguments: - - DeviceExtension - device context - -Return Value: - - LONGLONG - retry time - ---*/ -{ - NTSTATUS status; - ULONG transferSize = min(0xFFF0, DeviceExtension->ScratchContext.ScratchBufferSize); - CDB cdb; - LONGLONG result = -1; - - PAGED_CODE(); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.MODE_SENSE10.OperationCode = SCSIOP_MODE_SENSE10; - cdb.MODE_SENSE10.Dbd = 1; - cdb.MODE_SENSE10.PageCode = MODE_PAGE_CAPABILITIES; - cdb.MODE_SENSE10.AllocationLength[0] = (UCHAR)(transferSize >> 8); - cdb.MODE_SENSE10.AllocationLength[1] = (UCHAR)(transferSize & 0xFF); - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, NULL, transferSize, TRUE, &cdb, 10); - - // analyze the data on success.... - if (NT_SUCCESS(status)) - { - MODE_PARAMETER_HEADER10 const* header = DeviceExtension->ScratchContext.ScratchBuffer; - CDVD_CAPABILITIES_PAGE const* page = NULL; - ULONG dataLength = (header->ModeDataLength[0] << (8*1)) | - (header->ModeDataLength[1] << (8*0)) ; - - // no possible overflow - if (dataLength != 0) - { - dataLength += RTL_SIZEOF_THROUGH_FIELD(MODE_PARAMETER_HEADER10, ModeDataLength); - } - - // If it's not abundantly clear, we really don't trust the drive - // to be returning valid data. Get the page pointer and usable - // size of the page here... - if (dataLength < sizeof(MODE_PARAMETER_HEADER10)) - { - dataLength = 0; - } - else if (dataLength > DeviceExtension->ScratchContext.ScratchBufferSize) - { - dataLength = 0; - } - else if ((header->BlockDescriptorLength[1] == 0) && - (header->BlockDescriptorLength[0] == 0)) - { - dataLength -= sizeof(MODE_PARAMETER_HEADER10); - page = (CDVD_CAPABILITIES_PAGE const *)(header + 1); - } - else if ((header->BlockDescriptorLength[1] == 0) && - (header->BlockDescriptorLength[0] == sizeof(MODE_PARAMETER_BLOCK))) - { - dataLength -= sizeof(MODE_PARAMETER_HEADER10); - dataLength -= min(dataLength, sizeof(MODE_PARAMETER_BLOCK)); - page = (CDVD_CAPABILITIES_PAGE const *) - ( ((PUCHAR)header) + - sizeof(MODE_PARAMETER_HEADER10) + - sizeof(MODE_PARAMETER_BLOCK) - ); - } - - // Change dataLength from the size available per the header to - // the size available per the page itself. - if ((page != NULL) && - (dataLength >= RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, PageLength)) - ) - { - dataLength = min(dataLength, ((ULONG)(page->PageLength) + 2)); - } - - // Ignore the page if the fastest write speed field isn't available. - if ((page != NULL) && - (dataLength < RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, WriteSpeedMaximum)) - ) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "ModePage 2Ah was requested, but drive reported " - "only %x bytes (%x needed). Ignoring.\n", - dataLength, - RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, WriteSpeedMaximum) - )); - page = NULL; - } - - // Verify the page we requested is the one the drive actually provided - if ((page != NULL) && (page->PageCode != MODE_PAGE_CAPABILITIES)) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "ModePage 2Ah was requested, but drive reported " - "page %x\n", - page->PageCode - )); - page = NULL; - } - - // If _everything_ succeeded, then use the speed value in the page! - if (page != NULL) - { - ULONG temp = - (page->WriteSpeedMaximum[0] << (8*1)) | - (page->WriteSpeedMaximum[1] << (8*0)) ; - // stored as 1,000 byte increments... - temp *= 1000; - // typically stored at 2448 bytes/sector due to CD media - // error up to 20% high by presuming it returned 2048 data - // and convert to sectors/second - temp /= 2048; - // currently: sectors/sec - // ignore too-small or zero values - if (temp != 0) - { - result = ConvertSectorsPerSecondTo100nsUnitsFor64kWrite(temp); - } - } - } - - ScratchBuffer_EndUse(DeviceExtension); - - return result; -} - - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeDetectionBasedOnGetPerformance( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN UseLegacyNominalPerformance - ) -/*++ - -Routine Description: - - determine the retry time based on get performance data - -Arguments: - - DeviceExtension - device context - UseLegacyNominalPerformance - - -Return Value: - - LONGLONG - retry time - ---*/ -{ - typedef struct _GET_PERFORMANCE_HEADER { - UCHAR TotalDataLength[4]; // not including this field - UCHAR Except : 1; - UCHAR Write : 1; - UCHAR Reserved0 : 6; - UCHAR Reserved1[3]; - } GET_PERFORMANCE_HEADER, *PGET_PERFORMANCE_HEADER; - C_ASSERT( sizeof(GET_PERFORMANCE_HEADER) == 8); - - typedef struct _GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR { - UCHAR StartLba[4]; - UCHAR StartPerformance[4]; - UCHAR EndLba[4]; - UCHAR EndPerformance[4]; - } GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, *PGET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR; - C_ASSERT( sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR) == 16); - - - typedef struct _GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR { - UCHAR MixedReadWrite : 1; - UCHAR GuaranteedForWholeMedia : 1; - UCHAR Reserved0_RDD : 1; - UCHAR WriteRotationControl : 2; - UCHAR Reserved1 : 3; - UCHAR Reserved2[3]; - - UCHAR MediaCapacity[4]; - UCHAR ReadSpeedKilobytesPerSecond[4]; - UCHAR WriteSpeedKilobytesPerSecond[4]; - } GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, *PGET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR; - C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == 16); - - ////// - - NTSTATUS status; - LONGLONG result = -1; - - // transfer size -- descriptors + 8 byte header - // Note: this size is identical for both descriptor types - C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR)); - - ULONG const maxDescriptors = min(200, (DeviceExtension->ScratchContext.ScratchBufferSize-sizeof(GET_PERFORMANCE_HEADER))/sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR)); - ULONG validDescriptors = 0; - ULONG transferSize = sizeof(GET_PERFORMANCE_HEADER) + (maxDescriptors*sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR)); - CDB cdb; - - PAGED_CODE(); - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - if (UseLegacyNominalPerformance) - { - cdb.GET_PERFORMANCE.OperationCode = SCSIOP_GET_PERFORMANCE; - cdb.GET_PERFORMANCE.Except = 0; - cdb.GET_PERFORMANCE.Write = 1; - cdb.GET_PERFORMANCE.Tolerance = 2; // only defined option - cdb.GET_PERFORMANCE.MaximumNumberOfDescriptors[1] = (UCHAR)maxDescriptors; - cdb.GET_PERFORMANCE.Type = 0; // legacy nominal descriptors - } - else - { - cdb.GET_PERFORMANCE.OperationCode = SCSIOP_GET_PERFORMANCE; - cdb.GET_PERFORMANCE.MaximumNumberOfDescriptors[1] = (UCHAR)maxDescriptors; - cdb.GET_PERFORMANCE.Type = 3; // write speed - } - - status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, NULL, transferSize, TRUE, &cdb, 12, CDROM_GET_PERFORMANCE_TIMEOUT); - - // determine how many valid descriptors there actually are - if (NT_SUCCESS(status)) - { - GET_PERFORMANCE_HEADER const* header = (GET_PERFORMANCE_HEADER const*)DeviceExtension->ScratchContext.ScratchBuffer; - ULONG temp1 = (header->TotalDataLength[0] << (8*3)) | - (header->TotalDataLength[1] << (8*2)) | - (header->TotalDataLength[2] << (8*1)) | - (header->TotalDataLength[3] << (8*0)) ; - - // adjust data size for header - if (temp1 + (ULONG)RTL_SIZEOF_THROUGH_FIELD(GET_PERFORMANCE_HEADER, TotalDataLength) < temp1) - { - temp1 = 0; - } - else if (temp1 != 0) - { - temp1 += RTL_SIZEOF_THROUGH_FIELD(GET_PERFORMANCE_HEADER, TotalDataLength); - } - - if (temp1 == 0) - { - // no data returned - } - else if (temp1 <= sizeof(GET_PERFORMANCE_HEADER)) - { - // only the header returned, no descriptors - } - else if (UseLegacyNominalPerformance && - ((header->Except != 0) || (header->Write == 0)) - ) - { - // bad data being returned -- ignore it - } - else if (!UseLegacyNominalPerformance && - ((header->Except != 0) || (header->Write != 0)) - ) - { - // returning Performance (Type 0) data, not requested Write Speed (Type 3) data - } - else if ( (temp1 - sizeof(GET_PERFORMANCE_HEADER)) % sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) != 0) - { - // Note: this size is identical for both descriptor types - C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR)); - - // not returning valid data.... - } - else // save how many are usable - { - // Note: this size is identical for both descriptor types - C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR)); - - // take the smaller usable value - temp1 = min(temp1, DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength); - // then determine the usable descriptors - validDescriptors = (temp1 - sizeof(GET_PERFORMANCE_HEADER)) / sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR); - } - } - - // The drive likely supports this command. - // Verify the data makes sense. - if (NT_SUCCESS(status)) - { - ULONG i; - GET_PERFORMANCE_HEADER const* header = (GET_PERFORMANCE_HEADER const*)DeviceExtension->ScratchContext.ScratchBuffer; - GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR const* descriptor = (GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR const*)(header+1); // pointer math - - // NOTE: We could write this loop twice, once for each write descriptor type - // However, the only fields of interest are the writeKBps field (Type 3) and - // the EndPerformance field (Type 0), which both exist in the same exact - // location and have essentially the same meaning. So, just use the same - // loop/structure pointers for both of the to simplify the readability of - // this code. The C_ASSERT()s here verify this at compile-time. - - C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR)); - C_ASSERT( FIELD_OFFSET(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, WriteSpeedKilobytesPerSecond) == - FIELD_OFFSET(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, EndPerformance) - ); - C_ASSERT( RTL_FIELD_SIZE(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, WriteSpeedKilobytesPerSecond) == - RTL_FIELD_SIZE(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, EndPerformance) - ); - - // loop through them all, and find the fastest listed write speed - for (i = 0; NT_SUCCESS(status) && (i WriteSpeedKilobytesPerSecond[0] << (8*3)) | - (descriptor->WriteSpeedKilobytesPerSecond[1] << (8*2)) | - (descriptor->WriteSpeedKilobytesPerSecond[2] << (8*1)) | - (descriptor->WriteSpeedKilobytesPerSecond[3] << (8*0)) ; - - // Avoid overflow and still have good estimates - // 0x1 0000 0000 / 1000 == 0x00418937 == maximum writeKBps to multiple first - ULONG const sectorsPerSecond = - (writeKBps > 0x00418937) ? // would overflow occur by multiplying by 1000? - ((writeKBps / 2048) * 1000) : // must divide first, minimal loss of accuracy - ((writeKBps * 1000) / 2048) ; // must multiply first, avoid loss of accuracy - - if (sectorsPerSecond <= 0) - { - break; // out of the loop -- no longer valid data (very defensive programming) - } - - // we have at least one valid result, so prevent returning -1 as our result - if (result == -1) { result = MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS; } - - // take the fastest speed (smallest wait time) we've found thus far - result = min(result, ConvertSectorsPerSecondTo100nsUnitsFor64kWrite(sectorsPerSecond)); - } - } - - ScratchBuffer_EndUse(DeviceExtension); - - return result; -} - -#pragma warning(pop) // un-sets any local warning changes diff --git a/storage/class/cdrom/src/mmc.h b/storage/class/cdrom/src/mmc.h deleted file mode 100644 index 51c033091..000000000 --- a/storage/class/cdrom/src/mmc.h +++ /dev/null @@ -1,122 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - mmc.h - -Abstract: - - Functions for MMC area. - -Author: - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#ifndef __MMC_H__ -#define __MMC_H__ - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceDeallocateMmcResources( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceAllocateMmcResources( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceUpdateMmcCapabilities( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetConfigurationWithAlloc( - _In_ WDFDEVICE Device, - _Outptr_result_bytebuffer_all_(*BytesReturned) - PGET_CONFIGURATION_HEADER * Buffer, - _Out_ PULONG BytesReturned, - FEATURE_NUMBER const StartingFeature, - ULONG const RequestedType - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceGetConfiguration( - _In_ WDFDEVICE Device, - _Out_writes_bytes_to_(BufferSize, *ValidBytes) - PGET_CONFIGURATION_HEADER Buffer, - _In_ ULONG const BufferSize, - _Out_ PULONG ValidBytes, - _In_ FEATURE_NUMBER const StartingFeature, - _In_ ULONG const RequestedType - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceUpdateMmcWriteCapability( - _In_reads_bytes_(BufferSize) - PGET_CONFIGURATION_HEADER Buffer, - ULONG const BufferSize, - BOOLEAN const CurrentOnly, // TRUE == can drive write now, FALSE == can drive ever write - _Out_ PBOOLEAN Writable, - _Out_ PFEATURE_NUMBER ValidationSchema, - _Out_ PULONG BlockingFactor - ); - -_IRQL_requires_max_(APC_LEVEL) -PVOID -MmcDataFindFeaturePage( - _In_reads_bytes_(Length) - PGET_CONFIGURATION_HEADER FeatureBuffer, - ULONG const Length, - FEATURE_NUMBER const Feature - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -MmcDataFindProfileInProfiles( - _In_ FEATURE_DATA_PROFILE_LIST const* ProfileHeader, - _In_ FEATURE_PROFILE_TYPE const ProfileToFind, - _In_ BOOLEAN const CurrentOnly, - _Out_ PBOOLEAN Found - ); - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeGuessBasedOnProfile( - FEATURE_PROFILE_TYPE const Profile - ); - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeDetectionBasedOnModePage2A( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) -LONGLONG -DeviceRetryTimeDetectionBasedOnGetPerformance( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN UseLegacyNominalPerformance - ); - -#endif // __MMC_H__ diff --git a/storage/class/cdrom/src/pnppower.c b/storage/class/cdrom/src/pnppower.c deleted file mode 100644 index 56f239e4e..000000000 --- a/storage/class/cdrom/src/pnppower.c +++ /dev/null @@ -1,684 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - pnppower.c - -Abstract: - - Functions to handle PnP and Power IRPs. - -Environment: - - kernel mode only - -Notes: - optical devices do not need to issue SPIN UP when power up. - The device itself should SPIN UP to process commands. - - -Revision History: - ---*/ - - -#include "ntddk.h" -#include "wdfcore.h" - -#include "cdrom.h" -#include "ioctl.h" -#include "scratch.h" -#include "mmc.h" - -#ifdef DEBUG_USE_WPP -#include "pnppower.tmh" -#endif - - -NTSTATUS -DeviceScratchSyncCache( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -NTSTATUS -DeviceScratchPreventMediaRemoval( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN Prevent - ); - -NTSTATUS -RequestIssueShutdownFlush( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PIRP Irp - ); - -IO_COMPLETION_ROUTINE RequestProcessPowerIrpCompletion; - -EVT_WDF_REQUEST_COMPLETION_ROUTINE RequestUnlockQueueCompletion; - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DevicePowerSettingCallback) - -#endif - -#pragma warning(push) -#pragma warning(disable:4152) // nonstandard extension, function/data pointer conversion in expression - -#pragma warning(disable:28118) // Dispatch routines for IRP_MJ_SHUTDOWN, IRP_MJ_FLUSH_BUFFERS occur at PASSIVE_LEVEL. - // WDF defines EVT_WDFDEVICE_WDM_IRP_PREPROCESS with _IRQL_requires_max_(DISPATCH_LEVEL), - // triggering a false positive for this warning. - -NTSTATUS -RequestProcessShutdownFlush( - WDFDEVICE Device, - PIRP Irp - ) -/*++ - -Routine Description: - - process IRP: IRP_MJ_SHUTDOWN, IRP_MJ_FLUSH_BUFFERS - -Arguments: - - Device - device object - Irp - the irp - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PIO_STACK_LOCATION currentStack = NULL; - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - - //add trace info - - // acquire the shutdown/flush lock - WdfWaitLockAcquire(deviceExtension->ShutdownFlushWaitLock, NULL); - - currentStack = IoGetCurrentIrpStackLocation(Irp); - - // finish all current requests - WdfIoQueueStopSynchronously(deviceExtension->SerialIOQueue); - - // sync cache - if (NT_SUCCESS(status)) - { - // safe to use scratch srb to send the request. - status = DeviceScratchSyncCache(deviceExtension); - } - - // For SHUTDOWN, allow media removal. - if (NT_SUCCESS(status)) - { - if (currentStack->MajorFunction == IRP_MJ_SHUTDOWN) - { - // safe to use scratch srb to send the request. - status = DeviceScratchPreventMediaRemoval(deviceExtension, FALSE); - } - } - - // Use original IRP, send SRB_FUNCTION_SHUTDOWN or SRB_FUNCTION_FLUSH (no retry) - if (NT_SUCCESS(status)) - { - status = RequestIssueShutdownFlush(deviceExtension, Irp); - } - - // restart queue to allow processing further requests. - WdfIoQueueStart(deviceExtension->SerialIOQueue); - - // release the shutdown/flush lock - WdfWaitLockRelease(deviceExtension->ShutdownFlushWaitLock); - - // 6. complete the irp - Irp->IoStatus.Status = status; - IoCompleteRequest(Irp, 0); - - return status; -} - -NTSTATUS -RequestProcessSetPower( - WDFDEVICE Device, - PIRP Irp - ) -/*++ - -Routine Description: - - process IRP: IRP_MJ_POWER - -Arguments: - - Device - device object - Irp - the irp - -Return Value: - - NTSTATUS - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device); - PIO_STACK_LOCATION currentStack; - NTSTATUS status; - BOOLEAN IrpMarkedPending = FALSE; - - currentStack = IoGetCurrentIrpStackLocation(Irp); - - if ((currentStack->Parameters.Power.Type == DevicePowerState) && - (currentStack->Parameters.Power.State.DeviceState != PowerDeviceD0)) - { - // We need to unlock the device queue in D3 postprocessing. - IoCopyCurrentIrpStackLocationToNext(Irp); - IoSetCompletionRoutine(Irp, - RequestProcessPowerIrpCompletion, - deviceExtension, - TRUE, - TRUE, - TRUE); - - // Mark the Irp pending as we'll defer the I/O completion. - IoMarkIrpPending(Irp); - IrpMarkedPending = TRUE; - } - else { - - IoSkipCurrentIrpStackLocation(Irp); - } - -#pragma warning(push) -#pragma warning(disable: 28193) // OACR will complain that the status variable is not examined. - - // - // Deliver the IRP back to the framework. - // - - status = WdfDeviceWdmDispatchPreprocessedIrp(Device, Irp); - - if (IrpMarkedPending) - { - UNREFERENCED_PARAMETER(status); - return STATUS_PENDING; - } - -#pragma warning(pop) - - return status; -} - -// use scratch SRB to issue SYNC CACHE command. -NTSTATUS -DeviceScratchSyncCache( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - use scratch buffer to send SYNC CACHE command - -Arguments: - - DeviceExtension - device context - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE; - //srb->QueueTag = SP_UNTAGGED; - //srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - - status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, NULL, transferSize, FALSE, &cdb, 10, TimeOutValueGetCapValue(DeviceExtension->TimeOutValue, 4)); - - ScratchBuffer_EndUse(DeviceExtension); - - return status; -} - -NTSTATUS -DeviceScratchPreventMediaRemoval( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN Prevent - ) -/*++ - -Routine Description: - - use scratch SRB to issue ALLOW/PREVENT MEDIA REMOVAL command. - -Arguments: - - DeviceExtension - device context - Prevent - TRUE (prevent media removal); FALSE (allow media removal) - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - ULONG transferSize = 0; - CDB cdb; - - ScratchBuffer_BeginUse(DeviceExtension); - - RtlZeroMemory(&cdb, sizeof(CDB)); - // Set up the CDB - cdb.MEDIA_REMOVAL.OperationCode = SCSIOP_MEDIUM_REMOVAL; - cdb.MEDIA_REMOVAL.Prevent = Prevent; - //srb->QueueTag = SP_UNTAGGED; - //srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - - status = ScratchBuffer_ExecuteCdb(DeviceExtension, NULL, transferSize, FALSE, &cdb, 6); - - ScratchBuffer_EndUse(DeviceExtension); - - return status; -} - -NTSTATUS -RequestIssueShutdownFlush( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PIRP Irp - ) -/*++ - -Routine Description: - - issue SRB function Flush/Shutdown command. - -Arguments: - - DeviceExtension - device context - Irp - the irp - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PIO_STACK_LOCATION currentStack = NULL; - - ULONG transferSize = 0; - BOOLEAN shouldRetry = TRUE; - ULONG timesAlreadyRetried = 0; - LONGLONG retryIn100nsUnits = 0; - - - currentStack = IoGetCurrentIrpStackLocation(Irp); - - - ScratchBuffer_BeginUse(DeviceExtension); - - // no retry needed. - { - ScratchBuffer_SetupSrb(DeviceExtension, NULL, transferSize, FALSE); - - // Set up the SRB/CDB - srb->QueueTag = SP_UNTAGGED; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - srb->TimeOutValue = TimeOutValueGetCapValue(DeviceExtension->TimeOutValue, 4); - srb->CdbLength = 0; - - if (currentStack->MajorFunction == IRP_MJ_SHUTDOWN) - { - srb->Function = SRB_FUNCTION_SHUTDOWN; - } - else - { - srb->Function = SRB_FUNCTION_FLUSH; - } - - ScratchBuffer_SendSrb(DeviceExtension, TRUE, NULL); - - shouldRetry = RequestSenseInfoInterpretForScratchBuffer(DeviceExtension, - timesAlreadyRetried, - &status, - &retryIn100nsUnits); - UNREFERENCED_PARAMETER(shouldRetry); //defensive coding, avoid PREFAST warning. - UNREFERENCED_PARAMETER(status); //defensive coding, avoid PREFAST warning. - - // retrieve the real status from the request. - status = WdfRequestGetStatus(DeviceExtension->ScratchContext.ScratchRequest); - } - - ScratchBuffer_EndUse(DeviceExtension); - - - return status; -} - -VOID -RequestUnlockQueueCompletion ( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS Params, - _In_ WDFCONTEXT Context - ) -{ - PIRP Irp = Context; - WDFDEVICE device = WdfIoTargetGetDevice(Target); - PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device); - - UNREFERENCED_PARAMETER(Request); - UNREFERENCED_PARAMETER(Params); - - deviceExtension->PowerContext.Options.LockQueue = FALSE; - - PowerContextEndUse(deviceExtension); - - // Complete the original power irp - IoCompleteRequest( Irp, IO_NO_INCREMENT ); -} - -NTSTATUS -RequestProcessPowerIrpCompletion( - _In_ PDEVICE_OBJECT DeviceObject, - _In_ PIRP Irp, - _In_reads_opt_(_Inexpressible_("varies")) PVOID Context - ) -/*++ - -Routine Description: - - Free the Irp. - -Arguments: - - DeviceObject - device that the completion routine fires on. - - Irp - The irp to be completed. - - Context - IRP context - -Return Value: - NTSTATUS - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = Context; - PIO_STACK_LOCATION currentStack; - - UNREFERENCED_PARAMETER(DeviceObject); - - if (Irp->PendingReturned) - { - IoMarkIrpPending( Irp ); - } - - currentStack = IoGetCurrentIrpStackLocation(Irp); - - NT_ASSERT(currentStack->Parameters.Power.Type == DevicePowerState); - NT_ASSERT(currentStack->Parameters.Power.State.DeviceState != PowerDeviceD0); - - _Analysis_assume_(deviceExtension != NULL); - - deviceExtension->PowerContext.PowerChangeState.PowerDown++; - - // Step 5. UNLOCK QUEUE - if (deviceExtension->PowerContext.Options.LockQueue) - { - (VOID)DeviceSendPowerDownProcessRequest(deviceExtension, - RequestUnlockQueueCompletion, - Irp); - - // Let the completion routine complete the Irp - return STATUS_MORE_PROCESSING_REQUIRED; - } - - // Release the power context if it wasn't already done as part of D0Exit handling - if (deviceExtension->PowerContext.InUse) - { - PowerContextEndUse(deviceExtension); - } - - return STATUS_CONTINUE_COMPLETION; -} - - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextReuseRequest( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - reset fields for the request. - -Arguments: - - DeviceExtension - device context - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDF_REQUEST_REUSE_PARAMS reuseParams; - PIRP irp = NULL; - - RtlZeroMemory(&(DeviceExtension->PowerContext.SenseData), sizeof(DeviceExtension->PowerContext.SenseData)); - RtlZeroMemory(&(DeviceExtension->PowerContext.Srb), sizeof(DeviceExtension->PowerContext.Srb)); - - irp = WdfRequestWdmGetIrp(DeviceExtension->PowerContext.PowerRequest); - - // Re-use the previously created PowerRequest object and format it - WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_NOT_SUPPORTED); - status = WdfRequestReuse(DeviceExtension->PowerContext.PowerRequest, &reuseParams); - if (NT_SUCCESS(status)) - { - // This request was preformated during initialization so this call should never fail. - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - DeviceExtension->PowerContext.PowerRequest, - IOCTL_SCSI_EXECUTE_IN, - NULL, NULL, - NULL, NULL, - NULL, NULL); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "PowerContextReuseRequest: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n", - status)); - } - } - - // Do some basic initialization of the PowerRequest, the rest will be done by the caller - // of this function - if (NT_SUCCESS(status)) - { - PIO_STACK_LOCATION nextStack = NULL; - - nextStack = IoGetNextIrpStackLocation(irp); - - nextStack->MajorFunction = IRP_MJ_SCSI; - nextStack->Parameters.Scsi.Srb = &(DeviceExtension->PowerContext.Srb); - - DeviceExtension->PowerContext.Srb.Length = sizeof(SCSI_REQUEST_BLOCK); - DeviceExtension->PowerContext.Srb.OriginalRequest = irp; - - DeviceExtension->PowerContext.Srb.SenseInfoBuffer = &(DeviceExtension->PowerContext.SenseData); - DeviceExtension->PowerContext.Srb.SenseInfoBufferLength = SENSE_BUFFER_SIZE; - } - - return status; -} - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextBeginUse( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - initialize fields in power context - -Arguments: - - DeviceExtension - device context - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - NT_ASSERT(!DeviceExtension->PowerContext.InUse); - - DeviceExtension->PowerContext.InUse = TRUE; - DeviceExtension->PowerContext.RetryCount = MAXIMUM_RETRIES; - DeviceExtension->PowerContext.RetryIntervalIn100ns = 0; - - KeQueryTickCount(&DeviceExtension->PowerContext.StartTime); - - RtlZeroMemory(&(DeviceExtension->PowerContext.Options), sizeof(DeviceExtension->PowerContext.Options)); - RtlZeroMemory(&(DeviceExtension->PowerContext.PowerChangeState), sizeof(DeviceExtension->PowerContext.PowerChangeState)); - - status = PowerContextReuseRequest(DeviceExtension); - - RequestClearSendTime(DeviceExtension->PowerContext.PowerRequest); - - return status; -} - -_IRQL_requires_max_(DISPATCH_LEVEL) -NTSTATUS -PowerContextEndUse( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - inidate that power context using is finished. - -Arguments: - - DeviceExtension - device context - -Return Value: - - NTSTATUS - ---*/ -{ - NT_ASSERT(DeviceExtension->PowerContext.InUse); - - DeviceExtension->PowerContext.InUse = FALSE; - - KeQueryTickCount(&DeviceExtension->PowerContext.CompleteTime); - - return STATUS_SUCCESS; -} - - -_Function_class_(POWER_SETTING_CALLBACK) -_IRQL_requires_same_ -NTSTATUS -DevicePowerSettingCallback( - _In_ LPCGUID SettingGuid, - _In_reads_bytes_(ValueLength) PVOID Value, - _In_ ULONG ValueLength, - _Inout_opt_ PVOID Context - ) -/*++ -Description: - - This function is the callback for power setting notifications (registered - when ClasspGetD3IdleTimeout() is called for the first time). - - Currently, this function is used to get the disk idle timeout value from - the system power settings. - - This function is guaranteed to be called at PASSIVE_LEVEL. - -Arguments: - - SettingGuid - The power setting GUID. - Value - Pointer to the power setting value. - ValueLength - Size of the Value buffer. - Context - The FDO's device extension. - -Return Value: - - STATUS_SUCCESS - ---*/ -{ - PCDROM_DEVICE_EXTENSION DeviceExtension = Context; - MONITOR_DISPLAY_STATE DisplayState; - - PAGED_CODE(); - - if (IsEqualGUID(SettingGuid, &GUID_CONSOLE_DISPLAY_STATE)) { - - if ((ValueLength == sizeof(ULONG)) && (Value != NULL)) { - - DisplayState = *((PULONG)Value); - - _Analysis_assume_(DeviceExtension != NULL); - - // - // Power setting callbacks are asynchronous so make sure the device - // is completely initialized before taking any actions. - // - if (DeviceExtension->IsInitialized) { - - // - // If monitor is off, change media change requests to not keep device active. - // This allows the devices to go to sleep if there are no other active requests. - // - - if (DisplayState == PowerMonitorOff) { - - // - // Mark the device inactive so that it can enter a low power state. - // - - DeviceMarkActive(DeviceExtension, FALSE, TRUE); - SET_FLAG(DeviceExtension->MediaChangeDetectionInfo->SrbFlags, SRB_FLAGS_NO_KEEP_AWAKE); - } - else - { - CLEAR_FLAG(DeviceExtension->MediaChangeDetectionInfo->SrbFlags, SRB_FLAGS_NO_KEEP_AWAKE); - DeviceMarkActive(DeviceExtension, TRUE, TRUE); - } - } - } - } - - return STATUS_SUCCESS; -} - -#pragma warning(pop) // un-sets any local warning changes - diff --git a/storage/class/cdrom/src/scratch.c b/storage/class/cdrom/src/scratch.c deleted file mode 100644 index fe82049a8..000000000 --- a/storage/class/cdrom/src/scratch.c +++ /dev/null @@ -1,1463 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - scratch.c - -Abstract: - - Functions for using common scratch buffer - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "ioctl.h" -#include "scratch.h" -#include "mmc.h" - -#ifdef DEBUG_USE_WPP -#include "scratch.tmh" -#endif - -// Forward declarations -EVT_WDF_REQUEST_COMPLETION_ROUTINE ScratchBuffer_ReadWriteCompletionRoutine; - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, ScratchBuffer_Deallocate) -#pragma alloc_text(PAGE, ScratchBuffer_Allocate) -#pragma alloc_text(PAGE, ScratchBuffer_SetupSrb) -#pragma alloc_text(PAGE, ScratchBuffer_ExecuteCdbEx) - -#endif - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScratchBuffer_Deallocate( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - release all resources allocated for scratch. - -Arguments: - - DeviceExtension - device extension - -Return Value: - - none - ---*/ -{ - PAGED_CODE (); - - NT_ASSERT(DeviceExtension->ScratchContext.ScratchInUse == 0); - - if (DeviceExtension->ScratchContext.ScratchHistory != NULL) - { - ExFreePool(DeviceExtension->ScratchContext.ScratchHistory); - DeviceExtension->ScratchContext.ScratchHistory = NULL; - } - if (DeviceExtension->ScratchContext.ScratchSense != NULL) - { - ExFreePool(DeviceExtension->ScratchContext.ScratchSense); - DeviceExtension->ScratchContext.ScratchSense = NULL; - } - if (DeviceExtension->ScratchContext.ScratchSrb != NULL) - { - ExFreePool(DeviceExtension->ScratchContext.ScratchSrb); - DeviceExtension->ScratchContext.ScratchSrb = NULL; - } - if (DeviceExtension->ScratchContext.ScratchBufferSize != 0) - { - DeviceExtension->ScratchContext.ScratchBufferSize = 0; - } - if (DeviceExtension->ScratchContext.ScratchBufferMdl != NULL) - { - IoFreeMdl(DeviceExtension->ScratchContext.ScratchBufferMdl); - DeviceExtension->ScratchContext.ScratchBufferMdl = NULL; - } - if (DeviceExtension->ScratchContext.ScratchBuffer != NULL) - { - ExFreePool(DeviceExtension->ScratchContext.ScratchBuffer); - DeviceExtension->ScratchContext.ScratchBuffer = NULL; - } - - if (DeviceExtension->ScratchContext.PartialMdl != NULL) - { - IoFreeMdl(DeviceExtension->ScratchContext.PartialMdl); - DeviceExtension->ScratchContext.PartialMdl = NULL; - } - - if (DeviceExtension->ScratchContext.ScratchRequest != NULL) - { - PIRP irp = WdfRequestWdmGetIrp(DeviceExtension->ScratchContext.ScratchRequest); - if (irp->MdlAddress) - { - irp->MdlAddress = NULL; - } - WdfObjectDelete(DeviceExtension->ScratchContext.ScratchRequest); - DeviceExtension->ScratchContext.ScratchRequest = NULL; - } - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -ScratchBuffer_Allocate( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - allocate resources allocated for scratch. - -Arguments: - - DeviceExtension - device extension - -Return Value: - - none - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE (); - - NT_ASSERT(DeviceExtension->ScratchContext.ScratchInUse == 0); - - // quick-exit if already allocated - if ((DeviceExtension->ScratchContext.ScratchBuffer != NULL) && - (DeviceExtension->ScratchContext.ScratchBufferMdl != NULL) && - (DeviceExtension->ScratchContext.ScratchBufferSize != 0) && - (DeviceExtension->ScratchContext.ScratchRequest != NULL) && - (DeviceExtension->ScratchContext.ScratchSrb != NULL) && - (DeviceExtension->ScratchContext.ScratchHistory != NULL) && - (DeviceExtension->ScratchContext.PartialMdl != NULL) - ) - { - return TRUE; - } - - // validate max transfer already determined - NT_ASSERT(DeviceExtension->DeviceAdditionalData.MaxPageAlignedTransferBytes != 0); - - // validate no partially-saved state - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBuffer == NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBufferMdl == NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBufferSize == 0); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchRequest == NULL); - NT_ASSERT(DeviceExtension->ScratchContext.PartialMdl == NULL); - - // limit the scratch buffer to between 4k and 64k (so data length fits into USHORT -- req'd for many commands) - DeviceExtension->ScratchContext.ScratchBufferSize = min(DeviceExtension->DeviceAdditionalData.MaxPageAlignedTransferBytes, (64*1024)); - - // allocate the buffer - if (NT_SUCCESS(status)) - { - DeviceExtension->ScratchContext.ScratchBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, - DeviceExtension->ScratchContext.ScratchBufferSize, - CDROM_TAG_SCRATCH); - if (DeviceExtension->ScratchContext.ScratchBuffer == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch buffer of %x bytes\n", - DeviceExtension->ScratchContext.ScratchBufferSize - )); - } - else if (BYTE_OFFSET(DeviceExtension->ScratchContext.ScratchBuffer) != 0) - { - status = STATUS_INTERNAL_ERROR; - TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_INIT, - "Allocation of %x bytes non-paged pool was not " - "allocated on page boundary? STATUS_INTERNAL_ERROR\n", - DeviceExtension->ScratchContext.ScratchBufferSize - )); - } - } - - // allocate the MDL - if (NT_SUCCESS(status)) - { - DeviceExtension->ScratchContext.ScratchBufferMdl = IoAllocateMdl(DeviceExtension->ScratchContext.ScratchBuffer, - DeviceExtension->ScratchContext.ScratchBufferSize, - FALSE, FALSE, NULL); - if (DeviceExtension->ScratchContext.ScratchBufferMdl == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate MDL for %x byte buffer\n", - DeviceExtension->ScratchContext.ScratchBufferSize - )); - } - else - { - MmBuildMdlForNonPagedPool(DeviceExtension->ScratchContext.ScratchBufferMdl); - } - } - - // create the request - if (NT_SUCCESS(status)) - { - WDF_OBJECT_ATTRIBUTES attributes; - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, - CDROM_REQUEST_CONTEXT); - - status = WdfRequestCreate(&attributes, - DeviceExtension->IoTarget, - &DeviceExtension->ScratchContext.ScratchRequest); - - if ((!NT_SUCCESS(status)) || - (DeviceExtension->ScratchContext.ScratchRequest == NULL)) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch MDL \n")); - } - } - - // allocate the srb - if (NT_SUCCESS(status)) - { - DeviceExtension->ScratchContext.ScratchSrb = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SCSI_REQUEST_BLOCK), - CDROM_TAG_SCRATCH); - - if (DeviceExtension->ScratchContext.ScratchSrb == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch SRB\n")); - } - } - - // allocate the sense buffer - if (NT_SUCCESS(status)) - { - DeviceExtension->ScratchContext.ScratchSense = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SENSE_DATA), - CDROM_TAG_SCRATCH); - - if (DeviceExtension->ScratchContext.ScratchSense == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch sense data\n" - )); - } - } - - // allocate the SRB history data - if (NT_SUCCESS(status)) - { - size_t allocationSize = sizeof(SRB_HISTORY) - sizeof(SRB_HISTORY_ITEM); - allocationSize += 20 * sizeof(SRB_HISTORY_ITEM); - - DeviceExtension->ScratchContext.ScratchHistory = ExAllocatePool2(POOL_FLAG_NON_PAGED, - allocationSize, - CDROM_TAG_SCRATCH); - if (DeviceExtension->ScratchContext.ScratchHistory == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate scratch history buffer\n" - )); - } - else - { - // must be initialized here... - DeviceExtension->ScratchContext.ScratchHistory->TotalHistoryCount = 20; - } - } - - // allocate the MDL - if (NT_SUCCESS(status)) - { - ULONG transferLength = 0; - - status = RtlULongAdd(DeviceExtension->DeviceAdditionalData.MaxPageAlignedTransferBytes, PAGE_SIZE, &transferLength); - if (NT_SUCCESS(status)) - { - DeviceExtension->ScratchContext.PartialMdlIsBuilt = FALSE; - DeviceExtension->ScratchContext.PartialMdl = IoAllocateMdl(NULL, - transferLength, - FALSE, - FALSE, - NULL); - if (DeviceExtension->ScratchContext.PartialMdl == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "Failed to allocate MDL for %x byte buffer\n", - DeviceExtension->ScratchContext.ScratchBufferSize - )); - } - else - { - NT_ASSERT(DeviceExtension->ScratchContext.PartialMdl->Size >= - (CSHORT)(sizeof(MDL) + BYTES_TO_PAGES(DeviceExtension->DeviceAdditionalData.MaxPageAlignedTransferBytes) * sizeof(PFN_NUMBER))); - } - } - else - { - status = STATUS_INTEGER_OVERFLOW; - } - } - - // cleanup on failure - if (!NT_SUCCESS(status)) - { - ScratchBuffer_Deallocate(DeviceExtension); - } - - return NT_SUCCESS(status); -} - - -VOID -ScratchBuffer_ResetItems( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN ResetRequestHistory - ) -/*++ - -Routine Description: - - reset scratch items for reuse. - -Arguments: - - DeviceExtension - device extension - ResetRequestHistory - reset history fields or not - -Return Value: - - none - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDF_REQUEST_REUSE_PARAMS reuseParams; - PIRP irp = NULL; - - NT_ASSERT(DeviceExtension->ScratchContext.ScratchHistory != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchSense != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchSrb != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchRequest != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBufferSize != 0); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBuffer != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchBufferMdl != NULL); - NT_ASSERT(DeviceExtension->ScratchContext.ScratchInUse != 0); - - irp = WdfRequestWdmGetIrp(DeviceExtension->ScratchContext.ScratchRequest); - - if (ResetRequestHistory) - { - PSRB_HISTORY history = DeviceExtension->ScratchContext.ScratchHistory; - RtlZeroMemory(history->History, sizeof(SRB_HISTORY_ITEM) * history->TotalHistoryCount); - history->ClassDriverUse[0] = 0; - history->ClassDriverUse[1] = 0; - history->ClassDriverUse[2] = 0; - history->ClassDriverUse[3] = 0; - history->UsedHistoryCount = 0; - } - - // re-use the KMDF request object - - // deassign the MdlAddress, this is the value we assign explicitly. - // this is to prevent WdfRequestReuse to release the Mdl unexpectly. - if (irp->MdlAddress) - { - irp->MdlAddress = NULL; - } - - WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_NOT_SUPPORTED); - status = WdfRequestReuse(DeviceExtension->ScratchContext.ScratchRequest, &reuseParams); - // WDF request to format the request befor sending it - if (NT_SUCCESS(status)) - { - // clean up completion routine. - WdfRequestSetCompletionRoutine(DeviceExtension->ScratchContext.ScratchRequest, NULL, NULL); - - status = WdfIoTargetFormatRequestForInternalIoctlOthers(DeviceExtension->IoTarget, - DeviceExtension->ScratchContext.ScratchRequest, - IOCTL_SCSI_EXECUTE_IN, - NULL, NULL, - NULL, NULL, - NULL, NULL); - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "ScratchBuffer_ResetItems: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n", - status)); - } - } - - RtlZeroMemory(DeviceExtension->ScratchContext.ScratchSense, sizeof(SENSE_DATA)); - RtlZeroMemory(DeviceExtension->ScratchContext.ScratchSrb, sizeof(SCSI_REQUEST_BLOCK)); - - return; -} - - -NTSTATUS -ScratchBuffer_PerformNextReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN FirstTry - ) -/*++ - -Routine Description: - - This function asynchronously sends the next read/write SRB down the stack. - -Arguments: - - DeviceExtension - Device extension - -Return Value: - - none - ---*/ -{ - PCDROM_SCRATCH_READ_WRITE_CONTEXT readWriteContext = &DeviceExtension->ScratchContext.ScratchReadWriteContext; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(DeviceExtension->ScratchContext.ScratchRequest); - WDFREQUEST originalRequest = requestContext->OriginalRequest; - NTSTATUS status = STATUS_SUCCESS; - - ULONG transferSize; - BOOLEAN usePartialMdl; - - transferSize = min((readWriteContext->EntireXferLen - readWriteContext->TransferedBytes), readWriteContext->MaxLength); - - if (FirstTry) - { - DeviceExtension->ScratchContext.NumRetries = 0; - } - - ScratchBuffer_ResetItems(DeviceExtension, FALSE); - - usePartialMdl = (readWriteContext->PacketsCount > 1 || readWriteContext->TransferedBytes > 0); - - ScratchBuffer_SetupReadWriteSrb(DeviceExtension, - originalRequest, - readWriteContext->StartingOffset, - transferSize, - readWriteContext->DataBuffer, - readWriteContext->IsRead, - usePartialMdl - ); - - WdfRequestSetCompletionRoutine(DeviceExtension->ScratchContext.ScratchRequest, - ScratchBuffer_ReadWriteCompletionRoutine, DeviceExtension); - - status = ScratchBuffer_SendSrb(DeviceExtension, FALSE, (FirstTry ? &readWriteContext->SrbHistoryItem : NULL)); - - return status; -} - - -VOID -ScratchBuffer_ReadWriteTimerRoutine( - struct _KDPC *Dpc, - PVOID DeferredContext, - PVOID SystemArgument1, - PVOID SystemArgument2 - ) -/*++ - -Routine Description: - - Timer routine for retrying read and write requests. - -Arguments: - - Timer - WDF timer - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = NULL; - PCDROM_SCRATCH_READ_WRITE_CONTEXT readWriteContext = NULL; - WDFREQUEST originalRequest = NULL; - PCDROM_REQUEST_CONTEXT requestContext = NULL; - NTSTATUS status = STATUS_SUCCESS; - KIRQL oldIrql; - - UNREFERENCED_PARAMETER(Dpc); - UNREFERENCED_PARAMETER(SystemArgument1); - UNREFERENCED_PARAMETER(SystemArgument2); - - if (DeferredContext == NULL) - { - // This is impossible, but definition of KDEFERRED_ROUTINE allows optional argument, - // and thus OACR will complain. - - return; - } - - originalRequest = (WDFREQUEST) DeferredContext; - requestContext = RequestGetContext(originalRequest); - - KeAcquireSpinLock(&requestContext->ReadWriteCancelSpinLock, &oldIrql); - - if (!requestContext->ReadWriteIsCompleted) - { - // As the first step, unregister the cancellation routine - status = WdfRequestUnmarkCancelable(originalRequest); - } - else - { - status = STATUS_CANCELLED; - } - - KeReleaseSpinLock(&requestContext->ReadWriteCancelSpinLock, oldIrql); - - if (status != STATUS_CANCELLED) - { - deviceExtension = requestContext->DeviceExtension; - readWriteContext = &deviceExtension->ScratchContext.ScratchReadWriteContext; - - // We use timer only for retries, that's why the second parameter is always FALSE - status = ScratchBuffer_PerformNextReadWrite(deviceExtension, FALSE); - - if (!NT_SUCCESS(status)) - { - ScratchBuffer_EndUse(deviceExtension); - RequestCompletion(deviceExtension, originalRequest, status, readWriteContext->TransferedBytes); - } - } - - // - // Drop the extra reference - // - WdfObjectDereference(originalRequest); -} - - -EVT_WDF_REQUEST_CANCEL ScratchBuffer_ReadWriteEvtRequestCancel; - -VOID -ScratchBuffer_ReadWriteEvtRequestCancel( - _In_ WDFREQUEST Request - ) -/*++ - -Routine Description: - - Cancels a request waiting for the read/write timer to expire. This function does not - support cancellation of requests that have already been sent down. - -Arguments: - - Request - WDF request - -Return Value: - - none - ---*/ -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - PCDROM_DEVICE_EXTENSION deviceExtension = requestContext->DeviceExtension; - PCDROM_SCRATCH_READ_WRITE_CONTEXT readWriteContext = &deviceExtension->ScratchContext.ScratchReadWriteContext; - KIRQL oldIrql; - - KeAcquireSpinLock(&requestContext->ReadWriteCancelSpinLock, &oldIrql); - - if (KeCancelTimer(&requestContext->ReadWriteTimer)) - { - // - // Timer is canceled, we own the request. Drop the reference we took before - // queueing the timer. - // - WdfObjectDereference(Request); - } - else - { - // - // Timer will run and drop the reference but it won't complete the request - // because we set IsCompleted to TRUE - // - } - - requestContext->ReadWriteIsCompleted = TRUE; - - KeReleaseSpinLock(&requestContext->ReadWriteCancelSpinLock, oldIrql); - - ScratchBuffer_EndUse(deviceExtension); - - // If WdfTimerStop returned TRUE, it means this request was scheduled for a retry - // and the retry has not happened yet. We just need to cancel it and release the scratch buffer. - RequestCompletion(deviceExtension, Request, STATUS_CANCELLED, readWriteContext->TransferedBytes); -} - -VOID -ScratchBuffer_ReadWriteCompletionRoutine( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS Params, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - Read/write request completion routine. - -Arguments: - Request - WDF request - Target - The IO target the request was completed by. - Params - the request completion parameters - Context - context - -Return Value: - - none - ---*/ -{ - PCDROM_DEVICE_EXTENSION deviceExtension = (PCDROM_DEVICE_EXTENSION) Context; - PCDROM_SCRATCH_READ_WRITE_CONTEXT readWriteContext = &deviceExtension->ScratchContext.ScratchReadWriteContext; - NTSTATUS status = STATUS_SUCCESS; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(deviceExtension->ScratchContext.ScratchRequest); - WDFREQUEST originalRequest = requestContext->OriginalRequest; - - if (!NT_SUCCESS(WdfRequestGetStatus(Request))) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, - "WdfRequestSend: %lx\n", - WdfRequestGetStatus(Request) - )); - } - - UNREFERENCED_PARAMETER(Params); - UNREFERENCED_PARAMETER(Target); - - // We are not calling ScratchBuffer_BeginUse / ScratchBuffer_EndUse in this function, because we already own - // the scratch buffer if this function is being called. - - if ((deviceExtension->ScratchContext.ScratchSrb->SrbStatus == SRB_STATUS_ABORTED) && - (deviceExtension->ScratchContext.ScratchSrb->InternalStatus == STATUS_CANCELLED)) - { - // The request has been cancelled, just need to complete it - } - else if (SRB_STATUS(deviceExtension->ScratchContext.ScratchSrb->SrbStatus) != SRB_STATUS_SUCCESS) - { - // The SCSI command that we sent down has failed, retry it if necessary - BOOLEAN shouldRetry = TRUE; - LONGLONG retryIn100nsUnits = 0; - - shouldRetry = RequestSenseInfoInterpretForScratchBuffer(deviceExtension, - deviceExtension->ScratchContext.NumRetries, - &status, - &retryIn100nsUnits); - - if (shouldRetry) - { - deviceExtension->ScratchContext.NumRetries++; - - if (retryIn100nsUnits == 0) - { - // We take a shortcut here by calling ScratchBuffer_PerformNextReadWrite directly: - // this helps to avoid unnecessary context switch. - status = ScratchBuffer_PerformNextReadWrite(deviceExtension, FALSE); - - if (NT_SUCCESS(status)) - { - // We're not done with the request yet, no need to complete it now - return; - } - } - else - { - PCDROM_REQUEST_CONTEXT originalRequestContext = RequestGetContext(originalRequest); - KIRQL oldIrql; - - // - // Initialize the spin lock and timer local to the original request. - // - if (!originalRequestContext->ReadWriteRetryInitialized) - { - KeInitializeSpinLock(&originalRequestContext->ReadWriteCancelSpinLock); - KeInitializeTimer(&originalRequestContext->ReadWriteTimer); - KeInitializeDpc(&originalRequestContext->ReadWriteDpc, ScratchBuffer_ReadWriteTimerRoutine, originalRequest); - originalRequestContext->ReadWriteRetryInitialized = TRUE; - } - - KeAcquireSpinLock(&requestContext->ReadWriteCancelSpinLock, &oldIrql); - - status = WdfRequestMarkCancelableEx(originalRequest, ScratchBuffer_ReadWriteEvtRequestCancel); - - if (status == STATUS_CANCELLED) - { - requestContext->ReadWriteIsCompleted = TRUE; - - KeReleaseSpinLock(&requestContext->ReadWriteCancelSpinLock, oldIrql); - } - else - { - LARGE_INTEGER t; - - t.QuadPart = -retryIn100nsUnits; - - WdfObjectReference(originalRequest); - - // Use negative time to indicate that we want a relative delay - KeSetTimer(&originalRequestContext->ReadWriteTimer, - t, - &originalRequestContext->ReadWriteDpc - ); - - KeReleaseSpinLock(&requestContext->ReadWriteCancelSpinLock, oldIrql); - - return; - } - } - } - } - else - { - // The SCSI command has succeeded - readWriteContext->DataBuffer += deviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - readWriteContext->StartingOffset.QuadPart += deviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - readWriteContext->TransferedBytes += deviceExtension->ScratchContext.ScratchSrb->DataTransferLength; - readWriteContext->PacketsCount--; - - // Update the SRB history item - if (readWriteContext->SrbHistoryItem) - { - ULONG senseSize; - - // Query the tick count and store in the history - KeQueryTickCount(&readWriteContext->SrbHistoryItem->TickCountCompleted); - - // Copy the SRB Status... - readWriteContext->SrbHistoryItem->SrbStatus = deviceExtension->ScratchContext.ScratchSrb->SrbStatus; - - // Determine the amount of valid sense data - if (deviceExtension->ScratchContext.ScratchSrb->SenseInfoBufferLength >= - RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength)) - { - PSENSE_DATA sense = (PSENSE_DATA)deviceExtension->ScratchContext.ScratchSrb->SenseInfoBuffer; - senseSize = RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength) + - sense->AdditionalSenseLength; - senseSize = min(senseSize, sizeof(SENSE_DATA)); - } - else - { - senseSize = deviceExtension->ScratchContext.ScratchSrb->SenseInfoBufferLength; - } - - // Normalize the sense data copy in the history - RtlZeroMemory(&(readWriteContext->SrbHistoryItem->NormalizedSenseData), sizeof(SENSE_DATA)); - RtlCopyMemory(&(readWriteContext->SrbHistoryItem->NormalizedSenseData), - deviceExtension->ScratchContext.ScratchSrb->SenseInfoBuffer, senseSize); - } - - // Check whether we need to send more SCSI commands to complete the request - if (readWriteContext->PacketsCount > 0) - { - status = ScratchBuffer_PerformNextReadWrite(deviceExtension, TRUE); - - if (NT_SUCCESS(status)) - { - // We're not done with the request yet, no need to complete it now - return; - } - } - } - - ScratchBuffer_EndUse(deviceExtension); - - - RequestCompletion(deviceExtension, originalRequest, status, readWriteContext->TransferedBytes); -} - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScratchBuffer_SetupSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ ULONG MaximumTransferLength, - _In_ BOOLEAN GetDataFromDevice - ) -/*++ - -Routine Description: - - setup scratch SRB for sending out. - -Arguments: - - DeviceExtension - device extension - OriginalRequest - original request delivered by WDF - MaximumTransferLength - transfer length - GetDataFromDevice - TRUE (get data from device); FALSE (send data to device) - -Return Value: - - none - ---*/ -{ - WDFREQUEST request = DeviceExtension->ScratchContext.ScratchRequest; - PIRP irp = WdfRequestWdmGetIrp(request); - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PIO_STACK_LOCATION irpStack = NULL; - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(request); - - PAGED_CODE (); - - requestContext->OriginalRequest = OriginalRequest; - - // set to use the full scratch buffer via the scratch SRB - irpStack = IoGetNextIrpStackLocation(irp); - irpStack->MajorFunction = IRP_MJ_SCSI; - if (MaximumTransferLength == 0) - { - irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_NONE; - } - else if (GetDataFromDevice) - { - irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_IN; - } - else - { - irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_OUT; - } - irpStack->Parameters.Scsi.Srb = srb; - - if (MaximumTransferLength > 0) - { - // the Irp must show the MDL's address for the transfer - irp->MdlAddress = DeviceExtension->ScratchContext.ScratchBufferMdl; - - srb->DataBuffer = DeviceExtension->ScratchContext.ScratchBuffer; - } - - // prepare the SRB with default values - srb->Length = SCSI_REQUEST_BLOCK_SIZE; - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - srb->SrbStatus = 0; - srb->ScsiStatus = 0; - srb->NextSrb = NULL; - srb->OriginalRequest = irp; - srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE; - srb->SenseInfoBuffer = DeviceExtension->ScratchContext.ScratchSense; - - srb->CdbLength = 16; // to cause failures if not set correctly -- CD devices limited to 12 bytes for now... - - srb->DataTransferLength = min(DeviceExtension->ScratchContext.ScratchBufferSize, MaximumTransferLength); - srb->TimeOutValue = DeviceExtension->TimeOutValue; - srb->SrbFlags = DeviceExtension->SrbFlags; - SET_FLAG(srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER); - SET_FLAG(srb->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); - - if (MaximumTransferLength == 0) - { - SET_FLAG(srb->SrbFlags, SRB_FLAGS_NO_DATA_TRANSFER); - } - else if (GetDataFromDevice) - { - SET_FLAG(srb->SrbFlags, SRB_FLAGS_DATA_IN); - } - else - { - SET_FLAG(srb->SrbFlags, SRB_FLAGS_DATA_OUT); - } -} - - -NTSTATUS -ScratchBuffer_SendSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN SynchronousSrb, - _When_(SynchronousSrb, _Pre_null_) - _When_(!SynchronousSrb, _In_opt_) - PSRB_HISTORY_ITEM *SrbHistoryItem - ) -/*++ - -Routine Description: - - Send the command from the scratch SRB to lower driver and retry if necessary. - -Arguments: - - DeviceExtension - device extension - SynchronousSrb - indicates whether the SRB needs to be sent synchronously or nor - SrbHistoryItem - storage for SRB history item, if this is an asynchronous request - -Return Value: - - none - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PSRB_HISTORY history = DeviceExtension->ScratchContext.ScratchHistory; - PSRB_HISTORY_ITEM item = NULL; - BOOLEAN requestCancelled = FALSE; - - srb->InternalStatus = 0; - srb->SrbStatus = 0; - - // allocate/update history pre-command, if it is a synchronous request or we were supplied - // with a storage for the history item - if (SynchronousSrb || SrbHistoryItem != NULL) - { - // sending a packet implies a new history unit is to be used. - NT_ASSERT( history->UsedHistoryCount <= history->TotalHistoryCount ); - - // if already all used up, remove at least one history unit - if (history->UsedHistoryCount == history->TotalHistoryCount ) - { - CompressSrbHistoryData(history); - NT_ASSERT( history->UsedHistoryCount < history->TotalHistoryCount ); - } - - // thus, since we are about to increment the count, it must now be less... - NT_ASSERT( history->UsedHistoryCount < history->TotalHistoryCount ); - - // increment the number of history units in use - history->UsedHistoryCount++; - - // determine index to use - item = &( history->History[ history->UsedHistoryCount-1 ] ); - - if (SrbHistoryItem != NULL) - { - *SrbHistoryItem = item; - } - - // zero out the history item - RtlZeroMemory(item, sizeof(SRB_HISTORY_ITEM)); - - // Query the tick count and store in the history - KeQueryTickCount(&item->TickCountSent); - } - - // get cancellation status; - { - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(DeviceExtension->ScratchContext.ScratchRequest); - - if (requestContext->OriginalRequest != NULL) - { - requestCancelled = WdfRequestIsCanceled(requestContext->OriginalRequest); - } - } - - if (!requestCancelled) - { - status = RequestSend(DeviceExtension, - DeviceExtension->ScratchContext.ScratchRequest, - DeviceExtension->IoTarget, - SynchronousSrb ? WDF_REQUEST_SEND_OPTION_SYNCHRONOUS : 0, - NULL); - - // If this is a synchronous request, update the history item immediately, including "normalized" sense data - if (SynchronousSrb) - { - ULONG senseSize; - - // Query the tick count and store in the history - KeQueryTickCount(&item->TickCountCompleted); - - // Copy the SRB Status - item->SrbStatus = srb->SrbStatus; - - // Determine the amount of valid sense data - if (srb->SenseInfoBufferLength >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength)) - { - PSENSE_DATA sense = (PSENSE_DATA)srb->SenseInfoBuffer; - senseSize = RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength) + - sense->AdditionalSenseLength; - senseSize = min(senseSize, sizeof(SENSE_DATA)); - } - else - { - senseSize = srb->SenseInfoBufferLength; - } - - // Normalize the sense data copy in the history - RtlZeroMemory(&(item->NormalizedSenseData), sizeof(SENSE_DATA)); - RtlCopyMemory(&(item->NormalizedSenseData), srb->SenseInfoBuffer, senseSize); - } - } - else - { - DeviceExtension->ScratchContext.ScratchSrb->SrbStatus = SRB_STATUS_ABORTED; - DeviceExtension->ScratchContext.ScratchSrb->InternalStatus = (ULONG)STATUS_CANCELLED; - status = STATUS_CANCELLED; - } - - return status; -} - -VOID -CompressSrbHistoryData( - _Inout_ PSRB_HISTORY RequestHistory - ) -/*++ - -Routine Description: - - compress the SRB history data. - -Arguments: - - RequestHistory - SRB history data - -Return Value: - - RequestHistory - compressed history data - ---*/ -{ - ULONG i; - NT_ASSERT( RequestHistory->UsedHistoryCount == RequestHistory->TotalHistoryCount ); - ValidateSrbHistoryDataPresumptions(RequestHistory); - - for (i=0; i < RequestHistory->UsedHistoryCount; i++) - { - // for each item... - PSRB_HISTORY_ITEM toMatch = &( RequestHistory->History[i] ); - // hint: read const qualifiers backwards. i.e. srbstatus is a const UCHAR - // so, "UCHAR const * const x" is read "x is a const pointer to a const UCHAR" - // unfortunately, "const UCHAR" is equivalent to "UCHAR const", which causes - // people no end of confusion due to its widespread use. - UCHAR const srbStatus = toMatch->SrbStatus; - UCHAR const sense = toMatch->NormalizedSenseData.SenseKey; - UCHAR const asc = toMatch->NormalizedSenseData.AdditionalSenseCode; - UCHAR const ascq = toMatch->NormalizedSenseData.AdditionalSenseCodeQualifier; - ULONG j; - - // see if there are any at higher indices with identical Sense/ASC/ASCQ - for (j = i+1; (toMatch->ClassDriverUse != 0xFF) && (j < RequestHistory->UsedHistoryCount); j++) - { - PSRB_HISTORY_ITEM found = &( RequestHistory->History[j] ); - // close enough match? - if ((srbStatus == found->SrbStatus) && - (sense == found->NormalizedSenseData.SenseKey) && - (asc == found->NormalizedSenseData.AdditionalSenseCode) && - (ascq == found->NormalizedSenseData.AdditionalSenseCodeQualifier)) { - - // add the fields to keep reasonable track of delay times. - if (toMatch->MillisecondsDelayOnRetry + found->MillisecondsDelayOnRetry < toMatch->MillisecondsDelayOnRetry) { - toMatch->MillisecondsDelayOnRetry = MAXULONG; - } else { - toMatch->MillisecondsDelayOnRetry += found->MillisecondsDelayOnRetry; - } - - // this found item cannot contain any compressed entries because - // the first entry with a given set of sense/asc/ascq will always - // either be full (0xFF) or be the only partially-full entry with - // that sense/asc/ascq. - NT_ASSERT(found->ClassDriverUse == 0); - // add the counts so we still know how many retries total - toMatch->ClassDriverUse++; - - - // if not the last entry, need to move later entries earlier in the array - if (j != RequestHistory->UsedHistoryCount-1) { - // how many entries remain? - SIZE_T remainingBytes = RequestHistory->UsedHistoryCount - 1 - j; - remainingBytes *= sizeof(SRB_HISTORY_ITEM); - - // note that MOVE is required due to overlapping entries - RtlMoveMemory(found, found+1, remainingBytes); - - // Finally, decrement the number of used history count and - // decrement j to rescan the current location again - --RequestHistory->UsedHistoryCount; - --j; - } // end moving of array elements around - } // end of close enough match - } // end j loop - } // end i loop - - // unable to compress duplicate sense/asc/ascq, so just lose the most recent data - if (RequestHistory->UsedHistoryCount == RequestHistory->TotalHistoryCount) - { - PSRB_HISTORY_ITEM item = &( RequestHistory->History[ RequestHistory->TotalHistoryCount-1 ] ); - RequestHistory->ClassDriverUse[0] += item->ClassDriverUse; // how many did we "lose"? - RequestHistory->UsedHistoryCount--; - } - - // finally, zero any that are no longer in use - NT_ASSERT( RequestHistory->UsedHistoryCount != RequestHistory->TotalHistoryCount); - { - SIZE_T bytesToZero = RequestHistory->TotalHistoryCount - RequestHistory->UsedHistoryCount; - bytesToZero *= sizeof(SRB_HISTORY_ITEM); - RtlZeroMemory(&(RequestHistory->History[RequestHistory->UsedHistoryCount]), bytesToZero); - } - - ValidateSrbHistoryDataPresumptions(RequestHistory); - return; -} - -VOID -ValidateSrbHistoryDataPresumptions( - _In_ SRB_HISTORY const * RequestHistory - ) -{ -#if DBG - // validate that all fully-compressed items are before any non-fully-compressed items of any particular sense/asc/ascq - // validate that there is at most one partially-compressed item of any particular sense/asc/ascq - // validate that all items of any particular sense/asc/ascq that are uncompressed are at the end - // THUS: A(255) A(255) A( 40) A( 0) A( 0) is legal for all types with A as sense/asc/ascq - // A(0) B(255) A( 0) B( 17) B( 0) is also legal because A/B are different types of error - - ULONG i; - for (i = 0; i < RequestHistory->UsedHistoryCount; i++) - { - SRB_HISTORY_ITEM const * toMatch = &( RequestHistory->History[i] ); - UCHAR const srbStatus = toMatch->SrbStatus; - UCHAR const sense = toMatch->NormalizedSenseData.SenseKey; - UCHAR const asc = toMatch->NormalizedSenseData.AdditionalSenseCode; - UCHAR const ascq = toMatch->NormalizedSenseData.AdditionalSenseCodeQualifier; - ULONG j; - - BOOLEAN foundPartiallyCompressedItem = - (toMatch->ClassDriverUse != 0) && - (toMatch->ClassDriverUse != 0xFF) ; - BOOLEAN foundUncompressedItem = - (toMatch->ClassDriverUse == 0) ; - - for (j = i+1; j < RequestHistory->UsedHistoryCount; j++) - { - SRB_HISTORY_ITEM const * found = &( RequestHistory->History[j] ); - if ((srbStatus == found->SrbStatus) && - (sense == found->NormalizedSenseData.SenseKey) && - (asc == found->NormalizedSenseData.AdditionalSenseCode) && - (ascq == found->NormalizedSenseData.AdditionalSenseCodeQualifier) - ) - { - // found a matching type, so validate ordering rules - if (foundUncompressedItem && (found->ClassDriverUse != 0)) - { - DbgPrintEx(DPFLTR_CDROM_ID, DPFLTR_ERROR_LEVEL, - "History data has compressed history following uncompressed history " - "for srbstatus/sense/asc/ascq of %02x/%02x/%02x/%02x at indices %d (%08x) and %d (%08x)\n", - srbStatus, sense, asc, ascq, - i,i, j,j - ); - NT_ASSERT(FALSE); - } - else if (foundPartiallyCompressedItem && (found->ClassDriverUse == 0xFF)) - { - DbgPrintEx(DPFLTR_CDROM_ID, DPFLTR_ERROR_LEVEL, - "History data has fully compressed history following partially compressed history " - "for srbstatus/sense/asc/ascq of %02x/%02x/%02x/%02x at indices %d (%08x) and %d (%08x)\n", - srbStatus, sense, asc, ascq, - i,i, j,j - ); - NT_ASSERT(FALSE); - } - - // update if we have now found partially compressed and/or uncompressed items - if (found->ClassDriverUse == 0) - { - foundUncompressedItem = TRUE; - } - else if (found->ClassDriverUse != 0xFF) - { - foundPartiallyCompressedItem = TRUE; - } - } // end match of (toMatch,found) - } // end loop j - } // end loop i -#else - UNREFERENCED_PARAMETER(RequestHistory); -#endif - return; -} - -VOID -ScratchBuffer_SetupReadWriteSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST OriginalRequest, - _In_ LARGE_INTEGER StartingOffset, - _In_ ULONG RequiredLength, - _Inout_updates_bytes_(RequiredLength) UCHAR* DataBuffer, - _In_ BOOLEAN IsReadRequest, - _In_ BOOLEAN UsePartialMdl - ) -/*++ - -Routine Description: - - setup SRB for read/write request. - -Arguments: - - DeviceExtension - device extension - OriginalRequest - read/write request - StartingOffset - read/write starting offset - DataBuffer - buffer for read/write - IsReadRequest - TRUE (read); FALSE (write) - -Return Value: - - none - ---*/ -{ - //NOTE: R/W request not use the ScratchBuffer, instead, it uses the buffer associated with IRP. - - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PCDB cdb = (PCDB)srb->Cdb; - LARGE_INTEGER logicalBlockAddr; - ULONG numTransferBlocks; - - PIRP originalIrp = WdfRequestWdmGetIrp(OriginalRequest); - - PIRP irp = WdfRequestWdmGetIrp(DeviceExtension->ScratchContext.ScratchRequest); - PIO_STACK_LOCATION irpStack = NULL; - - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(DeviceExtension->ScratchContext.ScratchRequest); - - requestContext->OriginalRequest = OriginalRequest; - - - logicalBlockAddr.QuadPart = Int64ShrlMod32(StartingOffset.QuadPart, DeviceExtension->SectorShift); - numTransferBlocks = RequiredLength >> DeviceExtension->SectorShift; - - // set to use the full scratch buffer via the scratch SRB - irpStack = IoGetNextIrpStackLocation(irp); - irpStack->MajorFunction = IRP_MJ_SCSI; - if (IsReadRequest) - { - irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_IN; - } - else - { - irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_OUT; - } - irpStack->Parameters.Scsi.Srb = srb; - - // prepare the SRB with default values - srb->Length = SCSI_REQUEST_BLOCK_SIZE; - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->QueueAction = SRB_SIMPLE_TAG_REQUEST; - srb->SrbStatus = 0; - srb->ScsiStatus = 0; - srb->NextSrb = NULL; - srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE; - srb->SenseInfoBuffer = DeviceExtension->ScratchContext.ScratchSense; - - srb->DataBuffer = DataBuffer; - srb->DataTransferLength = RequiredLength; - - srb->QueueSortKey = logicalBlockAddr.LowPart; - if (logicalBlockAddr.QuadPart > 0xFFFFFFFF) - { - // - // If the requested LBA is more than max ULONG set the - // QueueSortKey to the maximum value, so that these - // requests can be added towards the end of the queue. - // - srb->QueueSortKey = 0xFFFFFFFF; - } - - srb->OriginalRequest = irp; - srb->TimeOutValue = DeviceExtension->TimeOutValue; - - if (RequestIsRealtimeStreaming(OriginalRequest, IsReadRequest) && - !TEST_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_NO_STREAMING)) - { - if (IsReadRequest) - { - RtlZeroMemory(&cdb->READ12, sizeof(cdb->READ12)); - REVERSE_BYTES(&cdb->READ12.LogicalBlock, &logicalBlockAddr.LowPart); - REVERSE_BYTES(&cdb->READ12.TransferLength, &numTransferBlocks); - cdb->READ12.Streaming = 1; - cdb->READ12.OperationCode = SCSIOP_READ12; - srb->CdbLength = sizeof(cdb->READ12); - } - else - { - RtlZeroMemory(&cdb->WRITE12, sizeof(cdb->WRITE12)); - REVERSE_BYTES(&cdb->WRITE12.LogicalBlock, &logicalBlockAddr.LowPart); - REVERSE_BYTES(&cdb->WRITE12.TransferLength, &numTransferBlocks); - cdb->WRITE12.Streaming = 1; - cdb->WRITE12.OperationCode = SCSIOP_WRITE12; - srb->CdbLength = sizeof(cdb->WRITE12); - } - } - else - { - RtlZeroMemory(&cdb->CDB10, sizeof(cdb->CDB10)); - cdb->CDB10.LogicalBlockByte0 = ((PFOUR_BYTE)&logicalBlockAddr.LowPart)->Byte3; - cdb->CDB10.LogicalBlockByte1 = ((PFOUR_BYTE)&logicalBlockAddr.LowPart)->Byte2; - cdb->CDB10.LogicalBlockByte2 = ((PFOUR_BYTE)&logicalBlockAddr.LowPart)->Byte1; - cdb->CDB10.LogicalBlockByte3 = ((PFOUR_BYTE)&logicalBlockAddr.LowPart)->Byte0; - cdb->CDB10.TransferBlocksMsb = ((PFOUR_BYTE)&numTransferBlocks)->Byte1; - cdb->CDB10.TransferBlocksLsb = ((PFOUR_BYTE)&numTransferBlocks)->Byte0; - cdb->CDB10.OperationCode = (IsReadRequest) ? SCSIOP_READ : SCSIOP_WRITE; - srb->CdbLength = sizeof(cdb->CDB10); - } - - // Set SRB and IRP flags - srb->SrbFlags = DeviceExtension->SrbFlags; - if (TEST_FLAG(originalIrp->Flags, IRP_PAGING_IO) || - TEST_FLAG(originalIrp->Flags, IRP_SYNCHRONOUS_PAGING_IO)) - { - SET_FLAG(srb->SrbFlags, SRB_CLASS_FLAGS_PAGING); - } - - SET_FLAG(srb->SrbFlags, (IsReadRequest) ? SRB_FLAGS_DATA_IN : SRB_FLAGS_DATA_OUT); - SET_FLAG(srb->SrbFlags, SRB_FLAGS_ADAPTER_CACHE_ENABLE); - - // - // If the request is not split, we can use the original IRP MDL. If the - // request needs to be split, we need to use a partial MDL. The partial MDL - // is needed because more than one driver might be mapping the same MDL - // and this causes problems. - // - if (UsePartialMdl == FALSE) - { - irp->MdlAddress = originalIrp->MdlAddress; - } - else - { - if (DeviceExtension->ScratchContext.PartialMdlIsBuilt != FALSE) - { - MmPrepareMdlForReuse(DeviceExtension->ScratchContext.PartialMdl); - } - - IoBuildPartialMdl(originalIrp->MdlAddress, DeviceExtension->ScratchContext.PartialMdl, srb->DataBuffer, srb->DataTransferLength); - DeviceExtension->ScratchContext.PartialMdlIsBuilt = TRUE; - irp->MdlAddress = DeviceExtension->ScratchContext.PartialMdl; - } - - //DBGLOGSENDPACKET(Pkt); - //HISTORYLOGSENDPACKET(Pkt); - - // - // Set the original irp here for SFIO. - // - srb->SrbExtension = (PVOID)(originalIrp); - - return; -} - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ScratchBuffer_ExecuteCdbEx( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ ULONG TransferSize, - _In_ BOOLEAN GetDataFromDevice, - _In_ PCDB Cdb, - _In_ UCHAR OprationLength, - _In_ ULONG TimeoutValue - ) -/*++ - -Routine Description: - - Use Scratch buffer to send the Cdb, check error and retry if necessary. - -Arguments: - - DeviceExtension - device context - OriginalRequest - original request that requires this CDB operation - TransferSize - Data transfer size required - GetFromDevice - TRUE if getting data from device. - Cdb - SCSI command - OprationLength - SCSI command length: 6, 10 or 12 - TimeoutValue - if > 0, use it as timeout value for command - if 0, use the default device timeout value - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PSCSI_REQUEST_BLOCK srb = DeviceExtension->ScratchContext.ScratchSrb; - PCDB cdb = (PCDB)(srb->Cdb); - - BOOLEAN shouldRetry = TRUE; - ULONG timesAlreadyRetried = 0; - LONGLONG retryIn100nsUnits = 0; - - PAGED_CODE (); - - while (shouldRetry) - { - ScratchBuffer_SetupSrb(DeviceExtension, OriginalRequest, TransferSize, GetDataFromDevice); - - // Set up the SRB/CDB - RtlCopyMemory(cdb, Cdb, sizeof(CDB)); - - srb->CdbLength = OprationLength; - - if (TimeoutValue > 0) - { - srb->TimeOutValue = TimeoutValue; - } - - ScratchBuffer_SendSrb(DeviceExtension, TRUE, NULL); - - if ((DeviceExtension->ScratchContext.ScratchSrb->SrbStatus == SRB_STATUS_ABORTED) && - (DeviceExtension->ScratchContext.ScratchSrb->InternalStatus == STATUS_CANCELLED)) - { - shouldRetry = FALSE; - status = STATUS_CANCELLED; - } - else - { - shouldRetry = RequestSenseInfoInterpretForScratchBuffer(DeviceExtension, - timesAlreadyRetried, - &status, - &retryIn100nsUnits); - if (shouldRetry) - { - LARGE_INTEGER t; - t.QuadPart = -retryIn100nsUnits; - timesAlreadyRetried++; - KeDelayExecutionThread(KernelMode, FALSE, &t); - // keep items clean - ScratchBuffer_ResetItems(DeviceExtension, FALSE); - } - } - } - - return status; -} - - diff --git a/storage/class/cdrom/src/scratch.h b/storage/class/cdrom/src/scratch.h deleted file mode 100644 index 92d75328f..000000000 --- a/storage/class/cdrom/src/scratch.h +++ /dev/null @@ -1,187 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - mmc.h - -Abstract: - - Functions/macros for using the scratch buffer and scratch request/SRB - in the serial I/O queue context - -Author: - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#ifndef __SCRATCH_H__ -#define __SCRATCH_H__ - - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScratchBuffer_Deallocate( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -_IRQL_requires_max_(APC_LEVEL) -BOOLEAN -ScratchBuffer_Allocate( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension - ); - -VOID -ScratchBuffer_ResetItems( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN ResetRequestHistory - ); - -_IRQL_requires_max_(APC_LEVEL) -VOID -ScratchBuffer_SetupSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ ULONG MaximumTransferLength, - _In_ BOOLEAN GetDataFromDevice - ); - -VOID -ScratchBuffer_SetupReadWriteSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST OriginalRequest, - _In_ LARGE_INTEGER StartingOffset, - _In_ ULONG RequiredLength, - _Inout_updates_bytes_(RequiredLength) UCHAR* DataBuffer, - _In_ BOOLEAN IsReadRequest, - _In_ BOOLEAN UsePartialMdl - ); - -NTSTATUS -ScratchBuffer_SendSrb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN SynchronousSrb, - _When_(SynchronousSrb, _Pre_null_) - _When_(!SynchronousSrb, _In_opt_) - PSRB_HISTORY_ITEM *SrbHistoryItem - ); - -NTSTATUS -ScratchBuffer_PerformNextReadWrite( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN FirstTry - ); - -#if DBG - #define ScratchBuffer_BeginUse(context) ScratchBuffer_BeginUseX((context), __FILE__, __LINE__) -#else - #define ScratchBuffer_BeginUse(context) ScratchBuffer_BeginUseX((context), NULL, (ULONG)-1) -#endif - -__inline VOID ScratchBuffer_BeginUseX(_Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, _In_opt_ LPCSTR File, ULONG Line) -{ - // NOTE: these are not "real" locks. They are simply to help - // avoid multiple uses of the scratch buffer. Thus, it - // is not critical to have atomic operations here. - PVOID tmp = InterlockedCompareExchangePointer((PVOID)&(DeviceExtension->ScratchContext.ScratchInUse), (PVOID)-1, NULL); - NT_ASSERT(tmp == NULL); - UNREFERENCED_PARAMETER(tmp); //defensive coding, avoid PREFAST warning. - DeviceExtension->ScratchContext.ScratchInUseFileName = File; - DeviceExtension->ScratchContext.ScratchInUseLineNumber = Line; - ScratchBuffer_ResetItems(DeviceExtension, TRUE); - RequestClearSendTime(DeviceExtension->ScratchContext.ScratchRequest); - return; -} -__inline VOID ScratchBuffer_EndUse(_Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension) -{ - // NOTE: these are not "real" locks. They are simply to help - // avoid multiple uses of the scratch buffer. Thus, it - // is not critical to have atomic operations here. - - // On lock release, we erase ScratchInUseFileName and ScratchInUseLineNumber _before_ releasing ScratchInUse, - // because otherwise we may erase these after the lock has been acquired again by another thread. We store the - // old values of ScratchInUseFileName and ScratchInUseLineNumber in local variables to facilitate debugging, - // if the ASSERT at the end of the function is hit. - PCSTR scratchInUseFileName; - ULONG scratchInUseLineNumber; - PVOID tmp; - - scratchInUseFileName = DeviceExtension->ScratchContext.ScratchInUseFileName; - scratchInUseLineNumber = DeviceExtension->ScratchContext.ScratchInUseLineNumber; - UNREFERENCED_PARAMETER(scratchInUseFileName); - UNREFERENCED_PARAMETER(scratchInUseLineNumber); - DeviceExtension->ScratchContext.ScratchInUseFileName = NULL; - DeviceExtension->ScratchContext.ScratchInUseLineNumber = 0; - - // - // If we have used the PartialMdl in the scratch context we should notify MM that we will be reusing it - // otherwise it may leak System VA if some one below us has mapped the same. - // - - if (DeviceExtension->ScratchContext.PartialMdlIsBuilt != FALSE) - { - MmPrepareMdlForReuse(DeviceExtension->ScratchContext.PartialMdl); - DeviceExtension->ScratchContext.PartialMdlIsBuilt = FALSE; - } - - tmp = InterlockedCompareExchangePointer((PVOID)&(DeviceExtension->ScratchContext.ScratchInUse), NULL, (PVOID)-1); - NT_ASSERT(tmp == ((PVOID)-1)); - UNREFERENCED_PARAMETER(tmp); //defensive coding, avoid PREFAST warning. - return; -} - -VOID -CompressSrbHistoryData( - _Inout_ PSRB_HISTORY RequestHistory - ); - -VOID -ValidateSrbHistoryDataPresumptions( - _In_ SRB_HISTORY const* RequestHistory - ); - -_IRQL_requires_max_(APC_LEVEL) -NTSTATUS -ScratchBuffer_ExecuteCdbEx( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ ULONG TransferSize, - _In_ BOOLEAN GetDataFromDevice, - _In_ PCDB Cdb, - _In_ UCHAR OprationLength, - _In_ ULONG TimeoutValue - ); - -_IRQL_requires_max_(APC_LEVEL) -__inline -NTSTATUS -ScratchBuffer_ExecuteCdb( - _Inout_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_opt_ WDFREQUEST OriginalRequest, - _In_ ULONG TransferSize, - _In_ BOOLEAN GetDataFromDevice, - _In_ PCDB Cdb, - _In_ UCHAR OprationLength - ) -{ - return ScratchBuffer_ExecuteCdbEx(DeviceExtension, - OriginalRequest, - TransferSize, - GetDataFromDevice, - Cdb, - OprationLength, - 0); -} - -KDEFERRED_ROUTINE ScratchBuffer_ReadWriteTimerRoutine; - -#endif //__SCRATCH_H__ diff --git a/storage/class/cdrom/src/sense.c b/storage/class/cdrom/src/sense.c deleted file mode 100644 index 7033c6ce6..000000000 --- a/storage/class/cdrom/src/sense.c +++ /dev/null @@ -1,2600 +0,0 @@ -/*-- - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - sense.c - -Abstract: - - This file contains the methods needed to accurately - determine how to retry requests on CDROM device types. - -Environment: - - kernel mode only - -Revision History: - ---*/ - -#include "stddef.h" -#include "string.h" - -#include "ntddk.h" -#include "ntddstor.h" -#include "cdrom.h" -#include "ntstrsafe.h" - - -#ifdef DEBUG_USE_WPP -#include "sense.tmh" -#endif - -// Forward declarations -VOID -SenseInfoInterpretRefineByIoControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_ BOOLEAN OverrideVerifyVolume, - _Inout_ BOOLEAN* Retry, - _Inout_ NTSTATUS* Status - ); - - -#ifdef ALLOC_PRAGMA - -#pragma alloc_text(PAGE, SenseInfoInterpretRefineByIoControl) - -#endif - - -// -// FROM CLASSPNP\CLASSP.H -// Lots of retries of synchronized SCSI commands that devices may not -// even support really slows down the system (especially while booting). -// (Even GetDriveCapacity may be failed on purpose if an external disk is powered off). -// If a disk cannot return a small initialization buffer at startup -// in two attempts (with delay interval) then we cannot expect it to return -// data consistently with four retries. -// So don't set the retry counts as high here as for data SRBs. -// -// If we find that these requests are failing consecutively, -// despite the retry interval, on otherwise reliable media, -// then we should either increase the retry interval for -// that failure or (by all means) increase these retry counts as appropriate. -// - -#define TOTAL_COUNT_RETRY_DEFAULT 4 -#define TOTAL_COUNT_RETRY_LOCK_MEDIA 1 -#define TOTAL_COUNT_RETRY_MODESENSE 1 -#define TOTAL_COUNT_RETRY_READ_CAPACITY 1 - - -#define TOTAL_SECONDS_RETRY_TIME_WRITE 160 -#define TOTAL_SECONDS_RETRY_TIME_MEDIUM_REMOVAL 120 - -typedef struct _ERROR_LOG_CONTEXT { - BOOLEAN LogError; - BOOLEAN ErrorUnhandled; - NTSTATUS ErrorCode; - ULONG UniqueErrorValue; - ULONG BadSector; -} ERROR_LOG_CONTEXT, *PERROR_LOG_CONTEXT; - -NTSTATUS -DeviceErrorHandlerForMmc( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Inout_ PNTSTATUS Status, - _Inout_ PBOOLEAN Retry - ) -/*++ - -Routine Description: - - this routine will be used for error handler for all MMC devices. - it's invoked by DeviceErrorHandler()that invoked by SenseInfoInterpret() or GESN - - This routine just checks for media change sense/asc/ascq and - also for other events, such as bus resets. this is used to - determine if the device behaviour has changed, to allow for - read and write operations to be allowed and/or disallowed. - -Arguments: - - DeviceExtension - device context - Srb - SRB structure for analyze - -Return Value: - - NTSTATUS - Status - - Retry - - ---*/ -{ - BOOLEAN mediaChange = FALSE; - PCDB cdb = (PCDB)Srb->Cdb; - - if (TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) - { - PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer; - - // the following sense keys could indicate a change in capabilities. - - // we used to expect this to be serialized, and only hit from our - // own routine. we now allow some requests to continue during our - // processing of the capabilities update in order to allow - // IoReadPartitionTable() to succeed. - switch (senseBuffer->SenseKey & 0xf) - { - - case SCSI_SENSE_NOT_READY: - { - if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_NO_MEDIA_IN_DEVICE) - { - if (DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: media removed, writes will be " - "failed until new media detected\n")); - } - - // NOTE - REF #0002 - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - } - else if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY) - { - if (senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_BECOMING_READY) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: media becoming ready, " - "SHOULD notify shell of change time by sending " - "GESN request immediately!\n")); - } - else if (((senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_OPERATION_IN_PROGRESS) || - (senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_LONG_WRITE_IN_PROGRESS) - ) && - ((Srb->Cdb[0] == SCSIOP_READ) || - (Srb->Cdb[0] == SCSIOP_READ6) || - (Srb->Cdb[0] == SCSIOP_READ_CAPACITY) || - (Srb->Cdb[0] == SCSIOP_READ_CD) || - (Srb->Cdb[0] == SCSIOP_READ_CD_MSF) || - (Srb->Cdb[0] == SCSIOP_READ_TOC) || - (Srb->Cdb[0] == SCSIOP_WRITE) || - (Srb->Cdb[0] == SCSIOP_WRITE6) || - (Srb->Cdb[0] == SCSIOP_READ_TRACK_INFORMATION) || - (Srb->Cdb[0] == SCSIOP_READ_DISK_INFORMATION) - ) - ) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: LONG_WRITE or " - "OP_IN_PROGRESS for limited subset of cmds -- " - "setting retry to TRUE\n")); - *Retry = TRUE; - *Status = STATUS_DEVICE_BUSY; - } - } - break; - } // end SCSI_SENSE_NOT_READY - - case SCSI_SENSE_UNIT_ATTENTION: - { - switch (senseBuffer->AdditionalSenseCode) - { - case SCSI_ADSENSE_MEDIUM_CHANGED: - { - // always update if the medium may have changed - - // NOTE - REF #0002 - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.UpdateState = CdromMmcUpdateRequired; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: media change detected, need to " - "update drive capabilities\n")); - mediaChange = TRUE; - break; - - } // end SCSI_ADSENSE_MEDIUM_CHANGED - - case SCSI_ADSENSE_BUS_RESET: - { - // NOTE - REF #0002 - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.UpdateState = CdromMmcUpdateRequired; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: bus reset detected, need to " - "update drive capabilities\n")); - break; - - } // end SCSI_ADSENSE_BUS_RESET - - case SCSI_ADSENSE_OPERATOR_REQUEST: - { - - BOOLEAN b = FALSE; - - switch (senseBuffer->AdditionalSenseCodeQualifier) - { - case SCSI_SENSEQ_MEDIUM_REMOVAL: - { - // eject notification currently handled by classpnp - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: Eject requested by user\n")); - *Retry = TRUE; - *Status = STATUS_DEVICE_BUSY; - break; - } - - case SCSI_SENSEQ_WRITE_PROTECT_DISABLE: - b = TRUE; - case SCSI_SENSEQ_WRITE_PROTECT_ENABLE: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: Write protect %s requested " - "by user\n", - (b ? "disable" : "enable"))); - *Retry = TRUE; - *Status = STATUS_DEVICE_BUSY; - // NOTE - REF #0002 - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - DeviceExtension->DeviceAdditionalData.Mmc.UpdateState = CdromMmcUpdateRequired; - - break; - } - - } // end of AdditionalSenseCodeQualifier switch - - - break; - - } // end SCSI_ADSENSE_OPERATOR_REQUEST - - default: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: Unit attention %02x/%02x\n", - senseBuffer->AdditionalSenseCode, - senseBuffer->AdditionalSenseCodeQualifier)); - break; - } - - } // end of AdditionSenseCode switch - break; - - } // end SCSI_SENSE_UNIT_ATTENTION - - case SCSI_SENSE_ILLEGAL_REQUEST: - { - if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_WRITE_PROTECT) - { - if (DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: media was writable, but " - "failed request with WRITE_PROTECT error...\n")); - } - // NOTE - REF #0002 - // do not update all the capabilities just because - // we can't write to the disc. - DeviceExtension->DeviceAdditionalData.Mmc.WriteAllowed = FALSE; - } - break; - } // end SCSI_SENSE_ILLEGAL_REQUEST - - } // end of SenseKey switch - - // Check if we failed to set the DVD region key and send appropriate error - if (cdb->CDB16.OperationCode == SCSIOP_SEND_KEY) - { - if (cdb->SEND_KEY.KeyFormat == DvdSetRpcKey) - { - if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_NO_MEDIA_IN_DEVICE) - { - // media of appropriate region required - *Status = STATUS_NO_MEDIA_IN_DEVICE; - *Retry = FALSE; - } - else if ((senseBuffer->SenseKey == SCSI_SENSE_ILLEGAL_REQUEST) && - (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_COPY_PROTECTION_FAILURE) && - (senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_MEDIA_CODE_MISMATCHED_TO_LOGICAL_UNIT)) - { - // media of appropriate region required - *Status = STATUS_CSS_REGION_MISMATCH; - *Retry = FALSE; - } - else if ((senseBuffer->SenseKey == SCSI_SENSE_ILLEGAL_REQUEST) && - (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_INVALID_MEDIA) && - (senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_INCOMPATIBLE_FORMAT)) - { - // media of appropriate region required - *Status = STATUS_CSS_REGION_MISMATCH; - *Retry = FALSE; - } - } - } - } // end of SRB_STATUS_AUTOSENSE_VALID - - // On media change, if device speed should be reset to default then - // queue a workitem to send the commands to the device. Do this on - // media arrival as some device will fail this command if no media - // is present. Ignore the fake media change from classpnp driver. - if ((mediaChange == TRUE) && (*Status != STATUS_MEDIA_CHANGED)) - { - if (DeviceExtension->DeviceAdditionalData.RestoreDefaults == TRUE) - { - NTSTATUS status = STATUS_SUCCESS; - WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; - WDFWORKITEM workItem; - - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = DeviceExtension->Device; - - WDF_WORKITEM_CONFIG_INIT(&workitemConfig, - DeviceRestoreDefaultSpeed); - - status = WdfWorkItemCreate(&workitemConfig, - &attributes, - &workItem); - if (!NT_SUCCESS(status)) - { - return STATUS_SUCCESS; - } - - WdfWorkItemEnqueue(workItem); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForMmc: Restore device default speed for %p\n", - DeviceExtension->DeviceObject)); - } - } - return STATUS_SUCCESS; -} - -NTSTATUS -DeviceErrorHandlerForHitachiGD2000( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Inout_ PNTSTATUS Status, - _Inout_ PBOOLEAN Retry - ) -/*++ - -Routine Description: - - error handler for HITACHI CDR-1750S, CDR-3650/1650S - - This routine checks the type of error. If the error suggests that the - drive has spun down and cannot reinitialize itself, send a - START_UNIT or READ to the device. This will force the drive to spin - up. This drive also loses the AGIDs it has granted when it spins down, - which may result in playback failure the first time around. - -Arguments: - - DeviceExtension - the device object. - - Srb - Supplies a pointer to the failing Srb. - - Status - return the final status for this command? - - Retry - return if the command should be retried. - -Return Value: - - None. - ---*/ -{ - PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer; - - if (!TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) - { - return STATUS_SUCCESS; //nobody cares about this return value yet. - } - - if (((senseBuffer->SenseKey & 0xf) == SCSI_SENSE_HARDWARE_ERROR) && - (senseBuffer->AdditionalSenseCode == 0x44)) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "DeviceErrorHandlerForHitachiGD2000 (%p) => Internal Target " - "Failure Detected -- spinning up drive\n", DeviceExtension->Device)); - - // the request should be retried because the device isn't ready - *Retry = TRUE; - *Status = STATUS_DEVICE_NOT_READY; - - // send a START_STOP unit to spin up the drive - // NOTE: this temporarily violates the StartIo serialization - // mechanism, but the completion routine on this will NOT - // call StartNextPacket(), so it's a temporary disruption - // of the serialization only. - DeviceSendStartUnit(DeviceExtension->Device); - } - - return STATUS_SUCCESS; -} - - -VOID -SenseInfoRequestGetInformation( - _In_ WDFREQUEST Request, - _Out_ UCHAR* MajorFunctionCode, - _Out_ ULONG* IoControlCode, - _Out_ BOOLEAN* OverrideVerifyVolume, - _Out_ ULONGLONG* Total100nsSinceFirstSend - ) -{ - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - - *MajorFunctionCode = 0; - *IoControlCode = 0; - *OverrideVerifyVolume = FALSE; - *Total100nsSinceFirstSend = 0; - - if (requestContext->OriginalRequest != NULL) - { - PIO_STACK_LOCATION originalIrpStack = NULL; - - PIRP originalIrp = WdfRequestWdmGetIrp(requestContext->OriginalRequest); - - if (originalIrp != NULL) - { - originalIrpStack = IoGetCurrentIrpStackLocation(originalIrp); - } - - if (originalIrpStack != NULL) - { - *MajorFunctionCode = originalIrpStack->MajorFunction; - - if (*MajorFunctionCode == IRP_MJ_DEVICE_CONTROL) - { - *IoControlCode = originalIrpStack->Parameters.DeviceIoControl.IoControlCode; - } - - *OverrideVerifyVolume = TEST_FLAG(originalIrpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME); - } - } - - // Calculate time past since the request was first time sent. - if (requestContext->TimeSentDownFirstTime.QuadPart > 0) - { - LARGE_INTEGER tmp; - KeQueryTickCount(&tmp); - tmp.QuadPart -= requestContext->TimeSentDownFirstTime.QuadPart; - tmp.QuadPart *= KeQueryTimeIncrement(); - *Total100nsSinceFirstSend = tmp.QuadPart; - } - else - { - // set to -1 if field TimeSentDownFirstTime not set. - *Total100nsSinceFirstSend = (ULONGLONG) -1; - } - - return; -} - -BOOLEAN -SenseInfoInterpretByAdditionalSenseCode( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ UCHAR AdditionalSenseCode, - _In_ UCHAR AdditionalSenseCodeQual, - _Inout_ NTSTATUS* Status, - _Inout_ BOOLEAN* Retry, - _Out_ _Deref_out_range_(0,100) ULONG* RetryIntervalInSeconds, - _Inout_ PERROR_LOG_CONTEXT LogContext - ) -/* - This function will interpret error based on ASC/ASCQ. - - If the error code is not processed in this function, e.g. return value is TRUE, - caller needs to call SenseInfoInterpretBySenseKey() for further interpret. -*/ -{ - BOOLEAN needFurtherInterpret = TRUE; - PSENSE_DATA senseBuffer = (PSENSE_DATA)Srb->SenseInfoBuffer; - - // set default values for retry fields. - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - - switch (AdditionalSenseCode) - { - case SCSI_ADSENSE_LUN_NOT_READY: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Lun not ready\n")); - - // - // Many non-WHQL certified drives (mostly CD-RW) return - // 2/4/0 when they have no media instead of the obvious choice of: - // - // SCSI_SENSE_NOT_READY/SCSI_ADSENSE_NO_MEDIA_IN_DEVICE - // - // These drives should not pass WHQL certification due to this discrepency. - // - // However, we have to retry on 2/4/0 (Not ready, LUN not ready, no info) - // and also 3/2/0 (no seek complete). - // - // These conditions occur when the shell tries to examine an - // injected CD (e.g. for autoplay) before the CD is spun up. - // - // The drive should be returning an ASCQ of SCSI_SENSEQ_BECOMING_READY - // (0x01) in order to comply with WHQL standards. - // - // The default retry timeout of one second is acceptable to balance - // these discrepencies. don't modify the status, though.... - // - - switch (AdditionalSenseCodeQual) - { - case SCSI_SENSEQ_OPERATION_IN_PROGRESS: - { - DEVICE_EVENT_BECOMING_READY notReady = {0}; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Operation In Progress\n")); - - needFurtherInterpret = FALSE; - - *Retry = TRUE; - *RetryIntervalInSeconds = NOT_READY_RETRY_INTERVAL; - *Status = STATUS_DEVICE_NOT_READY; - - notReady.Version = 1; - notReady.Reason = 2; - notReady.Estimated100msToReady = *RetryIntervalInSeconds * 10; - DeviceSendNotification(DeviceExtension, - &GUID_IO_DEVICE_BECOMING_READY, - sizeof(DEVICE_EVENT_BECOMING_READY), - ¬Ready); - - break; - } - - case SCSI_SENSEQ_BECOMING_READY: - { - DEVICE_EVENT_BECOMING_READY notReady = {0}; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: In process of becoming ready\n")); - - needFurtherInterpret = FALSE; - - *Retry = TRUE; - *RetryIntervalInSeconds = NOT_READY_RETRY_INTERVAL; - *Status = STATUS_DEVICE_NOT_READY; - - notReady.Version = 1; - notReady.Reason = 1; - notReady.Estimated100msToReady = *RetryIntervalInSeconds * 10; - DeviceSendNotification(DeviceExtension, - &GUID_IO_DEVICE_BECOMING_READY, - sizeof(DEVICE_EVENT_BECOMING_READY), - ¬Ready); - - break; - } - - case SCSI_SENSEQ_LONG_WRITE_IN_PROGRESS: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Long write in progress\n")); - - needFurtherInterpret = FALSE; - - // This has been seen as a transcient failure on some drives - *Status = STATUS_DEVICE_NOT_READY; - *Retry = TRUE; - // Set retry interval to be 0 as the drive can be ready at anytime. - *RetryIntervalInSeconds = 0; - - break; - } - - case SCSI_SENSEQ_MANUAL_INTERVENTION_REQUIRED: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Manual intervention required\n")); - - needFurtherInterpret = FALSE; - - *Status = STATUS_NO_MEDIA_IN_DEVICE; - *Retry = FALSE; - *RetryIntervalInSeconds = NOT_READY_RETRY_INTERVAL; - - break; - } - - case SCSI_SENSEQ_FORMAT_IN_PROGRESS: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Format in progress\n")); - - needFurtherInterpret = FALSE; - - *Status = STATUS_DEVICE_NOT_READY; - *Retry = FALSE; - *RetryIntervalInSeconds = NOT_READY_RETRY_INTERVAL; - - break; - } - - case SCSI_SENSEQ_CAUSE_NOT_REPORTABLE: - case SCSI_SENSEQ_INIT_COMMAND_REQUIRED: - default: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Initializing command required\n")); - - needFurtherInterpret = FALSE; - - *Status = STATUS_DEVICE_NOT_READY; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - - // This sense code/additional sense code combination may indicate - // that the device needs to be started. - if (TEST_FLAG(DeviceExtension->DeviceFlags, DEV_SAFE_START_UNIT) && - !TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_LOW_PRIORITY)) - { - DeviceSendStartUnit(DeviceExtension->Device); - } - - break; - } - } // end switch (AdditionalSenseCodeQual) - break; - - } // end case (SCSI_ADSENSE_LUN_NOT_READY) - - case SCSI_ADSENSE_NO_MEDIA_IN_DEVICE: - { - TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: No Media in device.\n")); - - needFurtherInterpret = FALSE; - - *Status = STATUS_NO_MEDIA_IN_DEVICE; - *Retry = FALSE; - - if (AdditionalSenseCodeQual == 0xCC) - { - // The IMAPIv1 filter returns this ASCQ value while it is burning CD media, and we want - // to preserve this functionality for compatibility reasons. - // We want to indicate that the media is not present to most applications; - // but RSM has to know that the media is still in the drive (i.e. the drive is not free). - DeviceSetMediaChangeStateEx(DeviceExtension, MediaUnavailable, NULL); - } - else - { - DeviceSetMediaChangeStateEx(DeviceExtension, MediaNotPresent, NULL); - } - - break; - } // end case SCSI_ADSENSE_NO_MEDIA_IN_DEVICE - - case SCSI_ADSENSE_INVALID_MEDIA: - { - switch (AdditionalSenseCodeQual) - { - - case SCSI_SENSEQ_UNKNOWN_FORMAT: - { - needFurtherInterpret = FALSE; - - // Log error only if this is a paging request - *Status = STATUS_UNRECOGNIZED_MEDIA; - *Retry = FALSE; - - LogContext->LogError = TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING); - LogContext->UniqueErrorValue = 256; - LogContext->ErrorCode = IO_ERR_BAD_BLOCK; - - break; - } - - case SCSI_SENSEQ_INCOMPATIBLE_FORMAT: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_UNRECOGNIZED_MEDIA; - *Retry = FALSE; - - LogContext->LogError = FALSE; - - break; - } - - case SCSI_SENSEQ_CLEANING_CARTRIDGE_INSTALLED: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_CLEANER_CARTRIDGE_INSTALLED; - *Retry = FALSE; - - LogContext->LogError = FALSE; - LogContext->UniqueErrorValue = 256; - LogContext->ErrorCode = IO_ERR_BAD_BLOCK; - break; - } - - default: - { - needFurtherInterpret = TRUE; - break; - } - } // end case AdditionalSenseCodeQual - - break; - } // end case SCSI_ADSENSE_NO_MEDIA_IN_DEVICE - - case SCSI_ADSENSE_NO_SEEK_COMPLETE: - { - switch (AdditionalSenseCodeQual) - { - - case 0x00: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_DEVICE_DATA_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 256; - LogContext->ErrorCode = IO_ERR_BAD_BLOCK; - break; - } - - default: - { - needFurtherInterpret = TRUE; - break; - } - } - - break; - } // end case SCSI_ADSENSE_NO_SEEK_COMPLETE - - case SCSI_ADSENSE_LUN_COMMUNICATION: - { - switch (AdditionalSenseCodeQual) - { - - case SCSI_SESNEQ_COMM_CRC_ERROR: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 1; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 257; - LogContext->ErrorCode = IO_ERR_CONTROLLER_ERROR; - break; - } - - default: - { - needFurtherInterpret = TRUE; - break; - } - } - - break; - } // end case SCSI_ADSENSE_LUN_COMMUNICATION - - case SCSI_ADSENSE_ILLEGAL_BLOCK: - { - needFurtherInterpret = FALSE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Illegal block address\n")); - *Status = STATUS_NONEXISTENT_SECTOR; - *Retry = FALSE; - break; - } - - case SCSI_ADSENSE_INVALID_LUN: - { - needFurtherInterpret = FALSE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Invalid LUN\n")); - *Status = STATUS_NO_SUCH_DEVICE; - *Retry = FALSE; - break; - } - - case SCSI_ADSENSE_COPY_PROTECTION_FAILURE: - { - needFurtherInterpret = FALSE; - - *Retry = FALSE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Key - Copy protection failure\n")); - - switch (AdditionalSenseCodeQual) - { - case SCSI_SENSEQ_AUTHENTICATION_FAILURE: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Authentication failure\n")); - *Status = STATUS_CSS_AUTHENTICATION_FAILURE; - break; - case SCSI_SENSEQ_KEY_NOT_PRESENT: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Key not present\n")); - *Status = STATUS_CSS_KEY_NOT_PRESENT; - break; - case SCSI_SENSEQ_KEY_NOT_ESTABLISHED: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Key not established\n")); - *Status = STATUS_CSS_KEY_NOT_ESTABLISHED; - break; - case SCSI_SENSEQ_READ_OF_SCRAMBLED_SECTOR_WITHOUT_AUTHENTICATION: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Read of scrambled sector w/o authentication\n")); - *Status = STATUS_CSS_SCRAMBLED_SECTOR; - break; - case SCSI_SENSEQ_MEDIA_CODE_MISMATCHED_TO_LOGICAL_UNIT: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Media region does not logical unit region\n")); - *Status = STATUS_CSS_REGION_MISMATCH; - break; - case SCSI_SENSEQ_LOGICAL_UNIT_RESET_COUNT_ERROR: - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Region set error -- region may be permanent\n")); - *Status = STATUS_CSS_RESETS_EXHAUSTED; - break; - - default: - *Status = STATUS_COPY_PROTECTION_FAILURE; - break; - } // end switch of ASCQ for COPY_PROTECTION_FAILURE - - break; - } - - case SCSI_ADSENSE_INVALID_CDB: - { - needFurtherInterpret = FALSE; - - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Key - Invalid CDB\n")); - - *Status = STATUS_INVALID_DEVICE_REQUEST; - *Retry = FALSE; - - // Note: the retry interval is not typically used. - // it is set here only because a ClassErrorHandler - // cannot set the RetryIntervalInSeconds, and the error may - // require a few commands to be sent to clear whatever - // caused this condition (i.e. disk clears the write - // cache, requiring at least two commands) - // - // hopefully, this shortcoming can be changed for blackcomb. - *RetryIntervalInSeconds = 3; - - break; - } - - case SCSI_ADSENSE_MEDIUM_CHANGED: - { - needFurtherInterpret = FALSE; - *RetryIntervalInSeconds = 0; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "SenseInfoInterpretByAdditionalSenseCode: Media changed\n")); - - DeviceSetMediaChangeStateEx(DeviceExtension, MediaPresent, NULL); - - // special process for Media Change - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - // Set bit to indicate that media may have changed and volume needs verification. - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - - *Status = STATUS_VERIFY_REQUIRED; - *Retry = FALSE; - } - else - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - break; - } - - case SCSI_ADSENSE_OPERATOR_REQUEST: - { - switch (AdditionalSenseCodeQual) - { - case SCSI_SENSEQ_MEDIUM_REMOVAL: - { - needFurtherInterpret = FALSE; - *RetryIntervalInSeconds = 0; - - InterlockedIncrement((PLONG)&DeviceExtension->MediaChangeCount); - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Ejection request received!\n")); - //Send eject notification. - DeviceSendNotification(DeviceExtension, - &GUID_IO_MEDIA_EJECT_REQUEST, - 0, - NULL); - // special process for Media Change - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - // Set bit to indicate that media may have changed and volume needs verification. - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - - *Status = STATUS_VERIFY_REQUIRED; - *Retry = FALSE; - } - else - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - break; - } - default: - { - needFurtherInterpret = TRUE; - break; - } - } - break; - } - - case SCSI_ADSENSE_OPERATING_CONDITIONS_CHANGED: - { - needFurtherInterpret = FALSE; - *RetryIntervalInSeconds = 5; - - InterlockedIncrement((PLONG)&DeviceExtension->MediaChangeCount); - - // Device information has changed, we need to rescan the - // bus for changed information such as the capacity. - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Device information changed. Invalidate the bus\n")); - - IoInvalidateDeviceRelations(DeviceExtension->LowerPdo, BusRelations); - - // special process for Media Change - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - // Set bit to indicate that media may have changed and volume needs verification. - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - - *Status = STATUS_VERIFY_REQUIRED; - *Retry = FALSE; - } - else - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - break; - } //end Case SCSI_ADSENSE_OPERATING_CONDITIONS_CHANGED - - - case SCSI_ADSENSE_REC_DATA_NOECC: - case SCSI_ADSENSE_REC_DATA_ECC: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_SUCCESS; - *Retry = FALSE; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 258; - LogContext->ErrorCode = IO_RECOVERED_VIA_ECC; - - if (senseBuffer->IncorrectLength) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Incorrect length detected.\n")); - *Status = STATUS_INVALID_BLOCK_LENGTH ; - } - break; - } - - case SCSI_ADSENSE_FAILURE_PREDICTION_THRESHOLD_EXCEEDED: - { - UCHAR wmiEventData[sizeof(ULONG)+sizeof(UCHAR)] = {0}; - - *((PULONG)wmiEventData) = sizeof(UCHAR); - wmiEventData[sizeof(ULONG)] = AdditionalSenseCodeQual; - - needFurtherInterpret = FALSE; - - // Don't log another eventlog if we have already logged once - // NOTE: this should have been interlocked, but the structure - // was publicly defined to use a BOOLEAN (char). Since - // media only reports these errors once per X minutes, - // the potential race condition is nearly non-existant. - // the worst case is duplicate log entries, so ignore. - - *Status = STATUS_SUCCESS; - *Retry = FALSE; - LogContext->UniqueErrorValue = 258; - LogContext->LogError = TRUE; - LogContext->ErrorCode = IO_WRN_FAILURE_PREDICTED; - - if (senseBuffer->IncorrectLength) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretByAdditionalSenseCode: Incorrect length detected.\n")); - *Status = STATUS_INVALID_BLOCK_LENGTH ; - } - break; - } - - case 0x57: - { - // UNABLE_TO_RECOVER_TABLE_OF_CONTENTS - // the Matshita CR-585 returns this for all read commands - // on blank CD-R and CD-RW media, and we need to handle - // this for READ_CD detection ability. - switch (AdditionalSenseCodeQual) - { - case 0x00: - { - needFurtherInterpret = FALSE; - - *Status = STATUS_UNRECOGNIZED_MEDIA; - *Retry = FALSE; - break; - } - default: - { - needFurtherInterpret = TRUE; - break; - } - } - break; - } //end case Matshita specific error 0x57 - - default: - { - needFurtherInterpret = TRUE; - break; - } - } - - return needFurtherInterpret; -} - -VOID -SenseInfoInterpretBySenseKey( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSENSE_DATA SenseData, - _In_ UCHAR SenseKey, - _Inout_ NTSTATUS* Status, - _Inout_ BOOLEAN* Retry, - _Out_ _Deref_out_range_(0,100) ULONG* RetryIntervalInSeconds, - _Inout_ PERROR_LOG_CONTEXT LogContext - ) -{ - // set default values for retry fields. - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - - switch (SenseKey) - { - case SCSI_SENSE_NOT_READY: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Not Ready (bad block)\n")); - - *Status = STATUS_DEVICE_NOT_READY; - *Retry = TRUE; - - // for unprocessed "not ready" codes, retry the command immediately. - *RetryIntervalInSeconds = 0; - break; - } - - case SCSI_SENSE_DATA_PROTECT: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Media write protected\n")); - *Status = STATUS_MEDIA_WRITE_PROTECTED; - *Retry = FALSE; - break; - } - - case SCSI_SENSE_MEDIUM_ERROR: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Medium Error (bad block)\n")); - - *Status = STATUS_DEVICE_DATA_ERROR; - *Retry = FALSE; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 256; - LogContext->ErrorCode = IO_ERR_BAD_BLOCK; - - break; - } // end SCSI_SENSE_MEDIUM_ERROR - - case SCSI_SENSE_HARDWARE_ERROR: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Hardware error\n")); - - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 257; - LogContext->ErrorCode = IO_ERR_CONTROLLER_ERROR; - - break; - } // end SCSI_SENSE_HARDWARE_ERROR - - case SCSI_SENSE_ILLEGAL_REQUEST: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Illegal SCSI request\n")); - *Status = STATUS_INVALID_DEVICE_REQUEST; - *Retry = FALSE; - - break; - } // end SCSI_SENSE_ILLEGAL_REQUEST - - case SCSI_SENSE_UNIT_ATTENTION: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Key - Unit Attention\n")); - - // A media change may have occured so increment the change - // count for the physical device - InterlockedIncrement((PLONG)&DeviceExtension->MediaChangeCount); - - if (IsVolumeMounted(DeviceExtension->DeviceObject)) - { - // Set bit to indicate that media may have changed - // and volume needs verification. - SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME); - - *Status = STATUS_VERIFY_REQUIRED; - *Retry = FALSE; - } - else - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - - break; - - } // end SCSI_SENSE_UNIT_ATTENTION - - case SCSI_SENSE_ABORTED_COMMAND: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Command aborted\n")); - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 1; - break; - } // end SCSI_SENSE_ABORTED_COMMAND - - case SCSI_SENSE_BLANK_CHECK: - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Media blank check\n")); - *Retry = FALSE; - *Status = STATUS_NO_DATA_DETECTED; - break; - } // end SCSI_SENSE_BLANK_CHECK - - case SCSI_SENSE_RECOVERED_ERROR: - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Recovered error\n")); - *Status = STATUS_SUCCESS; - *Retry = FALSE; - LogContext->LogError = TRUE; - LogContext->UniqueErrorValue = 258; - LogContext->ErrorCode = IO_ERR_CONTROLLER_ERROR; - - if (SenseData->IncorrectLength) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Incorrect length detected.\n")); - *Status = STATUS_INVALID_BLOCK_LENGTH ; - } - - break; - } // end SCSI_SENSE_RECOVERED_ERROR - - case SCSI_SENSE_NO_SENSE: - { - // Check other indicators. - if (SenseData->IncorrectLength) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Incorrect length detected.\n")); - *Status = STATUS_INVALID_BLOCK_LENGTH ; - *Retry = FALSE; - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: No specific sense key\n")); - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - - break; - } // end SCSI_SENSE_NO_SENSE - - default: - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpretBySenseKey: Unrecognized sense code\n")); - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - - break; - } - - } // end switch (SenseKey) - - return; -} - -VOID -SenseInfoInterpretBySrbStatus( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ ULONG RetriedCount, - _Inout_ NTSTATUS* Status, - _Inout_ BOOLEAN* Retry, - _Out_ _Deref_out_range_(0,100) ULONG* RetryIntervalInSeconds, - _Inout_ PERROR_LOG_CONTEXT LogContext - ) -{ - BOOLEAN incrementErrorCount = FALSE; - - // set default values for retry fields. - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - - switch (SRB_STATUS(Srb->SrbStatus)) - { - case SRB_STATUS_INVALID_LUN: - case SRB_STATUS_INVALID_TARGET_ID: - case SRB_STATUS_NO_DEVICE: - case SRB_STATUS_NO_HBA: - case SRB_STATUS_INVALID_PATH_ID: - { - *Status = STATUS_NO_SUCH_DEVICE; - *Retry = FALSE; - break; - } - - case SRB_STATUS_COMMAND_TIMEOUT: - case SRB_STATUS_TIMEOUT: - { - // Update the error count for the device. - *Status = STATUS_IO_TIMEOUT; - *Retry = TRUE; - *RetryIntervalInSeconds = 0; - incrementErrorCount = TRUE; - break; - } - - case SRB_STATUS_ABORTED: - { - // Update the error count for the device. - *Status = STATUS_IO_TIMEOUT; - *Retry = TRUE; - *RetryIntervalInSeconds = 1; - incrementErrorCount = TRUE; - break; - } - - case SRB_STATUS_SELECTION_TIMEOUT: - { - *Status = STATUS_DEVICE_NOT_CONNECTED; - *Retry = FALSE; - *RetryIntervalInSeconds = 2; - LogContext->LogError = TRUE; - LogContext->ErrorCode = IO_ERR_NOT_READY; - LogContext->UniqueErrorValue = 260; - break; - } - - case SRB_STATUS_DATA_OVERRUN: - { - *Status = STATUS_DATA_OVERRUN; - *Retry = FALSE; - break; - } - - case SRB_STATUS_PHASE_SEQUENCE_FAILURE: - { - // Update the error count for the device. - incrementErrorCount = TRUE; - *Status = STATUS_IO_DEVICE_ERROR; - - // If there was phase sequence error then limit the number of retries. - *Retry = (RetriedCount <= 1); - - break; - } - - case SRB_STATUS_REQUEST_FLUSHED: - { - // If the status needs verification bit is set. Then set - // the status to need verification and no retry; otherwise, - // just retry the request. - if (TEST_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME)) - { - *Status = STATUS_VERIFY_REQUIRED; - *Retry = FALSE; - } - else - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - - break; - } - - case SRB_STATUS_INVALID_REQUEST: - { - *Status = STATUS_INVALID_DEVICE_REQUEST; - *Retry = FALSE; - break; - } - - case SRB_STATUS_UNEXPECTED_BUS_FREE: - case SRB_STATUS_PARITY_ERROR: - // Update the error count for the device and fall through to below - incrementErrorCount = TRUE; - - case SRB_STATUS_BUS_RESET: - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - break; - } - - case SRB_STATUS_ERROR: - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - - if (Srb->ScsiStatus == 0) - { - // This is some strange return code. Update the error - // count for the device. - incrementErrorCount = TRUE; - } - - if (Srb->ScsiStatus == SCSISTAT_BUSY) - { - *Status = STATUS_DEVICE_NOT_READY; - } - - break; - } - - default: - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - LogContext->LogError = TRUE; - LogContext->ErrorCode = IO_ERR_CONTROLLER_ERROR; - LogContext->UniqueErrorValue = 259; - LogContext->ErrorUnhandled = TRUE; - break; - } - - } //end of (SRB_STATUS(Srb->SrbStatus)) - - if (incrementErrorCount) - { - // if any error count occurred, delay the retry of this io by - // at least one second, if caller supports it. - if (*RetryIntervalInSeconds == 0) - { - *RetryIntervalInSeconds = 1; - } - - DevicePerfIncrementErrorCount(DeviceExtension); - } - - return; -} - -VOID -SenseInfoLogError( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ UCHAR MajorFunctionCode, - _In_ ULONG IoControlCode, - _In_ ULONG RetriedCount, - _In_ NTSTATUS* Status, - _In_ BOOLEAN* Retry, - _Inout_ PERROR_LOG_CONTEXT LogContext - ) -{ - // Always log the error in our internal log. - // If logError is set, also log the error in the system log. - PSENSE_DATA senseBuffer = (PSENSE_DATA)Srb->SenseInfoBuffer; - ULONG totalSize = 0; - ULONG senseBufferSize = 0; - IO_ERROR_LOG_PACKET staticErrLogEntry = {0}; - CDROM_ERROR_LOG_DATA staticErrLogData = {0}; - - // Calculate the total size of the error log entry. - // add to totalSize in the order that they are used. - // the advantage to calculating all the sizes here is - // that we don't have to do a bunch of extraneous checks - // later on in this code path. - totalSize = sizeof(IO_ERROR_LOG_PACKET) // required - + sizeof(CDROM_ERROR_LOG_DATA); // struct for ease - - // also save any available extra sense data, up to the maximum errlog - // packet size . WMI should be used for real-time analysis. - // the event log should only be used for post-mortem debugging. - if (TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) - { - ULONG validSenseBytes; - BOOLEAN validSense; - - // make sure we can at least access the AdditionalSenseLength field - validSense = RTL_CONTAINS_FIELD(senseBuffer, - Srb->SenseInfoBufferLength, - AdditionalSenseLength); - if (validSense) - { - // if extra info exists, copy the maximum amount of available - // sense data that is safe into the the errlog. - validSenseBytes = senseBuffer->AdditionalSenseLength - + offsetof(SENSE_DATA, AdditionalSenseLength); - - // this is invalid because it causes overflow! - // whoever sent this type of request would cause - // a system crash. - NT_ASSERT(validSenseBytes < MAX_ADDITIONAL_SENSE_BYTES); - - // set to save the most sense buffer possible - senseBufferSize = max(validSenseBytes, sizeof(SENSE_DATA)); - senseBufferSize = min(senseBufferSize, Srb->SenseInfoBufferLength); - } - else - { - // it's smaller than required to read the total number of - // valid bytes, so just use the SenseInfoBufferLength field. - senseBufferSize = Srb->SenseInfoBufferLength; - } - - // Bump totalSize by the number of extra senseBuffer bytes - // (beyond the default sense buffer within CDROM_ERROR_LOG_DATA). - // Make sure to never allocate more than ERROR_LOG_MAXIMUM_SIZE. - if (senseBufferSize > sizeof(SENSE_DATA)) - { - totalSize += senseBufferSize-sizeof(SENSE_DATA); - if (totalSize > ERROR_LOG_MAXIMUM_SIZE) - { - senseBufferSize -= totalSize-ERROR_LOG_MAXIMUM_SIZE; - totalSize = ERROR_LOG_MAXIMUM_SIZE; - } - } - } - - // If we've used up all of our retry attempts, set the final status to - // reflect the appropriate result. - // - // ISSUE: the test below should also check RetriedCount to determine if we will actually retry, - // but there is no easy test because we'd have to consider the original retry count - // for the op; besides, InterpretTransferPacketError sometimes ignores the retry - // decision returned by this function. So just ErrorRetried to be true in the majority case. - // - if (*Retry) - { - staticErrLogEntry.FinalStatus = STATUS_SUCCESS; - staticErrLogData.ErrorRetried = TRUE; - } - else - { - staticErrLogEntry.FinalStatus = *Status; - } - - // Don't log generic IO_WARNING_PAGING_FAILURE message if either the - // I/O is retried, or it completed successfully. - if ((LogContext->ErrorCode == IO_WARNING_PAGING_FAILURE) && - (*Retry || NT_SUCCESS(*Status)) ) - { - LogContext->LogError = FALSE; - } - - if (TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING)) - { - staticErrLogData.ErrorPaging = TRUE; - } - - staticErrLogData.ErrorUnhandled = LogContext->ErrorUnhandled; - - // Calculate the device offset if there is a geometry. - staticErrLogEntry.DeviceOffset.QuadPart = (LONGLONG)LogContext->BadSector; - staticErrLogEntry.DeviceOffset.QuadPart *= (LONGLONG)DeviceExtension->DiskGeometry.BytesPerSector; - - if (LogContext->ErrorCode == -1) - { - staticErrLogEntry.ErrorCode = STATUS_IO_DEVICE_ERROR; - } - else - { - staticErrLogEntry.ErrorCode = LogContext->ErrorCode; - } - - // The dump data follows the IO_ERROR_LOG_PACKET - staticErrLogEntry.DumpDataSize = (USHORT)totalSize - sizeof(IO_ERROR_LOG_PACKET); - - staticErrLogEntry.SequenceNumber = 0; - staticErrLogEntry.MajorFunctionCode = MajorFunctionCode; - staticErrLogEntry.IoControlCode = IoControlCode; - staticErrLogEntry.RetryCount = (UCHAR)RetriedCount; - staticErrLogEntry.UniqueErrorValue = LogContext->UniqueErrorValue; - - KeQueryTickCount(&staticErrLogData.TickCount); - staticErrLogData.PortNumber = (ULONG)-1; - - // Save the entire contents of the SRB. - staticErrLogData.Srb = *Srb; - - // For our private log, save just the default length of the SENSE_DATA. - if (senseBufferSize != 0) - { - RtlCopyMemory(&staticErrLogData.SenseData, senseBuffer, min(senseBufferSize, sizeof(SENSE_DATA))); - } - - // Save the error log in our context. - // We only save the default sense buffer length. - { - KIRQL oldIrql; - KeAcquireSpinLock(&DeviceExtension->PrivateFdoData->SpinLock, &oldIrql); - DeviceExtension->PrivateFdoData->ErrorLogs[DeviceExtension->PrivateFdoData->ErrorLogNextIndex] = staticErrLogData; - DeviceExtension->PrivateFdoData->ErrorLogNextIndex++; - DeviceExtension->PrivateFdoData->ErrorLogNextIndex %= NUM_ERROR_LOG_ENTRIES; - KeReleaseSpinLock(&DeviceExtension->PrivateFdoData->SpinLock, oldIrql); - } - - // If logError is set, also save this log in the system's error log. - // But make sure we don't log TUR failures over and over - // (e.g. if an external drive was switched off and we're still sending TUR's to it every second). - if (LogContext->LogError) - { - // We do not want to log certain system events repetitively - switch (((PCDB)Srb->Cdb)->CDB10.OperationCode) - { - case SCSIOP_TEST_UNIT_READY: - { - if (DeviceExtension->PrivateFdoData->LoggedTURFailureSinceLastIO) - { - LogContext->LogError = FALSE; - } - else - { - DeviceExtension->PrivateFdoData->LoggedTURFailureSinceLastIO = TRUE; - } - - break; - } - - case SCSIOP_SYNCHRONIZE_CACHE: - { - if (DeviceExtension->PrivateFdoData->LoggedSYNCFailure) - { - LogContext->LogError = FALSE; - } - else - { - DeviceExtension->PrivateFdoData->LoggedSYNCFailure = TRUE; - } - - break; - } - } - - // Do not log 5/21/00 LOGICAL BLOCK ADDRESS OUT OF RANGE if the disc is blank, - // it is known to litter the Event Log with repetitive errors - // Do not log this error for READ, as it's known that File System mount process reads different sectors from media. - if (senseBufferSize > RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCodeQualifier) && - senseBuffer->SenseKey == SCSI_SENSE_ILLEGAL_REQUEST && - senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_ILLEGAL_BLOCK && - senseBuffer->AdditionalSenseCodeQualifier == 0 && - IS_SCSIOP_READ(((PCDB)Srb->Cdb)->CDB10.OperationCode)) - { - LogContext->LogError = FALSE; - } - } - - // Write the error log packet to the system error logging thread. - if (LogContext->LogError) - { - PIO_ERROR_LOG_PACKET errorLogEntry; - PCDROM_ERROR_LOG_DATA errlogData; - - errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(DeviceExtension->DeviceObject, (UCHAR)totalSize); - if (errorLogEntry) - { - errlogData = (PCDROM_ERROR_LOG_DATA)errorLogEntry->DumpData; - - *errorLogEntry = staticErrLogEntry; - *errlogData = staticErrLogData; - - // For the system log, copy as much of the sense buffer as possible. - if (senseBufferSize != 0) - { - RtlCopyMemory(&errlogData->SenseData, senseBuffer, senseBufferSize); - } - - // errorLogEntry - It will be freed by the kernel. - IoWriteErrorLogEntry(errorLogEntry); - } - } - - return; -} - -VOID -SenseInfoInterpretRefineByScsiCommand( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ ULONG RetriedCount, - _In_ LONGLONG Total100nsSinceFirstSend, - _In_ BOOLEAN OverrideVerifyVolume, - _Inout_ BOOLEAN* Retry, - _Inout_ NTSTATUS* Status, - _Inout_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ) -/*++ - -Routine Description: - - Based on SCSI command, modify the interpretion result. - -Arguments: - - DeviceExtension - device extension. - Srb - Supplies the scsi request block which failed. - RetriedCount - retried count. - Total100nsUnitsSinceFirstSend - time spent after the request was sent down first time. - OverrideVerifyVolume - should override verify volume request. - -Return Value: - - Retry - the reques should be retried or not. - Status - Returns the status for the request. - RetryInterval - waiting time (in 100ns) before the request should be retried. - Zero indicates the request should be immediately retried. - ---*/ -{ - UCHAR const opCode = Srb->Cdb[0]; - CDB const* cdb = (CDB const*)(Srb->Cdb); - PSENSE_DATA senseBuffer = (PSENSE_DATA)Srb->SenseInfoBuffer; - - if (opCode == SCSIOP_MEDIUM_REMOVAL) - { - if (( cdb->AsByte[1] == 0) && - ( cdb->AsByte[2] == 0) && - ( cdb->AsByte[3] == 0) && - ((cdb->AsByte[4] & 0xFC) == 0) - ) - { - // byte[4] == 0x3 or byte[4] == 0x1 == UNLOCK OF MEDIA - if ((cdb->AsByte[4] & 0x01) == 0) - { - if (RetriedCount < TOTAL_COUNT_RETRY_DEFAULT) - { - // keep retrying unlock operation for several times - *Retry = TRUE; - } - } - else // LOCK REQUEST - { - // do not retry LOCK requests more than once (per CLASSPNP code) - if (RetriedCount > TOTAL_COUNT_RETRY_LOCK_MEDIA) - { - *Retry = FALSE; - } - } - } - - // want a minimum time to retry of 2 seconds - if ((*Status == STATUS_DEVICE_NOT_READY) && - (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY)) - { - *RetryIntervalIn100ns = max(*RetryIntervalIn100ns, SECONDS_TO_100NS_UNITS(2)); - } - else if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SELECTION_TIMEOUT) - { - *RetryIntervalIn100ns = max(*RetryIntervalIn100ns, SECONDS_TO_100NS_UNITS(2)); - } - } - else if ((opCode == SCSIOP_MODE_SENSE) || (opCode == SCSIOP_MODE_SENSE10)) - { - // want a minimum time to retry of 2 seconds - if ((*Status == STATUS_DEVICE_NOT_READY) && - (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY)) - { - *RetryIntervalIn100ns = max(*RetryIntervalIn100ns, SECONDS_TO_100NS_UNITS(2)); - } - else if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SELECTION_TIMEOUT) - { - *RetryIntervalIn100ns = max(*RetryIntervalIn100ns, SECONDS_TO_100NS_UNITS(2)); - } - - // Want to ignore a STATUS_VERIFY_REQUIRED error because it either - // doesn't make sense or is required to satisfy the VERIFY. - if (*Status == STATUS_VERIFY_REQUIRED) - { - *Retry = TRUE; - } - else if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_DATA_OVERRUN) - { - /* - * This is a HACK. - * Atapi returns SRB_STATUS_DATA_OVERRUN when it really means - * underrun (i.e. success, and the buffer is longer than needed). - * So treat this as a success. - * When the caller of this function sees that the status was changed to success, - * it will add the transferred length to the original irp. - */ - *Status = STATUS_SUCCESS; - *Retry = FALSE; - } - - // limit the count of retries - if (RetriedCount > TOTAL_COUNT_RETRY_MODESENSE) - { - *Retry = FALSE; - } - } - else if ((opCode == SCSIOP_READ_CAPACITY) || (opCode == SCSIOP_READ_CAPACITY16)) - { - // Want to ignore a STATUS_VERIFY_REQUIRED error because it either - // doesn't make sense or is required to satisfy the VERIFY. - if (*Status == STATUS_VERIFY_REQUIRED) - { - *Retry = TRUE; - } - - if (RetriedCount > TOTAL_COUNT_RETRY_READ_CAPACITY) - { - *Retry = FALSE; - } - } - else if ((opCode == SCSIOP_RESERVE_UNIT) || (opCode == SCSIOP_RELEASE_UNIT)) - { - // The RESERVE(6) / RELEASE(6) commands are optional. - // So if they aren't supported, try the 10-byte equivalents - if (*Status == STATUS_INVALID_DEVICE_REQUEST) - { - PCDB tempCdb = (PCDB)Srb->Cdb; - - Srb->CdbLength = 10; - tempCdb->CDB10.OperationCode = (tempCdb->CDB6GENERIC.OperationCode == SCSIOP_RESERVE_UNIT) - ? SCSIOP_RESERVE_UNIT10 - : SCSIOP_RELEASE_UNIT10; - - SET_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_NO_RESERVE6); - *Retry = TRUE; - } - } - else if (IS_SCSIOP_READWRITE(opCode)) - { - // Retry if still verifying a (possibly) reloaded disk/cdrom. - if (OverrideVerifyVolume && (*Status == STATUS_VERIFY_REQUIRED)) - { - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - } - - // Special case for streaming READ/WRITE commands - if (((opCode == SCSIOP_READ12) && (cdb->READ12.Streaming == 1)) || - ((opCode == SCSIOP_WRITE12) && (cdb->WRITE12.Streaming == 1))) - { - // We've got a failure while performing a streaming operation and now need to guess if - // it's likely to be a permanent error because the drive does not support streaming at all - // (in which case we're going to fall back to normal reads/writes), or a transient error - // (in which case we quickly fail the request but contrinue to use streaming). - // - // We analyze the sense information to make that decision. Bus resets and device timeouts - // are treated as permanent errors, because some non-compliant devices may even hang when - // they get a command that they do not expect. - - BOOLEAN disableStreaming = FALSE; - - if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_TIMEOUT || - SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_COMMAND_TIMEOUT || - SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SELECTION_TIMEOUT || - SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_BUS_RESET) - { - disableStreaming = TRUE; - } - else if ((senseBuffer->SenseKey &0xf) == SCSI_SENSE_UNIT_ATTENTION) - { - if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_BUS_RESET || - senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_INSUFFICIENT_TIME_FOR_OPERATION) - { - disableStreaming = TRUE; - } - } - else if ((senseBuffer->SenseKey &0xf) == SCSI_SENSE_ILLEGAL_REQUEST) - { - // LBA Out of Range is an exception, as it's more likely to be caused by - // upper layers attempting to read/write a wrong LBA. - if (senseBuffer->AdditionalSenseCode != SCSI_ADSENSE_ILLEGAL_BLOCK) - { - disableStreaming = TRUE; - } - } - - if (disableStreaming) - { - // if the failure looks permanent, we disable streaming for all future reads/writes - // and retry the command immediately - SET_FLAG(DeviceExtension->PrivateFdoData->HackFlags, FDO_HACK_NO_STREAMING); - *Retry = TRUE; - *RetryIntervalIn100ns = 0; - } - else - { - // if the failure looks transient, we simply fail the current request without retries - // to minimize the time of processing - *Retry = FALSE; - } - } - - // Special-case handling of READ/WRITE commands. These commands now have a 120 second timeout, - // but the preferred behavior (and that taken by many drives) is to immediately report 2/4/x - // on OPC and similar commands. Thus, retries must occur for at least 160 seconds - // (120 seconds + four 10 second retries) as a conservative guess. - // Note: 160s retry time is also a result of discussion with OEMs for case of 2/4/7 and 2/4/8. - if (*Retry) - { - if ((Total100nsSinceFirstSend < 0) || - (((senseBuffer->SenseKey &0xf) == SCSI_SENSE_HARDWARE_ERROR) && (senseBuffer->AdditionalSenseCode == 0x09))) - { - // time information is not valid. use default retry count. - // or if it's SERVO FAILURE, use retry count instead of 160s retry. - *Retry = (RetriedCount <= TOTAL_COUNT_RETRY_DEFAULT); - } - else if (Total100nsSinceFirstSend > SECONDS_TO_100NS_UNITS(TOTAL_SECONDS_RETRY_TIME_WRITE)) - { - *Retry = FALSE; - } - - // How long should we request a delay for during writing? This depends entirely on - // the current write speed of the drive. If we request retries too quickly, - // we can overload the processor on the drive (resulting in garbage being written), - // but too slowly results in lesser performance. - // - *RetryIntervalIn100ns = DeviceExtension->DeviceAdditionalData.ReadWriteRetryDelay100nsUnits; - - } // end retry for 160 seconds modification - } - else if (opCode == SCSIOP_GET_PERFORMANCE) - { - if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_DATA_OVERRUN) - { - // This is a HACK. - // Atapi returns SRB_STATUS_DATA_OVERRUN when it really means - // underrun (i.e. success, and the buffer is longer than needed). - // So treat this as a success. - // When the caller of this function sees that the status was changed to success, - // it will add the transferred length to the original irp. - *Status = STATUS_SUCCESS; - *Retry = FALSE; - } - - if ((Srb->SenseInfoBufferLength < RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA,AdditionalSenseCodeQualifier)) || - !TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) - { - // If get configuration command is failing and if the request type is TYPE ONE - // then most likely the device does not support this request type. Set the - // flag so that the TYPE ONE requests will be tried as TYPE ALL requets. - if ((SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS) && - (SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_DATA_OVERRUN) && - (((PCDB)Srb->Cdb)->GET_CONFIGURATION.RequestType == SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE)) - { - - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "TYPE ONE GetConfiguration failed. Set hack flag and retry.\n")); - SET_FLAG(DeviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_TYPE_ONE_GET_CONFIG); - *Retry = TRUE; - } - } - - // limit retries to GET_PERFORMANCE commands to default retry count - if (RetriedCount > TOTAL_COUNT_RETRY_DEFAULT) - { - *Retry = FALSE; - } - } - else // default handler -- checks for retry count only. - { - if (RetriedCount > TOTAL_COUNT_RETRY_DEFAULT) - { - *Retry = FALSE; - } - } - - return; -} - - -VOID -SenseInfoInterpretRefineByIoControl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG IoControlCode, - _In_ BOOLEAN OverrideVerifyVolume, - _Inout_ BOOLEAN* Retry, - _Inout_ NTSTATUS* Status - ) -/*++ - -Routine Description: - - Based on IOCTL code, modify the interpretion result. - -Arguments: - - Device - Supplies the device object associated with this request. - OriginalRequest - the irp that error occurs on. - Srb - Supplies the scsi request block which failed. - MajorFunctionCode - Supplies the function code to be used for logging. - IoDeviceCode - Supplies the device code to be used for logging. - PreviousRetryCount - retried count. - RequestHistory_DoNotUse - the history list - -Return Value: - - BOOLEAN TRUE: Drivers should retry this request. - FALSE: Drivers should not retry this request. - Status - Returns the status for the request. - RetryInterval - Number of seconds before the request should be retried. - Zero indicates the request should be immediately retried. - ---*/ -{ - PAGED_CODE(); - - if ((IoControlCode == IOCTL_CDROM_GET_LAST_SESSION) || - (IoControlCode == IOCTL_CDROM_READ_TOC) || - (IoControlCode == IOCTL_CDROM_READ_TOC_EX) || - (IoControlCode == IOCTL_CDROM_GET_CONFIGURATION)|| - (IoControlCode == IOCTL_CDROM_GET_VOLUME)) - { - if (*Status == STATUS_DATA_OVERRUN) - { - *Status = STATUS_SUCCESS; - *Retry = FALSE; - } - } - - if (IoControlCode == IOCTL_CDROM_READ_Q_CHANNEL) - { - PLAY_ACTIVE(DeviceExtension) = FALSE; - } - - // If the status is verified required and the this request - // should bypass verify required then retry the request. - if (OverrideVerifyVolume && (*Status == STATUS_VERIFY_REQUIRED)) - { - // note: status gets overwritten here - *Status = STATUS_IO_DEVICE_ERROR; - *Retry = TRUE; - - if ((IoControlCode == IOCTL_CDROM_CHECK_VERIFY) || - (IoControlCode == IOCTL_STORAGE_CHECK_VERIFY) || - (IoControlCode == IOCTL_STORAGE_CHECK_VERIFY2) || - (IoControlCode == IOCTL_DISK_CHECK_VERIFY) - ) - { - // Update the geometry information, as the media could have changed. - (VOID) MediaReadCapacity(DeviceExtension->Device); - } // end of ioctls to update capacity - } - - if (!NT_SUCCESS(*Status) && (IoControlCode == IOCTL_CDROM_SET_SPEED)) - { - // If set speed request fails then we should disable the restore speed option. - // Otherwise we will try to restore to default speed on next media change, - // if requested by the caller. - DeviceExtension->DeviceAdditionalData.RestoreDefaults = FALSE; - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "Disable restore default\n")); - } - - return; -} - -BOOLEAN -SenseInfoInterpret( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ ULONG RetriedCount, - _Out_ NTSTATUS* Status, - _Out_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ) -/*++ - -SenseInfoInterpret() - -Routine Description: - - This routine interprets the data returned from the SCSI request sense. - It determines the status to return in the IRP - and whether this request can be retried. - -Arguments: - - Device - Supplies the device object associated with this request. - Srb - Supplies the scsi request block which failed. - MajorFunctionCode - Supplies the function code to be used for logging. - IoDeviceCode - Supplies the device code to be used for logging. - -Return Value: - - BOOLEAN TRUE: Drivers should retry this request. - FALSE: Drivers should not retry this request. - Status - Returns the status for the request. - RetryInterval - Number of seconds before the request should be retried. - Zero indicates the request should be immediately retried. - ---*/ -{ - ULONG retryIntervalInSeconds = 0; - BOOLEAN retry = TRUE; - PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer; - ULONG readSector = 0; - ERROR_LOG_CONTEXT logContext; - - UCHAR majorFunctionCode = 0; - ULONG ioControlCode = 0; - BOOLEAN overrideVerifyVolume = FALSE; - ULONGLONG total100nsSinceFirstSend = 0; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - // - *Status = STATUS_IO_DEVICE_ERROR; - - RtlZeroMemory(&logContext, sizeof(ERROR_LOG_CONTEXT)); - logContext.ErrorCode = -1; - - // Get Original Request related information - SenseInfoRequestGetInformation(Request, - &majorFunctionCode, - &ioControlCode, - &overrideVerifyVolume, - &total100nsSinceFirstSend); - - if(TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING)) - { - // Log anything remotely incorrect about paging i/o - logContext.LogError = TRUE; - logContext.UniqueErrorValue = 301; - logContext.ErrorCode = IO_WARNING_PAGING_FAILURE; - } - - // must handle the SRB_STATUS_INTERNAL_ERROR case first, - // as it has all the flags set. - if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_INTERNAL_ERROR) - { - TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, - "SenseInfoInterpret: Internal Error code is %x\n", - Srb->InternalStatus)); - - retry = FALSE; - *Status = Srb->InternalStatus; - } - else if (Srb->ScsiStatus == SCSISTAT_RESERVATION_CONFLICT) - { - retry = FALSE; - *Status = STATUS_DEVICE_BUSY; - logContext.LogError = FALSE; - } - else if ((Srb->SrbStatus & SRB_STATUS_AUTOSENSE_VALID) && - (Srb->SenseInfoBufferLength >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength))) - { - UCHAR senseKey = (UCHAR)(senseBuffer->SenseKey & 0x0f); - UCHAR additionalSenseCode = 0; - UCHAR additionalSenseCodeQual = 0; - - // Zero the additional sense code and additional sense code qualifier - // if they were not returned by the device. - readSector = senseBuffer->AdditionalSenseLength + offsetof(SENSE_DATA, AdditionalSenseLength); - if (readSector > Srb->SenseInfoBufferLength) - { - readSector = Srb->SenseInfoBufferLength; - } - - additionalSenseCode = (readSector >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCode)) ? - senseBuffer->AdditionalSenseCode : 0; - additionalSenseCodeQual = (readSector >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCodeQualifier)) ? - senseBuffer->AdditionalSenseCodeQualifier : 0; - - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SCSI Error - \n" - "\tcdb: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n" - "\tsrb status: %X; sense: %02X/%02X/%02X; Retried count: %d\n\n", - Srb->Cdb[0], Srb->Cdb[1], Srb->Cdb[2], Srb->Cdb[3], Srb->Cdb[4], Srb->Cdb[5], - Srb->Cdb[6], Srb->Cdb[7], Srb->Cdb[8], Srb->Cdb[9], Srb->Cdb[10], Srb->Cdb[11], - Srb->Cdb[12], Srb->Cdb[13], Srb->Cdb[14], Srb->Cdb[15], - SRB_STATUS(Srb->SrbStatus), - senseKey, - additionalSenseCode, - additionalSenseCodeQual, - RetriedCount)); - - if (senseKey == SCSI_SENSE_UNIT_ATTENTION) - { - ULONG mediaChangeCount; - - // A media change may have occured so increment the change count for the physical device - mediaChangeCount = InterlockedIncrement((PLONG)&DeviceExtension->MediaChangeCount); - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_MCN, - "SenseInfoInterpret: Media change count for device %d incremented to %#lx\n", - DeviceExtension->DeviceNumber, mediaChangeCount)); - } - - if ((zpoddInfo != NULL) && - (((PCDB)Srb->Cdb)->CDB6GENERIC.OperationCode == SCSIOP_TEST_UNIT_READY)) - { - // This sense code is in response to the Test Unit Ready sent during delayed power down - // request. Copy the sense data into the zpoddInfo structure for later processing. - zpoddInfo->SenseKey = senseKey; - zpoddInfo->AdditionalSenseCode = additionalSenseCode; - zpoddInfo->AdditionalSenseCodeQualifier = additionalSenseCodeQual; - } - - // Interpret error by specific ASC & ASCQ first, - // If the error is not handled, interpret using f - { - BOOLEAN notHandled = FALSE; - notHandled = SenseInfoInterpretByAdditionalSenseCode(DeviceExtension, - Srb, - additionalSenseCode, - additionalSenseCodeQual, - Status, - &retry, - &retryIntervalInSeconds, - &logContext); - - if (notHandled) - { - SenseInfoInterpretBySenseKey(DeviceExtension, - senseBuffer, - senseKey, - Status, - &retry, - &retryIntervalInSeconds, - &logContext); - } - } - - // Try to determine the bad sector from the inquiry data. - if ((IS_SCSIOP_READWRITE(((PCDB)Srb->Cdb)->CDB10.OperationCode)) || - (((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_VERIFY) || - (((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_VERIFY16)) - { - ULONG index; - readSector = 0; - - for (index = 0; index < 4; index++) - { - logContext.BadSector = (logContext.BadSector << 8) | senseBuffer->Information[index]; - } - - for (index = 0; index < 4; index++) - { - readSector = (readSector << 8) | Srb->Cdb[index+2]; - } - - index = (((PCDB)Srb->Cdb)->CDB10.TransferBlocksMsb << 8) | - ((PCDB)Srb->Cdb)->CDB10.TransferBlocksLsb; - - // Make sure the bad sector is within the read sectors. - if (!(logContext.BadSector >= readSector && logContext.BadSector < (readSector + index))) - { - logContext.BadSector = readSector; - } - } - } - else - { - // Request sense buffer not valid. No sense information - // to pinpoint the error. Return general request fail. - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "SCSI Error - \n" - "\tcdb: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n" - "\tsrb status: %X; sense info not valid; Retried count: %d\n\n", - Srb->Cdb[0], Srb->Cdb[1], Srb->Cdb[2], Srb->Cdb[3], Srb->Cdb[4], Srb->Cdb[5], - Srb->Cdb[6], Srb->Cdb[7], Srb->Cdb[8], Srb->Cdb[9], Srb->Cdb[10], Srb->Cdb[11], - Srb->Cdb[12], Srb->Cdb[13], Srb->Cdb[14], Srb->Cdb[15], - SRB_STATUS(Srb->SrbStatus), - RetriedCount)); - - SenseInfoInterpretBySrbStatus(DeviceExtension, - Srb, - RetriedCount, - Status, - &retry, - &retryIntervalInSeconds, - &logContext); - } - - // all functions using unit - seconds for retry Interval already be called. - *RetryIntervalIn100ns = SECONDS_TO_100NS_UNITS(retryIntervalInSeconds); - - // call the device specific error handler if it has one. - // DeviceErrorHandlerForMmmc() for all MMC devices - // or DeviceErrorHandlerForHitachiGD2000() for HITACHI GD-2000, HITACHI DVD-ROM GD-2000 - if (DeviceExtension->DeviceAdditionalData.ErrorHandler) - { - DeviceExtension->DeviceAdditionalData.ErrorHandler(DeviceExtension, Srb, Status, &retry); - } - - // Refine retry based on SCSI command - SenseInfoInterpretRefineByScsiCommand(DeviceExtension, - Srb, - RetriedCount, - total100nsSinceFirstSend, - overrideVerifyVolume, - &retry, - Status, - RetryIntervalIn100ns); - - // Refine retry based on IOCTL code. - if (majorFunctionCode == IRP_MJ_DEVICE_CONTROL) - { - SenseInfoInterpretRefineByIoControl(DeviceExtension, - ioControlCode, - overrideVerifyVolume, - &retry, - Status); - } - - // LOG the error: - // Always log the error in our internal log. - // If logError is set, also log the error in the system log. - SenseInfoLogError(DeviceExtension, - Srb, - majorFunctionCode, - ioControlCode, - RetriedCount, - Status, - &retry, - &logContext); - - // all process about the error done. check if the irp was cancelled. - if ((!NT_SUCCESS(*Status)) && retry) - { - PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request); - - if ((requestContext->OriginalRequest != NULL) && - WdfRequestIsCanceled(requestContext->OriginalRequest) - ) - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Request %p was cancelled when it would have been retried\n", - requestContext->OriginalRequest)); - - *Status = STATUS_CANCELLED; - retry = FALSE; - *RetryIntervalIn100ns = 0; - } - } - - // now, all decisions are made. display trace information. - if (retry) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "Command shall be retried in %2I64d.%03I64d seconds\n", - (*RetryIntervalIn100ns / UNIT_100NS_PER_SECOND), - (*RetryIntervalIn100ns / 10000) % 1000 - )); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Will not retry; Sense/ASC/ASCQ of %02x/%02x/%02x\n", - senseBuffer->SenseKey, - senseBuffer->AdditionalSenseCode, - senseBuffer->AdditionalSenseCodeQualifier - )); - } - - return retry; - -} // end SenseInfoInterpret() - - -BOOLEAN -SenseInfoInterpretForZPODD( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ PSCSI_REQUEST_BLOCK Srb, - _Out_ NTSTATUS* Status, - _Out_ _Out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ) -/*++ - -SenseInfoInterpretForZPODD() - -Routine Description: - - This routine interprets the data returned from the SCSI request sense. - It determines the status to return in the IRP - and whether this request can be retried. - -Arguments: - - Device - Supplies the device object associated with this request. - Srb - Supplies the scsi request block which failed. - -Return Value: - - BOOLEAN TRUE: Drivers should retry this request. - FALSE: Drivers should not retry this request. - Status - Returns the status for the request. - RetryInterval - Number of seconds before the request should be retried. - Zero indicates the request should be immediately retried. - ---*/ -{ - BOOLEAN retry = FALSE; - PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer; - ULONG readSector = 0; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - *Status = STATUS_IO_DEVICE_ERROR; - *RetryIntervalIn100ns = 0; - - if (zpoddInfo->RetryFirstCommand != FALSE) - { - // The first command to the logical unit after power resumed will be terminated - // with CHECK CONDITION Status, 6/29/00 POWER ON, RESET, OR BUS DEVICE RESET OCCURRED - - // We have observed some devices return a different sense code, and thus as long as - // the first command after power resume fails, we just retry one more time. - zpoddInfo->RetryFirstCommand = FALSE; - - retry = TRUE; - } - else if ((Srb->SrbStatus & SRB_STATUS_AUTOSENSE_VALID) && - (Srb->SenseInfoBufferLength >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength))) - { - UCHAR senseKey = (UCHAR)(senseBuffer->SenseKey & 0x0f); - UCHAR additionalSenseCode = 0; - UCHAR additionalSenseCodeQual = 0; - - // Zero the additional sense code and additional sense code qualifier - // if they were not returned by the device. - readSector = senseBuffer->AdditionalSenseLength + offsetof(SENSE_DATA, AdditionalSenseLength); - if (readSector > Srb->SenseInfoBufferLength) - { - readSector = Srb->SenseInfoBufferLength; - } - - additionalSenseCode = (readSector >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCode)) ? - senseBuffer->AdditionalSenseCode : 0; - additionalSenseCodeQual = (readSector >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCodeQualifier)) ? - senseBuffer->AdditionalSenseCodeQualifier : 0; - - // If sense code is 2/4/1, device is becoming ready from ZPODD mode. According to Mt Fuji, device - // could take up to 800msec to be fully operational. - if ((senseKey == SCSI_SENSE_NOT_READY) && - (additionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY) && - (additionalSenseCodeQual == SCSI_SENSEQ_BECOMING_READY)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "SenseInfoInterpretForZPODD: In process of becoming ready\n")); - - zpoddInfo->BecomingReadyRetryCount--; - - if (zpoddInfo->BecomingReadyRetryCount > 0) - { - DEVICE_EVENT_BECOMING_READY notReady = {0}; - - retry = TRUE; - *Status = STATUS_DEVICE_NOT_READY; - *RetryIntervalIn100ns = BECOMING_READY_RETRY_INTERNVAL_IN_100NS; - - notReady.Version = 1; - notReady.Reason = 1; - notReady.Estimated100msToReady = (ULONG) *RetryIntervalIn100ns / (1000 * 1000); - DeviceSendNotification(DeviceExtension, - &GUID_IO_DEVICE_BECOMING_READY, - sizeof(DEVICE_EVENT_BECOMING_READY), - ¬Ready); - } - } - } - - // now, all decisions are made. display trace information. - if (retry) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL, - "Command shall be retried in %2I64d.%03I64d seconds\n", - (*RetryIntervalIn100ns / UNIT_100NS_PER_SECOND), - (*RetryIntervalIn100ns / 10000) % 1000 - )); - } - else - { - TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL, - "Will not retry; Sense/ASC/ASCQ of %02x/%02x/%02x\n", - senseBuffer->SenseKey, - senseBuffer->AdditionalSenseCode, - senseBuffer->AdditionalSenseCodeQualifier - )); - } - - return retry; - -} // end SenseInfoInterpret() - - -BOOLEAN -RequestSenseInfoInterpret( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ WDFREQUEST Request, - _In_ PSCSI_REQUEST_BLOCK Srb, - _In_ ULONG RetriedCount, - _Out_ NTSTATUS* Status, - _Out_opt_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ) -/*++ - -Routine Description: - -Interpret the error, process it. - 1. Release device queue if it's frozen. - 2. Interpret and process the error. - -Arguments: - - DeviceExtension - Supplies the device object associated with this request. - Request - the Request that error occurs on. - Srb - Supplies the scsi request block which failed. - RetriedCount - retried count. - -Return Value: - - BOOLEAN TRUE: Drivers should retry this request. - FALSE: Drivers should not retry this request. - Status - Returns the status for the request. - RetryIntervalIn100nsUnits - Number of 100ns before the request should be retried. - Zero indicates the request should be immediately retried. - ---*/ -{ - BOOLEAN retry = FALSE; - LONGLONG retryIntervalIn100ns = 0; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SUCCESS) - { - // request succeeded. - if ((zpoddInfo != NULL) && - (zpoddInfo->BecomingReadyRetryCount > 0)) - { - zpoddInfo->BecomingReadyRetryCount = 0; - } - - *Status = STATUS_SUCCESS; - retry = FALSE; - } - else - { - // request failed. We need to process the error. - - // 1. Release the queue if it is frozen. - if (Srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) - { - DeviceReleaseQueue(DeviceExtension->Device); - } - - if ((zpoddInfo != NULL) && - ((zpoddInfo->RetryFirstCommand != FALSE) || (zpoddInfo->BecomingReadyRetryCount > 0))) - { - retry = SenseInfoInterpretForZPODD(DeviceExtension, - Srb, - Status, - &retryIntervalIn100ns); - } - - if (retry == FALSE) - { - // 2. Error Processing - if ((zpoddInfo != NULL) && - (zpoddInfo->BecomingReadyRetryCount > 0)) - { - zpoddInfo->BecomingReadyRetryCount = 0; - } - - retry = SenseInfoInterpret(DeviceExtension, - Request, - Srb, - RetriedCount, - Status, - &retryIntervalIn100ns); - } - } - - if (RetryIntervalIn100ns != NULL) - { - *RetryIntervalIn100ns = retryIntervalIn100ns; - } - - return retry; -} - - -BOOLEAN -RequestSenseInfoInterpretForScratchBuffer( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ ULONG RetriedCount, - _Out_ NTSTATUS* Status, - _Out_ _Deref_out_range_(0, MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS) - LONGLONG* RetryIntervalIn100ns - ) -/*++ - -Routine Description: - - to analyze the error occurred and set the status, retry interval and decide to retry or not. - -Arguments: - - DeviceExtension - device extension - RetriedCount - already retried count. - -Return Value: - - BOOLEAN - TRUE (should retry) - Status - NTSTATUS - RetryIntervalIn100nsUnits - retry interval - ---*/ -{ - NT_ASSERT(DeviceExtension->ScratchContext.ScratchInUse != 0); - - return RequestSenseInfoInterpret(DeviceExtension, - DeviceExtension->ScratchContext.ScratchRequest, - DeviceExtension->ScratchContext.ScratchSrb, - RetriedCount, - Status, - RetryIntervalIn100ns); -} - - diff --git a/storage/class/cdrom/src/zpodd.c b/storage/class/cdrom/src/zpodd.c deleted file mode 100644 index 9e7291438..000000000 --- a/storage/class/cdrom/src/zpodd.c +++ /dev/null @@ -1,823 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation. All rights reserved. - -Module Name: - - zpodd.c - -Abstract: - - Code for Zero Power ODD support. - -Environment: - - kernel mode only - -Notes: - - -Revision History: - ---*/ - -#include "ntddk.h" -#include "ntddstor.h" -#include "wdmguid.h" -#include "cdrom.h" -#include "mmc.h" -#include "ioctl.h" -#include "scratch.h" - -#ifdef DEBUG_USE_WPP -#include "zpodd.tmh" -#endif - -_IRQL_requires_max_(PASSIVE_LEVEL) -ULONG -DeviceGetZPODDEnabledFromRegistry(); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceQueryD3ColdInterface( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PD3COLD_SUPPORT_INTERFACE D3ColdInterface - ); - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSendEnableIdlePowerIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN WakeCapable, - _In_ BOOLEAN Enable, - _In_ ULONG D3IdleTimeout - ); - -#if ALLOC_PRAGMA - -#pragma alloc_text(PAGE, DeviceInitializeZPODD) -#pragma alloc_text(PAGE, DeviceGetZPODDEnabledFromRegistry) -#pragma alloc_text(PAGE, DeviceQueryD3ColdInterface) -#pragma alloc_text(PAGE, DeviceSendEnableIdlePowerIoctl) -#pragma alloc_text(PAGE, DeviceReleaseZPODDResources) -#pragma alloc_text(PAGE, DeviceZPODDIsInHomePosition) -#pragma alloc_text(PAGE, DeviceMarkActive) - -#endif - -#pragma warning(push) -#pragma warning(disable:4152) // nonstandard extension, function/data pointer conversion in expression -#pragma warning(disable:26000) // read overflow reported because of pointer type conversion - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceInitializeZPODD( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine initialize the contents of ZPODD structure. - -Arguments: - - DeviceExtension - the device extension - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - NTSTATUS tempStatus = STATUS_SUCCESS; - PZERO_POWER_ODD_INFO zpoddInfo = NULL; - PFEATURE_DATA_REMOVABLE_MEDIUM removableMediumHeader = NULL; - ULONG ZPODDEnabledInRegistry = 0; - PD3COLD_SUPPORT_INTERFACE d3ColdInterface = NULL; - DEVICE_WAKE_DEPTH deepestWakeableDstate = DeviceWakeDepthNotWakeable; - BOOLEAN inHomePosition = FALSE; - - PAGED_CODE(); - - if (DeviceExtension->ZeroPowerODDInfo != NULL) - { - // - // Already initialized. - // - - goto Cleanup; - } - - ZPODDEnabledInRegistry = DeviceGetZPODDEnabledFromRegistry(); - - if (ZPODDEnabledInRegistry == 0) - { - // - // User has explicitly disabled Zero Power ODD. - // - - status = STATUS_NOT_SUPPORTED; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD not enabled due to registry settings.\n" - )); - - goto Cleanup; - } - - zpoddInfo = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(ZERO_POWER_ODD_INFO), - CDROM_TAG_ZERO_POWER_ODD); - - if (zpoddInfo == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - - goto Cleanup; - } - - // - // Check the system for the following prerequisites: - // - // 1. SATA: Device Attention line - // 2. SATA: Asynchronous Notification - // 3. ODD: LoChange / MediaRemoval - // 4. ACPI: Wake capable - // - // Only drawer and slot loading types have well defined behaviors in the spec, so only these two - // types are supported. - // - - // - // Check for DA & AN - // - - if ((DeviceExtension->PowerDescriptor == NULL) || - (DeviceExtension->PowerDescriptor->DeviceAttentionSupported == FALSE) || - (DeviceExtension->PowerDescriptor->AsynchronousNotificationSupported == FALSE)) - { - status = STATUS_NOT_SUPPORTED; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD not enabled due to SATA features not present.\n" - )); - - goto Cleanup; - } - - // - // Check for LoChange / MediaRemoval - // - - removableMediumHeader = (PFEATURE_DATA_REMOVABLE_MEDIUM) - DeviceFindFeaturePage(DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBuffer, - DeviceExtension->DeviceAdditionalData.Mmc.CapabilitiesBufferSize, - FeatureRemovableMedium); - - if ((removableMediumHeader == NULL) || - !((removableMediumHeader->LoadingMechanism == LOADING_MECHANISM_TRAY) && (removableMediumHeader->Load == 0) && // Drawer ... - (removableMediumHeader->DBML != FALSE)) && // requires LoChange/NotBusy - !((removableMediumHeader->LoadingMechanism == LOADING_MECHANISM_CADDY) && (removableMediumHeader->Load == 0) && // Slot ... - (DeviceExtension->MediaChangeDetectionInfo->Gesn.Supported != FALSE))) // requires MediaRemoval - { - status = STATUS_NOT_SUPPORTED; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD not enabled due to ODD features not present.\n" - )); - - goto Cleanup; - } - - zpoddInfo->LoadingMechanism = removableMediumHeader->LoadingMechanism; - zpoddInfo->Load = removableMediumHeader->Load; - - // - // Check for ACPI - // - - status = DeviceQueryD3ColdInterface(DeviceExtension, &zpoddInfo->D3ColdInterface); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: Query D3Cold support interface failed.\n" - )); - - goto Cleanup; - } - - // - // If the platform supports Zero Power ODD, the following conditions must be met: - // - // 1. The deepest wakeable D-state for the device is D3Cold; - // 2. The platform supports D3Cold for the device. - // - - d3ColdInterface = &zpoddInfo->D3ColdInterface; - - status = d3ColdInterface->GetIdleWakeInfo(d3ColdInterface->Context, - PowerSystemWorking, - &deepestWakeableDstate); - - if (!NT_SUCCESS(status)) - { - goto Cleanup; - } - - // - // DeviceExtension->PowerDescriptor->D3ColdSupported is retrieved from lower layer. - // It has more accurate supportive information than just uses d3ColdInterface->GetD3ColdCapability - // - if ((deepestWakeableDstate != DeviceWakeDepthD3cold) || - (DeviceExtension->PowerDescriptor->D3ColdSupported == FALSE)) - { - status = STATUS_NOT_SUPPORTED; - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD not enabled due to ACPI support not present.\n" - )); - - goto Cleanup; - } - - // - // The system meets all requirements. Go ahead and enable ZPODD. - // - - // - // Register with the runtime power framework. - // Note that no un-registration is needed during tear-down. - // D3Cold will be enabled (success case of following call) or disabled by port driver during processing Enable Idle Power IOCTL. - // - - status = DeviceSendEnableIdlePowerIoctl(DeviceExtension, TRUE, TRUE, DELAY_TIME_TO_ENTER_ZERO_POWER_IN_MS); - - if (!NT_SUCCESS(status)) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD not enabled due to runtime power framework.\n" - )); - - goto Cleanup; - } - - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: ZPODD is enabled.\n" - )); - - DeviceExtension->ZeroPowerODDInfo = zpoddInfo; - - // - // If device is not in home position, then we should take an active reference here - // to prevent it from being powered off. - // - - inHomePosition = DeviceZPODDIsInHomePosition(DeviceExtension); - - if (inHomePosition == FALSE) - { - TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, - "DeviceInitializeZPODD: not ready to power off, device marked as active\n")); - - DeviceMarkActive(DeviceExtension, TRUE, FALSE); - } - else - { - // - // cache get configuration response. - // failing is not critical, so we don't want to check for status here. - // - - if (zpoddInfo->GetConfigurationBuffer == NULL) - { - tempStatus = DeviceGetConfigurationWithAlloc(DeviceExtension->Device, - &zpoddInfo->GetConfigurationBuffer, - &zpoddInfo->GetConfigurationBufferSize, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL); - - UNREFERENCED_PARAMETER(tempStatus); // Avoid PREFAST warning. - } - } - -Cleanup: - - if (!NT_SUCCESS(status)) - { - // - // We register always even in non-ZPODD case, per request from storport. - // - - tempStatus = DeviceSendEnableIdlePowerIoctl(DeviceExtension, FALSE, FALSE, DELAY_TIME_TO_ENTER_ZERO_POWER_IN_MS); - - if (NT_SUCCESS(tempStatus)) - { - // - // Mark the device active; this reference will never be released unless the system enters a - // low power state. - // - - DeviceMarkActive(DeviceExtension, TRUE, FALSE); - } - - FREE_POOL(zpoddInfo); - } - - // - // If Zero Power ODD is not supported, we should not block the device init sequence. - // - - return STATUS_SUCCESS; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -ULONG -DeviceGetZPODDEnabledFromRegistry() -/*++ - -Routine Description: - - Get the ZeroPowerODDEnabled value from registry, which dictates if Zero Power ODD - should be enabled or not. If the value is not in registry, by default Zero - Power ODD is enabled. - -Arguments: - - None - -Return Value: - - ULONG - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - WDFKEY registryKey = NULL; - ULONG ZPODDEnabled = 0; - - DECLARE_CONST_UNICODE_STRING(registryValueName, L"ZeroPowerODDEnabled"); - - PAGED_CODE(); - - // - // open the Parameters key under the service key. - // - - status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(), - KEY_READ, - WDF_NO_OBJECT_ATTRIBUTES, - ®istryKey); - - if (NT_SUCCESS(status)) - { - status = WdfRegistryQueryULong(registryKey, - ®istryValueName, - &ZPODDEnabled); - - WdfRegistryClose(registryKey); - } - - if (!NT_SUCCESS(status)) - { - // - // By default, Zero Power ODD is enabled - // - - ZPODDEnabled = 1; - } - - return ZPODDEnabled; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceQueryD3ColdInterface( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PD3COLD_SUPPORT_INTERFACE D3ColdInterface - ) -/*++ - -Routine Description: - - Queries ACPI for the D3Cold support interface. - -Arguments: - - DeviceExtension - the device extension - D3ColdInterface - output buffer receiving the interface - -Return Value: - - NTSTATUS - ---*/ -{ - PIRP irp = NULL; - KEVENT event; - NTSTATUS status = STATUS_SUCCESS; - PDEVICE_OBJECT targetDevice = NULL; - IO_STATUS_BLOCK ioStatus = {0}; - PIO_STACK_LOCATION irpStack = NULL; - - PAGED_CODE(); - - RtlZeroMemory(D3ColdInterface, sizeof(D3COLD_SUPPORT_INTERFACE)); - - // - // Query D3COLD support interface synchronously - // - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - targetDevice = IoGetAttachedDeviceReference(DeviceExtension->DeviceObject); - - irp = IoBuildSynchronousFsdRequest(IRP_MJ_PNP, - targetDevice, - NULL, - 0, - 0, - &event, - &ioStatus); - - if (irp == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - - goto Cleanup; - } - - irp->IoStatus.Status = STATUS_NOT_SUPPORTED; - irp->IoStatus.Information = 0; - - irpStack = IoGetNextIrpStackLocation(irp); - irpStack->MinorFunction = IRP_MN_QUERY_INTERFACE; - irpStack->Parameters.QueryInterface.InterfaceType = (LPGUID) &GUID_D3COLD_SUPPORT_INTERFACE; - irpStack->Parameters.QueryInterface.Size = sizeof (D3COLD_SUPPORT_INTERFACE); - irpStack->Parameters.QueryInterface.Version = D3COLD_SUPPORT_INTERFACE_VERSION; - irpStack->Parameters.QueryInterface.Interface = (PINTERFACE) D3ColdInterface; - irpStack->Parameters.QueryInterface.InterfaceSpecificData = NULL; - - status = IoCallDriver(targetDevice, irp); - - if (status == STATUS_PENDING) - { - KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); - - status = ioStatus.Status; - } - - if (!NT_SUCCESS(status)) - { - goto Cleanup; - } - - NT_ASSERT(D3ColdInterface->SetD3ColdSupport != NULL); - NT_ASSERT(D3ColdInterface->GetIdleWakeInfo != NULL); - NT_ASSERT(D3ColdInterface->GetD3ColdCapability != NULL); - -Cleanup: - - ObDereferenceObject(targetDevice); - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -NTSTATUS -DeviceSendEnableIdlePowerIoctl( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN WakeCapable, - _In_ BOOLEAN Enable, - _In_ ULONG D3IdleTimeout - ) -/*++ - -Routine Description: - - Enables idle power support. - -Arguments: - - DeviceExtension - the device extension - WakeCapable - whether the device is wake capable - Enable - enable / disable idle power management - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - STORAGE_IDLE_POWER idlePower = {0}; - IO_STATUS_BLOCK ioStatus = {0}; - PIRP irp = NULL; - KEVENT event; - - PAGED_CODE(); - - idlePower.Version = 1; - idlePower.Size = sizeof (STORAGE_IDLE_POWER); - idlePower.WakeCapableHint = WakeCapable; - idlePower.D3ColdSupported = Enable; - idlePower.D3IdleTimeout = D3IdleTimeout; - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - irp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_ENABLE_IDLE_POWER, - DeviceExtension->LowerPdo, - &idlePower, - sizeof(STORAGE_IDLE_POWER), - NULL, - 0, - FALSE, - &event, - &ioStatus); - - if (irp == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - // - // Send the synchronous request to port driver. - // - - status = IoCallDriver(DeviceExtension->LowerPdo, irp); - - if (status == STATUS_PENDING) - { - KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); - - status = ioStatus.Status; - } - } - - TracePrint((TRACE_LEVEL_INFORMATION, - TRACE_FLAG_POWER, - "DeviceSendEnableIdlePowerIoctl: Port driver returned status (%x) for FDO (%p)\n" - "\tD3ColdSupported: %u\n" - "\tD3IdleTimeout: %u (ms)", - status, - DeviceExtension->DeviceObject, - Enable, - DELAY_TIME_TO_ENTER_ZERO_POWER_IN_MS)); - - return status; -} - -_IRQL_requires_max_(APC_LEVEL) -VOID -DeviceReleaseZPODDResources( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - This routine will cleanup any resources allocated for ZPODD. - -Arguments: - - DeviceExtension - the device context - -Return Value: - None. - ---*/ -{ - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - PAGED_CODE() - - if (zpoddInfo != NULL) - { - FREE_POOL(zpoddInfo->GetConfigurationBuffer); - FREE_POOL(zpoddInfo); - } - - return; -} - -NTSTATUS -DeviceZPODDGetPowerupReason( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _Out_ PSTORAGE_IDLE_POWERUP_REASON PowerupReason - ) -/*++ - -Routine Description: - - This routine queries the port driver for what caused the power up. - -Arguments: - - DeviceExtension - device extension. - PowerupReason - what caused the power up. - -Return Value: - NTSTATUS - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PIRP irp = NULL; - IO_STATUS_BLOCK ioStatus = {0}; - KEVENT event; - - RtlZeroMemory(PowerupReason, sizeof (STORAGE_IDLE_POWERUP_REASON)); - - PowerupReason->Size = sizeof (STORAGE_IDLE_POWERUP_REASON); - PowerupReason->Version = STORAGE_IDLE_POWERUP_REASON_VERSION_V1; - - // - // Setup a synchronous irp. - // - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - irp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_GET_IDLE_POWERUP_REASON, - DeviceExtension->LowerPdo, - PowerupReason, - sizeof (STORAGE_IDLE_POWERUP_REASON), - PowerupReason, - sizeof (STORAGE_IDLE_POWERUP_REASON), - FALSE, - &event, - &ioStatus); - - if (irp == NULL) - { - status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - // - // Send the synchronous request to port driver. - // - - status = IoCallDriver(DeviceExtension->LowerPdo, irp); - - if (status == STATUS_PENDING) - { - KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); - - status = ioStatus.Status; - } - } - - return status; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -BOOLEAN -DeviceZPODDIsInHomePosition( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension - ) -/*++ - -Routine Description: - - Checks to see if the device is ready to be powered off. - Requirements are: 1. tray closed 2. no media present. - -Arguments: - - DeviceExtension - device extension. - -Return Value: - BOOLEAN - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - SCSI_REQUEST_BLOCK srb = {0}; - PCDB cdb = (PCDB) srb.Cdb; - BOOLEAN inHomePosition = FALSE; - - PAGED_CODE(); - - if (zpoddInfo != NULL) - { - // - // Clear sense data. - // - - zpoddInfo->SenseKey = 0; - zpoddInfo->AdditionalSenseCode = 0; - zpoddInfo->AdditionalSenseCodeQualifier = 0; - - // - // Send a Test Unit Ready to check media & tray status. - // - - RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK)); - - srb.CdbLength = 6; - cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY; - - srb.TimeOutValue = CDROM_TEST_UNIT_READY_TIMEOUT; - - status = DeviceSendSrbSynchronously(DeviceExtension->Device, - &srb, - NULL, - 0, - FALSE, - NULL); - - // - // At this time, sense data, if available, is already copied into zpoddInfo. - // - // We don't check for status because we expect it to fail in case there is no media in device. - // - // Should enter Zero Power state if: - // - // Drawer: 02/3A/01 - // Slot: 02/3A/xx - // - - if (((zpoddInfo->LoadingMechanism == LOADING_MECHANISM_TRAY) && (zpoddInfo->Load == 0) && // Drawer - (zpoddInfo->SenseKey == SCSI_SENSE_NOT_READY) && - (zpoddInfo->AdditionalSenseCode == SCSI_ADSENSE_NO_MEDIA_IN_DEVICE) && - (zpoddInfo->AdditionalSenseCodeQualifier == 0x01)) || - ((zpoddInfo->LoadingMechanism == LOADING_MECHANISM_CADDY) && (zpoddInfo->Load == 0) && // Slot - (zpoddInfo->SenseKey == SCSI_SENSE_NOT_READY) && - (zpoddInfo->AdditionalSenseCode == SCSI_ADSENSE_NO_MEDIA_IN_DEVICE))) - { - inHomePosition = TRUE; - } - } - - return inHomePosition; -} - -_IRQL_requires_max_(PASSIVE_LEVEL) -VOID -DeviceMarkActive( - _In_ PCDROM_DEVICE_EXTENSION DeviceExtension, - _In_ BOOLEAN IsActive, - _In_ BOOLEAN SetIdleTimeout - ) -/*++ - -Routine Description: - - This routine will mark the device as active / idle. - -Arguments: - - DeviceExtension - the device context - IsActive - if the device should be marked as active - -Return Value: - None. - ---*/ -{ - NTSTATUS status = STATUS_SUCCESS; - PZERO_POWER_ODD_INFO zpoddInfo = DeviceExtension->ZeroPowerODDInfo; - - PAGED_CODE() - - if (DeviceExtension->IsActive != IsActive) - { - if ((IsActive == FALSE) && (zpoddInfo != NULL)) - { - // cache get configuration response. - // failing is not critical, so we don't want to check for status here. - if (zpoddInfo->GetConfigurationBuffer == NULL) - { - (VOID)DeviceGetConfigurationWithAlloc(DeviceExtension->Device, - &zpoddInfo->GetConfigurationBuffer, - &zpoddInfo->GetConfigurationBufferSize, - FeatureProfileList, - SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL); - } - } - - if (SetIdleTimeout) - { - status = DeviceSendEnableIdlePowerIoctl(DeviceExtension, - FALSE, - FALSE, - IsActive ? DELAY_TIME_TO_ENTER_ZERO_POWER_IN_MS : DELAY_TIME_TO_ENTER_AOAC_IDLE_POWER_IN_MS); - } - - if (NT_SUCCESS(status)) - { - DeviceSendIoctlAsynchronously(DeviceExtension, - IsActive ? IOCTL_STORAGE_POWER_ACTIVE : IOCTL_STORAGE_POWER_IDLE, - DeviceExtension->LowerPdo); - } - - DeviceExtension->IsActive = IsActive; - } -} - -#pragma warning(pop) // un-sets any local warning changes - - diff --git a/storage/class/classpnp/src/classpnp.vcxproj b/storage/class/classpnp/src/classpnp.vcxproj index 2727ab878..4b092509b 100644 --- a/storage/class/classpnp/src/classpnp.vcxproj +++ b/storage/class/classpnp/src/classpnp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver ExportDriver WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver ExportDriver WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver ExportDriver WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver ExportDriver WindowsKernelModeDriver10.0 Driver diff --git a/storage/class/disk/src/diskdev.inf b/storage/class/disk/src/diskdev.inf index 70e8fad15..96948f388 100644 Binary files a/storage/class/disk/src/diskdev.inf and b/storage/class/disk/src/diskdev.inf differ diff --git a/storage/filters/addfilter/src/addfilter.vcxproj b/storage/filters/addfilter/src/addfilter.vcxproj index 1cb9300f4..7216a90ab 100644 --- a/storage/filters/addfilter/src/addfilter.vcxproj +++ b/storage/filters/addfilter/src/addfilter.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/storage/miniports/storahci/src/inbox/storahci.vcxproj b/storage/miniports/storahci/src/inbox/storahci.vcxproj index cd55b82af..fbe467392 100644 --- a/storage/miniports/storahci/src/inbox/storahci.vcxproj +++ b/storage/miniports/storahci/src/inbox/storahci.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver Miniport WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver Miniport WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver Miniport WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver Miniport WindowsKernelModeDriver10.0 Driver diff --git a/storage/msdsm/src/SampleDSM.vcxproj b/storage/msdsm/src/SampleDSM.vcxproj index 308353caa..5387d218b 100644 --- a/storage/msdsm/src/SampleDSM.vcxproj +++ b/storage/msdsm/src/SampleDSM.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver diff --git a/storage/sfloppy/README.md b/storage/sfloppy/README.md deleted file mode 100644 index d05748dfa..000000000 --- a/storage/sfloppy/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -page_type: sample -description: "A sample class driver for Super Floppy disk drives." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Super Floppy (sfloppy) Storage Class Driver - -The sfloppy sample is a super floppy driver. This driver is a class driver for Super Floppy disk drives. - -## Universal Windows Driver Compliant - -This sample builds a Universal Windows Driver. It uses only APIs and DDIs that are included in OneCoreUAP. - -## Installation and Operation - -This sample sits a level above the port driver (ATAPI, USB, and so on) in the driver stack and controls communication between the application level and the port driver. The floppy driver takes requests from file system drivers and then sends the appropriate [**SCSI\_REQUEST\_BLOCK**](https://docs.microsoft.com/windows-hardware/drivers/ddi/content/srb/ns-srb-_scsi_request_block) (SRB) to the port driver. - -For more information, see [Introduction to Storage Class Drivers](https://docs.microsoft.com/windows-hardware/drivers/storage/introduction-to-storage-class-drivers) in the storage technologies design guide. diff --git a/storage/sfloppy/sfloppy.sln b/storage/sfloppy/sfloppy.sln deleted file mode 100644 index ad9d60c3e..000000000 --- a/storage/sfloppy/sfloppy.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sfloppy", "src\sfloppy.vcxproj", "{97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Debug|Win32.Build.0 = Debug|Win32 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Release|Win32.ActiveCfg = Release|Win32 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Release|Win32.Build.0 = Release|Win32 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Debug|x64.ActiveCfg = Debug|x64 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Debug|x64.Build.0 = Debug|x64 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Release|x64.ActiveCfg = Release|x64 - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/storage/sfloppy/src/floppy.c b/storage/sfloppy/src/floppy.c deleted file mode 100644 index 282885a60..000000000 --- a/storage/sfloppy/src/floppy.c +++ /dev/null @@ -1,3428 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, 1991 - 1999 - -Module Name: - - floppy.c - -Abstract: - - SCSI floppy class driver - -Author: - - Jeff Havens (jhavens) - -Environment: - - kernel mode only - -Notes: - -Revision History: -02/28/96 georgioc Merged this code with code developed by compaq in - parallel with microsoft, for 120MB floppy support. - -01/17/96 georgioc Made code PNP aware (uses the new \storage\classpnp/scsiport) - ---*/ - -#pragma warning(disable:4214) // nonstandard extension used : bit field types other than int -#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#define MODE_DATA_SIZE 192 -#define SCSI_FLOPPY_TIMEOUT 20 -#define SFLOPPY_SRB_LIST_SIZE 4 -#define SFLOPPY_TAG 'poFS' -// -// Define all possible drive/media combinations, given drives listed above -// and media types in ntdddisk.h. -// -// These values are used to index the DriveMediaConstants table. -// - -#define NUMBER_OF_DRIVE_TYPES 7 -#define DRIVE_TYPE_120M 4 //120MB Floptical -#define DRIVE_TYPE_NONE NUMBER_OF_DRIVE_TYPES - -// -// This array describes all media types we support. -// It should be arranged in the increasing order of density -// -// For a given drive, we list all the mediatypes that will -// work with that drive. For instance, a 120MB drive will -// take 720KB media, 1.44MB media, and 120MB media. -// -// Note that, DriveMediaConstants given below is grouped -// as drive and media combination -// -typedef enum _DRIVE_MEDIA_TYPE { - Drive360Media160, // 5.25" 360k drive; 160k media - Drive360Media180, // 5.25" 360k drive; 180k media - Drive360Media320, // 5.25" 360k drive; 320k media - Drive360Media32X, // 5.25" 360k drive; 320k 1k secs - Drive360Media360, // 5.25" 360k drive; 360k media - Drive720Media720, // 3.5" 720k drive; 720k media - Drive120Media160, // 5.25" 1.2Mb drive; 160k media - Drive120Media180, // 5.25" 1.2Mb drive; 180k media - Drive120Media320, // 5.25" 1.2Mb drive; 320k media - Drive120Media32X, // 5.25" 1.2Mb drive; 320k 1k secs - Drive120Media360, // 5.25" 1.2Mb drive; 360k media - Drive120Media120, // 5.25" 1.2Mb drive; 1.2Mb media - Drive144Media720, // 3.5" 1.44Mb drive; 720k media - Drive144Media144, // 3.5" 1.44Mb drive; 1.44Mb media - Drive288Media720, // 3.5" 2.88Mb drive; 720k media - Drive288Media144, // 3.5" 2.88Mb drive; 1.44Mb media - Drive288Media288, // 3.5" 2.88Mb drive; 2.88Mb media - Drive2080Media720, // 3.5" 20.8Mb drive; 720k media - Drive2080Media144, // 3.5" 20.8Mb drive; 1.44Mb media - Drive2080Media2080, // 3.5" 20.8Mb drive; 20.8Mb media - Drive32MMedia32M, // 3.5" 32Mb drive; 32MB media - Drive120MMedia720, // 3.5" 120Mb drive; 720k media - Drive120MMedia144, // 3.5" 120Mb drive; 1.44Mb media - Drive120MMedia120M, // 3.5" 120Mb drive; 120Mb media - Drive240MMedia144M, // 3.5" 240Mb drive; 1.44Mb media - Drive240MMedia120M, // 3.5" 240Mb drive; 120Mb media - Drive240MMedia240M // 3.5" 240Mb drive; 240Mb media -} DRIVE_MEDIA_TYPE; - -// -// When we want to determine the media type in a drive, we will first -// guess that the media with highest possible density is in the drive, -// and keep trying lower densities until we can successfully read from -// the drive. -// -// These values are used to select a DRIVE_MEDIA_TYPE value. -// -// The following table defines ranges that apply to the DRIVE_MEDIA_TYPE -// enumerated values when trying media types for a particular drive type. -// Note that for this to work, the DRIVE_MEDIA_TYPE values must be sorted -// by ascending densities within drive types. Also, for maximum track -// size to be determined properly, the drive types must be in ascending -// order. -// - -typedef struct _DRIVE_MEDIA_LIMITS { - DRIVE_MEDIA_TYPE HighestDriveMediaType; - DRIVE_MEDIA_TYPE LowestDriveMediaType; -} DRIVE_MEDIA_LIMITS, *PDRIVE_MEDIA_LIMITS; - -#if 0 -DRIVE_MEDIA_LIMITS DriveMediaLimits[NUMBER_OF_DRIVE_TYPES] = { - - { Drive360Media360, Drive360Media160 }, // DRIVE_TYPE_0360 - { Drive120Media120, Drive120Media160 }, // DRIVE_TYPE_1200 - { Drive720Media720, Drive720Media720 }, // DRIVE_TYPE_0720 - { Drive144Media144, Drive144Media720 }, // DRIVE_TYPE_1440 - { Drive288Media288, Drive288Media720 }, // DRIVE_TYPE_2880 - { Drive2080Media2080, Drive2080Media720 } -}; -#else -DRIVE_MEDIA_LIMITS DriveMediaLimits[NUMBER_OF_DRIVE_TYPES] = { - - { Drive720Media720, Drive720Media720 }, // DRIVE_TYPE_0720 - { Drive144Media144, Drive144Media720}, // DRIVE_TYPE_1440 - { Drive288Media288, Drive288Media720}, // DRIVE_TYPE_2880 - { Drive2080Media2080, Drive2080Media720 }, - { Drive32MMedia32M, Drive32MMedia32M }, // DRIVE_TYPE_32M - { Drive120MMedia120M, Drive120MMedia720 }, // DRIVE_TYPE_120M - { Drive240MMedia240M, Drive240MMedia144M } // DRIVE_TYPE_240M -}; - -#endif -// -// For each drive/media combination, define important constants. -// - -typedef struct _DRIVE_MEDIA_CONSTANTS { - MEDIA_TYPE MediaType; - USHORT BytesPerSector; - UCHAR SectorsPerTrack; - USHORT MaximumTrack; - UCHAR NumberOfHeads; -} DRIVE_MEDIA_CONSTANTS, *PDRIVE_MEDIA_CONSTANTS; - -// -// Magic value to add to the SectorLengthCode to use it as a shift value -// to determine the sector size. -// - -#define SECTORLENGTHCODE_TO_BYTESHIFT 7 - -// -// The following values were gleaned from many different sources, which -// often disagreed with each other. Where numbers were in conflict, I -// chose the more conservative or most-often-selected value. -// - -DRIVE_MEDIA_CONSTANTS DriveMediaConstants[] = - { - - { F5_160_512, 0x200, 0x08, 0x27, 0x1 }, - { F5_180_512, 0x200, 0x09, 0x27, 0x1 }, - { F5_320_1024, 0x400, 0x04, 0x27, 0x2 }, - { F5_320_512, 0x200, 0x08, 0x27, 0x2 }, - { F5_360_512, 0x200, 0x09, 0x27, 0x2 }, - - { F3_720_512, 0x200, 0x09, 0x4f, 0x2 }, - - { F5_160_512, 0x200, 0x08, 0x27, 0x1 }, - { F5_180_512, 0x200, 0x09, 0x27, 0x1 }, - { F5_320_1024, 0x400, 0x04, 0x27, 0x2 }, - { F5_320_512, 0x200, 0x08, 0x27, 0x2 }, - { F5_360_512, 0x200, 0x09, 0x27, 0x2 }, - { F5_1Pt2_512, 0x200, 0x0f, 0x4f, 0x2 }, - - { F3_720_512, 0x200, 0x09, 0x4f, 0x2 }, - { F3_1Pt44_512, 0x200, 0x12, 0x4f, 0x2 }, - - { F3_720_512, 0x200, 0x09, 0x4f, 0x2 }, - { F3_1Pt44_512, 0x200, 0x12, 0x4f, 0x2 }, - { F3_2Pt88_512, 0x200, 0x24, 0x4f, 0x2 }, - - { F3_720_512, 0x200, 0x09, 0x4f, 0x2 }, - { F3_1Pt44_512, 0x200, 0x12, 0x4f, 0x2 }, - { F3_20Pt8_512, 0x200, 0x1b, 0xfa, 0x6 }, - - { F3_32M_512, 0x200, 0x20, 0x3ff,0x2}, - - { F3_720_512, 0x200, 0x09, 0x4f, 0x2 }, - { F3_1Pt44_512, 0x200, 0x12, 0x4f, 0x2 }, - { F3_120M_512, 0x200, 0x20, 0x3c2,0x8 }, - - { F3_1Pt44_512, 0x200, 0x12, 0x4f, 0x2 }, - { F3_120M_512, 0x200, 0x20, 0x3c2,0x8 }, - { F3_240M_512, 0x200, 0x38, 0x105,0x20} -}; - - -#define NUMBER_OF_DRIVE_MEDIA_COMBINATIONS sizeof(DriveMediaConstants)/sizeof(DRIVE_MEDIA_CONSTANTS) - -// -// floppy device data -// - -typedef struct _DISK_DATA { - ULONG DriveType; - BOOLEAN IsDMF; - // BOOLEAN EnableDMF; - UNICODE_STRING FloppyInterfaceString; -} DISK_DATA, *PDISK_DATA; - -// -// The FloppyCapacities and FloppyGeometries arrays are used by the -// USBFlopGetMediaTypes() and USBFlopFormatTracks() routines. - -// The FloppyCapacities and FloppyGeometries arrays must be kept in 1:1 sync, -// i.e. each FloppyGeometries[i] must correspond to each FloppyCapacities[i]. - -// Also, the arrays must be kept in sorted ascending order so that they -// are returned in sorted ascending order by IOCTL_DISK_GET_MEDIA_TYPES. -// - -typedef struct _FORMATTED_CAPACITY -{ - ULONG NumberOfBlocks; - - ULONG BlockLength; - - BOOLEAN CanFormat; // return for IOCTL_DISK_GET_MEDIA_TYPES ? - -} FORMATTED_CAPACITY, *PFORMATTED_CAPACITY; - - -FORMATTED_CAPACITY FloppyCapacities[] = -{ - // Blocks BlockLen CanFormat H T B/S S/T - {0x000500, 0x0200, TRUE}, // 2 80 512 8 640 KB F5_640_512 - {0x0005A0, 0x0200, TRUE}, // 2 80 512 9 720 KB F3_720_512 - {0x000960, 0x0200, TRUE}, // 2 80 512 15 1.20 MB F3_1Pt2_512 (Toshiba) - {0x0004D0, 0x0400, TRUE}, // 2 77 1024 8 1.23 MB F3_1Pt23_1024 (NEC) - {0x000B40, 0x0200, TRUE}, // 2 80 512 18 1.44 MB F3_1Pt44_512 - {0x000D20, 0x0200, FALSE}, // 2 80 512 21 1.70 MB DMF - {0x010000, 0x0200, TRUE}, // 2 1024 512 32 32 MB F3_32M_512 - {0x03C300, 0x0200, TRUE}, // 8 963 512 32 120 MB F3_120M_512 - {0x0600A4, 0x0200, TRUE}, // 13 890 512 34 200 MB F3_200Mb_512 (HiFD) - {0x072A00, 0x0200, TRUE} // 32 262 512 56 240 MB F3_240M_512 -}; - -DISK_GEOMETRY FloppyGeometries[] = -{ - // Cyl MediaType Trk/Cyl Sec/Trk Bytes/Sec - {{80,0}, F3_640_512, 2, 8, 512}, - {{80,0}, F3_720_512, 2, 9, 512}, - {{80,0}, F3_1Pt2_512, 2, 15, 512}, - {{77,0}, F3_1Pt23_1024, 2, 8, 1024}, - {{80,0}, F3_1Pt44_512, 2, 18, 512}, - {{80,0}, F3_1Pt44_512, 2, 21, 512}, // DMF -> F3_1Pt44_512 - {{1024,0}, F3_32M_512, 2, 32, 512}, - {{963,0}, F3_120M_512, 8, 32, 512}, - {{890,0}, F3_200Mb_512, 13, 34, 512}, - {{262,0}, F3_240M_512, 32, 56, 512} -}; - -#define FLOPPY_CAPACITIES (sizeof(FloppyCapacities)/sizeof(FloppyCapacities[0])) - -C_ASSERT((sizeof(FloppyGeometries)/sizeof(FloppyGeometries[0])) == FLOPPY_CAPACITIES); - -// -// The following structures are used by USBFlopFormatTracks() -// - -#pragma pack (push, 1) - -typedef struct _CDB12FORMAT -{ - UCHAR OperationCode; - UCHAR DefectListFormat : 3; - UCHAR CmpList : 1; - UCHAR FmtData : 1; - UCHAR LogicalUnitNumber : 3; - UCHAR TrackNumber; - UCHAR InterleaveMsb; - UCHAR InterleaveLsb; - UCHAR Reserved1[2]; - UCHAR ParameterListLengthMsb; - UCHAR ParameterListLengthLsb; - UCHAR Reserved2[3]; -} CDB12FORMAT, *PCDB12FORMAT; - - -typedef struct _DEFECT_LIST_HEADER -{ - UCHAR Reserved1; - UCHAR Side : 1; - UCHAR Immediate : 1; - UCHAR Reserved2 : 2; - UCHAR SingleTrack : 1; - UCHAR DisableCert : 1; - UCHAR Reserved3 : 1; - UCHAR FormatOptionsValid : 1; - UCHAR DefectListLengthMsb; - UCHAR DefectListLengthLsb; -} DEFECT_LIST_HEADER, *PDEFECT_LIST_HEADER; - -typedef struct _FORMAT_UNIT_PARAMETER_LIST -{ - DEFECT_LIST_HEADER DefectListHeader; - FORMATTED_CAPACITY_DESCRIPTOR FormatDescriptor; -} FORMAT_UNIT_PARAMETER_LIST, *PFORMAT_UNIT_PARAMETER_LIST; - -#pragma pack (pop) - -DRIVER_INITIALIZE DriverEntry; - -DRIVER_UNLOAD ScsiFlopUnload; - -DRIVER_ADD_DEVICE ScsiFlopAddDevice; - -NTSTATUS -ScsiFlopInitDevice( - IN PDEVICE_OBJECT Fdo - ); - -NTSTATUS -ScsiFlopStartDevice( - IN PDEVICE_OBJECT Fdo - ); - -NTSTATUS -ScsiFlopRemoveDevice( - IN PDEVICE_OBJECT Fdo, - IN UCHAR Type - ); - -NTSTATUS -ScsiFlopStopDevice( - IN PDEVICE_OBJECT Fdo, - IN UCHAR Type - ); - -BOOLEAN -FindScsiFlops( - IN PDRIVER_OBJECT DriverObject, - IN PUNICODE_STRING RegistryPath, - IN PCLASS_INIT_DATA InitializationData, - IN PDEVICE_OBJECT PortDeviceObject, - IN ULONG PortNumber - ); - -NTSTATUS -ScsiFlopReadWriteVerification( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ); - -NTSTATUS -ScsiFlopDeviceControl( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ); - -BOOLEAN -IsFloppyDevice( - PDEVICE_OBJECT DeviceObject - ); - -NTSTATUS -CreateFlopDeviceObject( - IN PDRIVER_OBJECT DriverObject, - IN PDEVICE_OBJECT PortDeviceObject, - IN ULONG DeviceCount - ); - -NTSTATUS -DetermineMediaType( - PDEVICE_OBJECT DeviceObject - ); - -ULONG -DetermineDriveType( - PDEVICE_OBJECT DeviceObject - ); - -BOOLEAN -FlCheckFormatParameters( - IN PDEVICE_OBJECT DeviceObject, - IN PFORMAT_PARAMETERS FormatParameters - ); - -NTSTATUS -FormatMedia( - PDEVICE_OBJECT DeviceObject, - MEDIA_TYPE MediaType - ); - -NTSTATUS -FlopticalFormatMedia( - PDEVICE_OBJECT DeviceObject, - PFORMAT_PARAMETERS Format - ); - -VOID -ScsiFlopProcessError( - PDEVICE_OBJECT DeviceObject, - PSCSI_REQUEST_BLOCK Srb, - NTSTATUS *Status, - BOOLEAN *Retry - ); - -NTSTATUS -USBFlopGetMediaTypes( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ); - -NTSTATUS -USBFlopFormatTracks( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ); - -#ifdef ALLOC_PRAGMA -#pragma alloc_text(INIT, DriverEntry) - -#pragma alloc_text(PAGE, ScsiFlopUnload) -#pragma alloc_text(PAGE, ScsiFlopAddDevice) -#pragma alloc_text(PAGE, CreateFlopDeviceObject) -#pragma alloc_text(PAGE, ScsiFlopStartDevice) -#pragma alloc_text(PAGE, ScsiFlopRemoveDevice) -#pragma alloc_text(PAGE, IsFloppyDevice) -#pragma alloc_text(PAGE, DetermineMediaType) -#pragma alloc_text(PAGE, DetermineDriveType) -#pragma alloc_text(PAGE, FlCheckFormatParameters) -#pragma alloc_text(PAGE, FormatMedia) -#pragma alloc_text(PAGE, FlopticalFormatMedia) -#pragma alloc_text(PAGE, USBFlopGetMediaTypes) -#pragma alloc_text(PAGE, USBFlopFormatTracks) - -#endif - - -NTSTATUS -DriverEntry( - IN PDRIVER_OBJECT DriverObject, - IN PUNICODE_STRING RegistryPath - ) -/*++ - -Routine Description: - - This is the system initialization routine for installable drivers. - It calls the SCSI class driver initialization routine. - -Arguments: - - DriverObject - Pointer to driver object created by system. - -Return Value: - - NTSTATUS - ---*/ - -{ - CLASS_INIT_DATA InitializationData; - - // - // Zero InitData - // - - RtlZeroMemory (&InitializationData, sizeof(CLASS_INIT_DATA)); - - // - // Set sizes - // - - InitializationData.InitializationDataSize = sizeof(CLASS_INIT_DATA); - InitializationData.FdoData.DeviceExtensionSize = - sizeof(FUNCTIONAL_DEVICE_EXTENSION) + sizeof(DISK_DATA); - - InitializationData.FdoData.DeviceType = FILE_DEVICE_DISK; - InitializationData.FdoData.DeviceCharacteristics = FILE_REMOVABLE_MEDIA | FILE_FLOPPY_DISKETTE; - - // - // Set entry points - // - - InitializationData.FdoData.ClassInitDevice = ScsiFlopInitDevice; - InitializationData.FdoData.ClassStartDevice = ScsiFlopStartDevice; - InitializationData.FdoData.ClassStopDevice = ScsiFlopStopDevice; - InitializationData.FdoData.ClassRemoveDevice = ScsiFlopRemoveDevice; - - InitializationData.FdoData.ClassReadWriteVerification = ScsiFlopReadWriteVerification; - InitializationData.FdoData.ClassDeviceControl = ScsiFlopDeviceControl; - - InitializationData.FdoData.ClassShutdownFlush = NULL; - InitializationData.FdoData.ClassCreateClose = NULL; - InitializationData.FdoData.ClassError = ScsiFlopProcessError; - InitializationData.ClassStartIo = NULL; - - InitializationData.ClassAddDevice = ScsiFlopAddDevice; - InitializationData.ClassUnload = ScsiFlopUnload; - // - // Call the class init routine - // - - return ClassInitialize( DriverObject, RegistryPath, &InitializationData); - - -} // end DriverEntry() - -VOID -ScsiFlopUnload( - IN PDRIVER_OBJECT DriverObject - ) -{ - PAGED_CODE(); - UNREFERENCED_PARAMETER(DriverObject); - return; -} - -// -// AddDevice operation is performed in CreateFlopDeviceObject function which -// is called by ScsiFlopAddDevice (The AddDevice routine for sfloppy.sys). -// DO_DEVICE_INITIALIZING flag is cleard upon successfully processing AddDevice -// operation in CreateFlopDeviceObject. But PREFAST is currently unable to -// detect that DO_DEVICE_INITIALIZING is indeed cleard in CreateFlopDeviceObject -// and it raises Warning 28152 (The return from an AddDevice-like function -// unexpectedly did not clear DO_DEVICE_INITIALIZING). Suppress that warning -// using #pragma. -// -#pragma warning(push) -#pragma warning(disable:28152) - -NTSTATUS -ScsiFlopAddDevice ( - IN PDRIVER_OBJECT DriverObject, - IN PDEVICE_OBJECT Pdo - ) -/*++ - -Routine Description: - - This routine creates and initializes a new FDO for the corresponding - PDO. It may perform property queries on the FDO but cannot do any - media access operations. - -Arguments: - - DriverObject - Scsiscan class driver object. - - Pdo - the physical device object we are being added to - -Return Value: - - status - ---*/ -{ - NTSTATUS status; - ULONG floppyCount = IoGetConfigurationInformation()->FloppyCount; - - PAGED_CODE(); - - // - // Get the number of disks already initialized. - // - - status = CreateFlopDeviceObject(DriverObject, Pdo, floppyCount); - - if (NT_SUCCESS(status)) { - - // - // Increment system floppy device count. - // - - IoGetConfigurationInformation()->FloppyCount++; - } - - return status; -} - -NTSTATUS -CreateFlopDeviceObject( - IN PDRIVER_OBJECT DriverObject, - IN PDEVICE_OBJECT Pdo, - IN ULONG DeviceCount - ) - -/*++ - -Routine Description: - - This routine creates an object for the device and then calls the - SCSI port driver for media capacity and sector size. - -Arguments: - - DriverObject - Pointer to driver object created by system. - PortDeviceObject - to connect to SCSI port driver. - DeviceCount - Number of previously installed Floppys. - AdapterDescriptor - Pointer to structure returned by SCSI port - driver describing adapter capabilites (and limitations). - DeviceDescriptor - Pointer to configuration information for this device. - -Return Value: - ---*/ -{ - NTSTATUS status; - PDEVICE_OBJECT deviceObject = NULL; - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = NULL; - PDISK_DATA diskData; - - PAGED_CODE(); - - DebugPrint((3,"CreateFlopDeviceObject: Enter routine\n")); - - // - // Try to claim the device. - // - - status = ClassClaimDevice(Pdo,FALSE); - - if (!NT_SUCCESS(status)) { - return(status); - } - - DeviceCount--; - - do { - UCHAR name[256]; - - // - // Create device object for this device. - // - - DeviceCount++; - - status = RtlStringCbPrintfA((PCCHAR) name, - sizeof(name), - "\\Device\\Floppy%u", - DeviceCount); - if (NT_SUCCESS(status)) { - - status = ClassCreateDeviceObject(DriverObject, - (PCCHAR) name, - Pdo, - TRUE, - &deviceObject); - } - } while ((status == STATUS_OBJECT_NAME_COLLISION) || - (status == STATUS_OBJECT_NAME_EXISTS)); - - if (!NT_SUCCESS(status)) { - DebugPrint((1,"CreateFlopDeviceObjects: Can not create device\n")); - goto CreateFlopDeviceObjectExit; - } - - // - // Indicate that IRPs should include MDLs. - // - - deviceObject->Flags |= DO_DIRECT_IO; - - fdoExtension = deviceObject->DeviceExtension; - - // - // Back pointer to device object. - // - - fdoExtension->CommonExtension.DeviceObject = deviceObject; - - // - // This is the physical device. - // - - fdoExtension->CommonExtension.PartitionZeroExtension = fdoExtension; - - // - // Reset the drive type. - // - - diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; - diskData->DriveType = DRIVE_TYPE_NONE; - diskData->IsDMF = FALSE; - // diskData->EnableDMF = TRUE; - - // - // Initialize lock count to zero. The lock count is used to - // disable the ejection mechanism when media is mounted. - // - - fdoExtension->LockCount = 0; - - // - // Save system floppy number - // - - fdoExtension->DeviceNumber = DeviceCount; - - // - // Set the alignment requirements for the device based on the - // host adapter requirements - // - - if (Pdo->AlignmentRequirement > deviceObject->AlignmentRequirement) { - deviceObject->AlignmentRequirement = Pdo->AlignmentRequirement; - } - - // - // Clear the SrbFlags and disable synchronous transfers - // - - fdoExtension->SrbFlags = SRB_FLAGS_DISABLE_SYNCH_TRANSFER; - - // - // Finally, attach to the PDO - // - - fdoExtension->LowerPdo = Pdo; - - fdoExtension->CommonExtension.LowerDeviceObject = - IoAttachDeviceToDeviceStack(deviceObject, Pdo); - - if(fdoExtension->CommonExtension.LowerDeviceObject == NULL) { - - status = STATUS_UNSUCCESSFUL; - goto CreateFlopDeviceObjectExit; - } - - deviceObject->StackSize++; - - // - // The device is initialized properly - mark it as such. - // - - deviceObject->Flags &= ~DO_DEVICE_INITIALIZING; - - return STATUS_SUCCESS; - -CreateFlopDeviceObjectExit: - - if (deviceObject != NULL) { - IoDeleteDevice(deviceObject); - } - - return status; - -} // end CreateFlopDeviceObject() -#pragma warning(pop) - -NTSTATUS -ScsiFlopInitDevice( - IN PDEVICE_OBJECT Fdo - ) -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension; - PCOMMON_DEVICE_EXTENSION commonExtension = Fdo->DeviceExtension; - PDISK_DATA diskData = commonExtension->DriverData; - - PVOID senseData = NULL; - ULONG timeOut; - - NTSTATUS status = STATUS_SUCCESS; - - // - // Allocate request sense buffer. - // - - senseData = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED, - SENSE_BUFFER_SIZE, - SFLOPPY_TAG); - - if (senseData == NULL) { - - // - // The buffer cannot be allocated. - // - - status = STATUS_INSUFFICIENT_RESOURCES; - return status; - } - - // - // Set the sense data pointer in the device extension. - // - - fdoExtension->SenseData = senseData; - - // - // Build the lookaside list for srb's for this device. - // - - ClassInitializeSrbLookasideList((PCOMMON_DEVICE_EXTENSION)fdoExtension, - SFLOPPY_SRB_LIST_SIZE); - - // - // Register for media change notification - // - ClassInitializeMediaChangeDetection(fdoExtension, - (PUCHAR) "SFloppy"); - - // - // Set timeout value in seconds. - // - - timeOut = ClassQueryTimeOutRegistryValue(Fdo); - if (timeOut) { - fdoExtension->TimeOutValue = timeOut; - } else { - fdoExtension->TimeOutValue = SCSI_FLOPPY_TIMEOUT; - } - - // - // Floppies are not partitionable so starting offset is 0. - // - - fdoExtension->CommonExtension.StartingOffset.QuadPart = (LONGLONG)0; - -#if 0 - if (!IsFloppyDevice(Fdo) || - !(Fdo->Characteristics & FILE_REMOVABLE_MEDIA) || - (fdoExtension->DeviceDescriptor->DeviceType != DIRECT_ACCESS_DEVICE)) { - - ExFreePool(senseData); - status = STATUS_NO_SUCH_DEVICE; - return status; - } -#endif - - RtlZeroMemory(&(fdoExtension->DiskGeometry), - sizeof(DISK_GEOMETRY)); - - // - // Determine the media type if possible. Set the current media type to - // Unknown so that determine media type will check the media. - // - - fdoExtension->DiskGeometry.MediaType = Unknown; - - // - // Register interfaces for this device. - // - - { - UNICODE_STRING interfaceName; - - RtlInitUnicodeString(&interfaceName, NULL); - - status = IoRegisterDeviceInterface(fdoExtension->LowerPdo, - (LPGUID) &GUID_DEVINTERFACE_FLOPPY, - NULL, - &interfaceName); - - if(NT_SUCCESS(status)) { - diskData->FloppyInterfaceString = interfaceName; - } else { - RtlInitUnicodeString(&(diskData->FloppyInterfaceString), NULL); - DebugPrint((1, "ScsiFlopStartDevice: Unable to register device " - "interface for fdo %p [%08lx]\n", - Fdo, status)); - } - } - - return (STATUS_SUCCESS); -} - -#pragma warning(suppress:6262) // This function uses 1096 bytes of stack which exceed default value of 1024 bytes used by Code Analysis for flagging as warning -NTSTATUS ScsiFlopStartDevice( - IN PDEVICE_OBJECT Fdo - ) -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension; - PCOMMON_DEVICE_EXTENSION commonExtension = Fdo->DeviceExtension; - - PIRP irp; - IO_STATUS_BLOCK ioStatus; - - SCSI_ADDRESS scsiAddress; - - WCHAR ntNameBuffer[256]; - UNICODE_STRING ntUnicodeString; - - WCHAR arcNameBuffer[256]; - UNICODE_STRING arcUnicodeString; - - KEVENT event; - - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - KeInitializeEvent(&event,SynchronizationEvent,FALSE); - - DetermineMediaType(Fdo); // ignore unsuccessful here - - // - // Create device object for this device. - // - - RtlStringCbPrintfW(ntNameBuffer, - sizeof(ntNameBuffer), - L"\\Device\\Floppy%u", - fdoExtension->DeviceNumber); - - // - // Create local copy of unicode string - // - RtlInitUnicodeString(&ntUnicodeString,ntNameBuffer); - - // - // Create a symbolic link from the disk name to the corresponding - // ARC name, to be used if we're booting off the disk. This will - // fail if it's not system initialization time; that's fine. The - // ARC name looks something like \ArcName\scsi(0)Flop(0)fdisk(0). - // In order to get the address, we need to send a IOCTL_SCSI_GET_ADDRESS... - // - - irp = IoBuildDeviceIoControlRequest(IOCTL_SCSI_GET_ADDRESS, - Fdo, - NULL, - 0, - &scsiAddress, - sizeof(scsiAddress), - FALSE, - &event, - &ioStatus); - - if (irp == NULL) { - return STATUS_INSUFFICIENT_RESOURCES; - } - - status = IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, irp); - - if (status == STATUS_PENDING) { - KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); - status = ioStatus.Status; - } - - // - // IOCTL_SCSI_GET_ADDRESS might not be supported by the port driver and - // hence may fail. But it is not a fatal error. Do not fail PnP start - // if this IOCTL fails. - // - if (NT_SUCCESS(status)) { - - RtlStringCbPrintfW(arcNameBuffer, - sizeof(arcNameBuffer), - L"\\ArcName\\scsi(%u)disk(%u)fdisk(%u)", - scsiAddress.PortNumber, - scsiAddress.TargetId, - scsiAddress.Lun); - - RtlInitUnicodeString(&arcUnicodeString, arcNameBuffer); - - IoAssignArcName(&arcUnicodeString, &ntUnicodeString); - } - - status = STATUS_SUCCESS; - - // - // Create the multi() arc name -- Create the "fake" - // name of multi(0)disk(0)fdisk(#) to handle the case where the - // SCSI floppy is the only floppy in the system. If this fails - // it doesn't matter because the previous scsi() based ArcName - // will work. This name is necessary for installation. - // - - RtlStringCbPrintfW(arcNameBuffer, - sizeof(arcNameBuffer), - L"\\ArcName\\multi(%u)disk(%u)fdisk(%u)", - 0, - 0, - fdoExtension->DeviceNumber); - - RtlInitUnicodeString(&arcUnicodeString, arcNameBuffer); - - IoAssignArcName(&arcUnicodeString, &ntUnicodeString); - - // - // Set our interface state. - // - - { - PDISK_DATA diskData = commonExtension->DriverData; - - if(diskData->FloppyInterfaceString.Buffer != NULL) { - - status = IoSetDeviceInterfaceState( - &(diskData->FloppyInterfaceString), - TRUE); - - if(!NT_SUCCESS(status)) { - DebugPrint((1, "ScsiFlopStartDevice: Unable to set device " - "interface state to TRUE for fdo %p " - "[%08lx]\n", - Fdo, status)); - } - } - } - - return STATUS_SUCCESS; -} - - -NTSTATUS -ScsiFlopReadWriteVerification( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ) - -/*++ - -Routine Description: - -Arguments: - -Return Value: - - NT Status - ---*/ - -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp); - NTSTATUS status = STATUS_SUCCESS; - - // - // Make sure that the number of bytes to transfer is a multiple of the sector size - // - if ((irpSp->Parameters.Read.Length & (fdoExtension->DiskGeometry.BytesPerSector - 1)) != 0) - { - status = STATUS_INVALID_PARAMETER; - } - - Irp->IoStatus.Status = status; - - return status; -} - - -NTSTATUS -ScsiFlopDeviceControl( - PDEVICE_OBJECT DeviceObject, - PIRP Irp - ) - -/*++ - -Routine Description: - -Arguments: - -Return Value: - - Status is returned. - ---*/ - -{ - KIRQL currentIrql; - PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp); - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension; - PSCSI_REQUEST_BLOCK srb; - PCDB cdb; - NTSTATUS status; - PDISK_GEOMETRY outputBuffer; - ULONG outputBufferLength; - ULONG i; - DRIVE_MEDIA_TYPE lowestDriveMediaType; - DRIVE_MEDIA_TYPE highestDriveMediaType; - PFORMAT_PARAMETERS formatParameters; - PMODE_PARAMETER_HEADER modeData; - ULONG length; - - // - // Initialize the information field - // - Irp->IoStatus.Information = 0; - - srb = ExAllocatePool2(POOL_FLAG_NON_PAGED, - SCSI_REQUEST_BLOCK_SIZE, - SFLOPPY_TAG); - - if (srb == NULL) { - - Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; - if (IoIsErrorUserInduced(Irp->IoStatus.Status)) { - - IoSetHardErrorOrVerifyDevice(Irp, DeviceObject); - } - - KeRaiseIrql(DISPATCH_LEVEL, ¤tIrql); - ClassReleaseRemoveLock(DeviceObject, Irp); - ClassCompleteRequest(DeviceObject, Irp, 0); - KeLowerIrql(currentIrql); - - return(STATUS_INSUFFICIENT_RESOURCES); - } - - // - // Write zeros to Srb. - // - - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - cdb = (PCDB)srb->Cdb; - - switch (irpStack->Parameters.DeviceIoControl.IoControlCode) { - - - case IOCTL_DISK_VERIFY: { - - PVERIFY_INFORMATION verifyInfo = Irp->AssociatedIrp.SystemBuffer; - LARGE_INTEGER byteOffset; - ULONG sectorOffset; - USHORT sectorCount; - - // - // Validate buffer length. - // - - if (irpStack->Parameters.DeviceIoControl.InputBufferLength < - sizeof(VERIFY_INFORMATION)) { - - status = STATUS_INFO_LENGTH_MISMATCH; - break; - } - - // - // Perform a bounds check on the sector range - // - if ((verifyInfo->StartingOffset.QuadPart > fdoExtension->CommonExtension.PartitionLength.QuadPart) || - (verifyInfo->StartingOffset.QuadPart < 0)) - { - status = STATUS_NONEXISTENT_SECTOR; - break; - } - else - { - ULONGLONG bytesRemaining = fdoExtension->CommonExtension.PartitionLength.QuadPart - verifyInfo->StartingOffset.QuadPart; - - if ((ULONGLONG)verifyInfo->Length > bytesRemaining) - { - status = STATUS_NONEXISTENT_SECTOR; - break; - } - } - - // - // Verify sectors - // - - srb->CdbLength = 10; - - cdb->CDB10.OperationCode = SCSIOP_VERIFY; - - // - // Add disk offset to starting sector. - // - - byteOffset.QuadPart = fdoExtension->CommonExtension.StartingOffset.QuadPart + - verifyInfo->StartingOffset.QuadPart; - - // - // Convert byte offset to sector offset. - // - - sectorOffset = (ULONG)(byteOffset.QuadPart >> fdoExtension->SectorShift); - - // - // Convert ULONG byte count to USHORT sector count. - // - - sectorCount = (USHORT)(verifyInfo->Length >> fdoExtension->SectorShift); - - // - // Move little endian values into CDB in big endian format. - // - - cdb->CDB10.LogicalBlockByte0 = ((PFOUR_BYTE)§orOffset)->Byte3; - cdb->CDB10.LogicalBlockByte1 = ((PFOUR_BYTE)§orOffset)->Byte2; - cdb->CDB10.LogicalBlockByte2 = ((PFOUR_BYTE)§orOffset)->Byte1; - cdb->CDB10.LogicalBlockByte3 = ((PFOUR_BYTE)§orOffset)->Byte0; - - cdb->CDB10.TransferBlocksMsb = ((PFOUR_BYTE)§orCount)->Byte1; - cdb->CDB10.TransferBlocksLsb = ((PFOUR_BYTE)§orCount)->Byte0; - - // - // The verify command is used by the NT FORMAT utility and - // requests are sent down for 5% of the volume size. The - // request timeout value is calculated based on the number of - // sectors verified. - // - - srb->TimeOutValue = ((sectorCount + 0x7F) >> 7) * - fdoExtension->TimeOutValue; - - status = ClassSendSrbAsynchronous(DeviceObject, - srb, - Irp, - NULL, - 0, - FALSE); - return(status); - - } - - case IOCTL_DISK_GET_PARTITION_INFO: { - - if (fdoExtension->AdapterDescriptor->BusType == BusTypeUsb) { - - USBFlopGetMediaTypes(DeviceObject, NULL); - - // Don't need to propagate any error if one occurs - // - status = STATUS_SUCCESS; - - } else { - - status = DetermineMediaType(DeviceObject); - } - - if (!NT_SUCCESS(status)) { - // so will propogate error - NOTHING; - } else if (fdoExtension->DiskGeometry.MediaType == F3_120M_512) { - //so that the format code will not try to partition it. - status = STATUS_INVALID_DEVICE_REQUEST; - } else { - // - // Free the Srb, since it is not needed. - // - - ExFreePool(srb); - - // - // Pass the request to the common device control routine. - // - - return(ClassDeviceControl(DeviceObject, Irp)); - } - break; - } - - case IOCTL_DISK_GET_DRIVE_GEOMETRY: { - - DebugPrint((3,"ScsiDeviceIoControl: Get drive geometry\n")); - - if (fdoExtension->AdapterDescriptor->BusType == BusTypeUsb) - { - status = USBFlopGetMediaTypes(DeviceObject, - Irp); - break; - } - - // - // If there's not enough room to write the - // data, then fail the request. - // - - if ( irpStack->Parameters.DeviceIoControl.OutputBufferLength < - sizeof( DISK_GEOMETRY ) ) { - - status = STATUS_INVALID_PARAMETER; - break; - } - - status = DetermineMediaType(DeviceObject); - - if (!NT_SUCCESS(status)) { - - Irp->IoStatus.Information = 0; - Irp->IoStatus.Status = status; - - } else { - - // - // Copy drive geometry information from device extension. - // - - RtlMoveMemory(Irp->AssociatedIrp.SystemBuffer, - &(fdoExtension->DiskGeometry), - sizeof(DISK_GEOMETRY)); - - Irp->IoStatus.Information = sizeof(DISK_GEOMETRY); - status = STATUS_SUCCESS; - - } - - break; - } - - case IOCTL_DISK_GET_MEDIA_TYPES: { - - if (fdoExtension->AdapterDescriptor->BusType == BusTypeUsb) - { - status = USBFlopGetMediaTypes(DeviceObject, - Irp); - break; - } - - i = DetermineDriveType(DeviceObject); - - if (i == DRIVE_TYPE_NONE) { - status = STATUS_UNRECOGNIZED_MEDIA; - break; - } - - lowestDriveMediaType = DriveMediaLimits[i].LowestDriveMediaType; - highestDriveMediaType = DriveMediaLimits[i].HighestDriveMediaType; - - outputBufferLength = - irpStack->Parameters.DeviceIoControl.OutputBufferLength; - - // - // Make sure that the input buffer has enough room to return - // at least one descriptions of a supported media type. - // - - if ( outputBufferLength < ( sizeof( DISK_GEOMETRY ) ) ) { - - status = STATUS_BUFFER_TOO_SMALL; - break; - } - - // - // Assume success, although we might modify it to a buffer - // overflow warning below (if the buffer isn't big enough - // to hold ALL of the media descriptions). - // - - status = STATUS_SUCCESS; - - if (outputBufferLength < ( sizeof( DISK_GEOMETRY ) * - ( highestDriveMediaType - lowestDriveMediaType + 1 ) ) ) { - - // - // The buffer is too small for all of the descriptions; - // calculate what CAN fit in the buffer. - // - - status = STATUS_BUFFER_OVERFLOW; - - highestDriveMediaType = (DRIVE_MEDIA_TYPE)( ( lowestDriveMediaType - 1 ) + - ( outputBufferLength / - sizeof( DISK_GEOMETRY ) ) ); - } - - outputBuffer = (PDISK_GEOMETRY) Irp->AssociatedIrp.SystemBuffer; - - for (i = (UCHAR)lowestDriveMediaType;i <= (UCHAR)highestDriveMediaType;i++ ) { - - outputBuffer->MediaType = DriveMediaConstants[i].MediaType; - outputBuffer->Cylinders.LowPart = - DriveMediaConstants[i].MaximumTrack + 1; - outputBuffer->Cylinders.HighPart = 0; - outputBuffer->TracksPerCylinder = - DriveMediaConstants[i].NumberOfHeads; - outputBuffer->SectorsPerTrack = - DriveMediaConstants[i].SectorsPerTrack; - outputBuffer->BytesPerSector = - DriveMediaConstants[i].BytesPerSector; - outputBuffer++; - - Irp->IoStatus.Information += sizeof( DISK_GEOMETRY ); - } - - break; - } - - case IOCTL_DISK_FORMAT_TRACKS: { - - if (fdoExtension->AdapterDescriptor->BusType == BusTypeUsb) - { - status = USBFlopFormatTracks(DeviceObject, - Irp); - break; - } - - // - // Make sure that we got all the necessary format parameters. - // - - if ( irpStack->Parameters.DeviceIoControl.InputBufferLength AssociatedIrp.SystemBuffer; - - // - // Make sure the parameters we got are reasonable. - // - - if ( !FlCheckFormatParameters(DeviceObject, formatParameters)) { - - status = STATUS_INVALID_PARAMETER; - break; - } - - // - // If this request is for a 20.8 MB floppy then call a special - // floppy format routine. - // - - if (formatParameters->MediaType == F3_20Pt8_512) { - status = FlopticalFormatMedia(DeviceObject, - formatParameters - ); - - break; - } - - // - // All the work is done in the pass. If this is not the first pass, - // then complete the request and return; - // - - if (formatParameters->StartCylinderNumber != 0 || formatParameters->StartHeadNumber != 0) { - - status = STATUS_SUCCESS; - break; - } - - status = FormatMedia( DeviceObject, formatParameters->MediaType); - break; - } - - case IOCTL_DISK_IS_WRITABLE: { - - if ((fdoExtension->DiskGeometry.MediaType) == F3_32M_512) { - - // - // 32MB media is READ ONLY. Just return - // STATUS_MEDIA_WRITE_PROTECTED - // - - status = STATUS_MEDIA_WRITE_PROTECTED; - - break; - } - - // - // Determine if the device is writable. - // - - modeData = ExAllocatePool(NonPagedPoolNxCacheAligned, MODE_DATA_SIZE); - - if (modeData == NULL) { - status = STATUS_INSUFFICIENT_RESOURCES; - break; - } - - RtlZeroMemory(modeData, MODE_DATA_SIZE); - - length = ClassModeSense(DeviceObject, - (PCHAR) modeData, - MODE_DATA_SIZE, - MODE_SENSE_RETURN_ALL); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - - // - // Retry the request in case of a check condition. - // - - length = ClassModeSense(DeviceObject, - (PCHAR) modeData, - MODE_DATA_SIZE, - MODE_SENSE_RETURN_ALL); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - status = STATUS_IO_DEVICE_ERROR; - ExFreePool(modeData); - break; - } - } - - if (modeData->DeviceSpecificParameter & MODE_DSP_WRITE_PROTECT) { - status = STATUS_MEDIA_WRITE_PROTECTED; - } else { - status = STATUS_SUCCESS; - } - - DebugPrint((2,"IOCTL_DISK_IS_WRITABLE returns %08X\n", status)); - - ExFreePool(modeData); - break; - } - - default: { - - DebugPrint((3,"ScsiIoDeviceControl: Unsupported device IOCTL\n")); - - // - // Free the Srb, since it is not needed. - // - - ExFreePool(srb); - - // - // Pass the request to the common device control routine. - // - - return(ClassDeviceControl(DeviceObject, Irp)); - - break; - } - - } // end switch( ... - - // - // Check if SL_OVERRIDE_VERIFY_VOLUME flag is set in the IRP. - // If so, do not return STATUS_VERIFY_REQUIRED - // - if ((status == STATUS_VERIFY_REQUIRED) && - (TEST_FLAG(irpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME))) { - - status = STATUS_IO_DEVICE_ERROR; - - } - - Irp->IoStatus.Status = status; - - if (!NT_SUCCESS(status) && IoIsErrorUserInduced(status)) { - - IoSetHardErrorOrVerifyDevice(Irp, DeviceObject); - } - - KeRaiseIrql(DISPATCH_LEVEL, ¤tIrql); - ClassReleaseRemoveLock(DeviceObject, Irp); - ClassCompleteRequest(DeviceObject, Irp, 0); - KeLowerIrql(currentIrql); - - ExFreePool(srb); - - return status; - -} // end ScsiFlopDeviceControl() - -#if 0 - -BOOLEAN -IsFloppyDevice( - PDEVICE_OBJECT DeviceObject - ) -/*++ - -Routine Description: - - The routine performs the necessary funcitons to deterime if the device is - really a floppy rather than a harddisk. This is done by a mode sense - command. First a check is made to see if the medimum type is set. Second - a check is made for the flexible parameters mode page. - -Arguments: - - DeviceObject - Supplies the device object to be tested. - -Return Value: - - Return TRUE if the indicated device is a floppy. - ---*/ -{ - - PVOID modeData; - PUCHAR pageData; - ULONG length; - - modeData = ExAllocatePool(NonPagedPoolNxCacheAligned, MODE_DATA_SIZE); - - if (modeData == NULL) { - return(FALSE); - } - - RtlZeroMemory(modeData, MODE_DATA_SIZE); - - length = ClassModeSense(DeviceObject, modeData, MODE_DATA_SIZE, MODE_SENSE_RETURN_ALL); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - - // - // Retry the request in case of a check condition. - // - - length = ClassModeSense(DeviceObject, - modeData, - MODE_DATA_SIZE, - MODE_SENSE_RETURN_ALL); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - - ExFreePool(modeData); - return(FALSE); - - } - } - -#if 0 - // - // Some drives incorrectly report this. In particular the SONY RMO-S350 - // when in disk mode. - // - - if (((PMODE_PARAMETER_HEADER) modeData)->MediumType >= MODE_FD_SINGLE_SIDE - && ((PMODE_PARAMETER_HEADER) modeData)->MediumType <= MODE_FD_MAXIMUM_TYPE) { - - DebugPrint((1, "ScsiFlop: MediumType value %2x, This is a floppy.\n", ((PMODE_PARAMETER_HEADER) modeData)->MediumType)); - ExFreePool(modeData); - return(TRUE); - } - -#endif - - // - // If the length is greater than length indiated by the mode data reset - // the data to the mode data. - // - if (length > (ULONG)((PMODE_PARAMETER_HEADER) modeData)->ModeDataLength + 1) { - length = (ULONG)((PMODE_PARAMETER_HEADER) modeData)->ModeDataLength + 1; - - } - - // - // Look for the flexible disk mode page. - // - - pageData = ClassFindModePage( modeData, length, MODE_PAGE_FLEXIBILE, TRUE); - - if (pageData != NULL) { - - DebugPrint((1, "ScsiFlop: Flexible disk page found, This is a floppy.\n")); - - // - // As a special case for the floptical driver do a magic mode sense to - // enable the drive. - // - - ClassModeSense(DeviceObject, modeData, 0x2a, 0x2e); - - ExFreePool(modeData); - return(TRUE); - - } - - ExFreePool(modeData); - return(FALSE); - -} -#endif - - -NTSTATUS -DetermineMediaType( - PDEVICE_OBJECT DeviceObject - ) -/*++ - -Routine Description: - - This routine determines the floppy media type based on the size of the - device. The geometry information is set for the device object. - -Arguments: - - DeviceObject - Supplies the device object to be tested. - -Return Value: - - None - ---*/ -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension; - PDISK_GEOMETRY geometry; - LONG index; - NTSTATUS status; - - PAGED_CODE(); - - geometry = &(fdoExtension->DiskGeometry); - - // - // Issue ReadCapacity to update device extension - // with information for current media. - // - - status = ClassReadDriveCapacity(DeviceObject); - - if (!NT_SUCCESS(status)) { - - // - // Set the media type to unknow and zero the geometry information. - // - - geometry->MediaType = Unknown; - - return status; - - } - - // - // Look at the capcity of disk to determine its type. - // - - for (index = NUMBER_OF_DRIVE_MEDIA_COMBINATIONS - 1; index >= 0; index--) { - - // - // Walk the table backward untill the drive capacity holds all of the - // data and the bytes per setor are equal - // - - if ((ULONG) (DriveMediaConstants[index].NumberOfHeads * - (DriveMediaConstants[index].MaximumTrack + 1) * - DriveMediaConstants[index].SectorsPerTrack * - DriveMediaConstants[index].BytesPerSector) <= - fdoExtension->CommonExtension.PartitionLength.LowPart && - DriveMediaConstants[index].BytesPerSector == - geometry->BytesPerSector) { - - geometry->MediaType = DriveMediaConstants[index].MediaType; - geometry->TracksPerCylinder = DriveMediaConstants[index].NumberOfHeads; - geometry->SectorsPerTrack = DriveMediaConstants[index].SectorsPerTrack; - geometry->Cylinders.LowPart = DriveMediaConstants[index].MaximumTrack+1; - break; - } - } - - if (index == -1) { - - // - // Set the media type to unknow and zero the geometry information. - // - - geometry->MediaType = Unknown; - - - } else { - // - // DMF check breaks the insight SCSI floppy, so its disabled for that case - // - PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; - - // if (diskData->EnableDMF == TRUE) { - - // - //check to see if DMF - // - - PSCSI_REQUEST_BLOCK srb; - PVOID readData; - - // - // Allocate a Srb for the read command. - // - - readData = ExAllocatePool(NonPagedPoolNx, geometry->BytesPerSector); - if (readData == NULL) { - return STATUS_NO_MEMORY; - } - - srb = ExAllocatePool(NonPagedPoolNx, SCSI_REQUEST_BLOCK_SIZE); - - if (srb == NULL) { - - ExFreePool(readData); - return STATUS_NO_MEMORY; - } - - RtlZeroMemory(readData, geometry->BytesPerSector); - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - srb->CdbLength = 10; - srb->Cdb[0] = SCSIOP_READ; - srb->Cdb[5] = 0; - srb->Cdb[8] = (UCHAR) 1; - - // - // Set timeout value. - // - - srb->TimeOutValue = fdoExtension->TimeOutValue; - - // - // Send the mode select data. - // - - status = ClassSendSrbSynchronous(DeviceObject, - srb, - readData, - geometry->BytesPerSector, - FALSE - ); - - if (NT_SUCCESS(status)) { - char *pchar = (char *)readData; - - pchar += 3; //skip 3 bytes jump code - - // If the MSDMF3. signature is there then mark it as DMF diskette - if (RtlCompareMemory(pchar, "MSDMF3.", 7) == 7) { - diskData->IsDMF = TRUE; - } - - } - ExFreePool(readData); - ExFreePool(srb); - // }// else - } - return status; -} - -ULONG -DetermineDriveType( - PDEVICE_OBJECT DeviceObject - ) -/*++ - -Routine Description: - - The routine determines the device type so that the supported medias can be - determined. It does a mode sense for the default parameters. This code - assumes that the returned values are for the maximum device size. - -Arguments: - - DeviceObject - Supplies the device object to be tested. - -Return Value: - - None - ---*/ -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension; - PVOID modeData; - PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; - PMODE_FLEXIBLE_DISK_PAGE pageData; - ULONG length; - LONG index; - UCHAR numberOfHeads; - UCHAR sectorsPerTrack; - USHORT maximumTrack; - BOOLEAN applyFix = FALSE; - - PAGED_CODE(); - - if (diskData->DriveType != DRIVE_TYPE_NONE) { - return(diskData->DriveType); - } - - modeData = ExAllocatePool(NonPagedPoolNxCacheAligned, MODE_DATA_SIZE); - - if (modeData == NULL) { - return(DRIVE_TYPE_NONE); - } - - RtlZeroMemory(modeData, MODE_DATA_SIZE); - - length = ClassModeSense(DeviceObject, - modeData, - MODE_DATA_SIZE, - MODE_PAGE_FLEXIBILE); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - - // - // Retry the request one more time - // in case of a check condition. - // - length = ClassModeSense(DeviceObject, - modeData, - MODE_DATA_SIZE, - MODE_PAGE_FLEXIBILE); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - - ExFreePool(modeData); - return(DRIVE_TYPE_NONE); - } - } - - // - // Look for the flexible disk mode page. - // - - pageData = ClassFindModePage( modeData, - length, - MODE_PAGE_FLEXIBILE, - TRUE); - - // - // Make sure the page is returned and is large enough. - // - - if ((pageData != NULL) && - (pageData->PageLength + 2 >= - (UCHAR)offsetof(MODE_FLEXIBLE_DISK_PAGE, StartWritePrecom))) { - - // - // Pull out the heads, cylinders, and sectors. - // - - numberOfHeads = pageData->NumberOfHeads; - maximumTrack = pageData->NumberOfCylinders[1]; - maximumTrack |= pageData->NumberOfCylinders[0] << 8; - sectorsPerTrack = pageData->SectorsPerTrack; - - - // - // Convert from number of cylinders to maximum track. - // - - maximumTrack--; - - // - // Search for the maximum supported media. Based on the number of heads, - // sectors per track and number of cylinders - // - for (index = 0; index < NUMBER_OF_DRIVE_MEDIA_COMBINATIONS; index++) { - - // - // Walk the table forward until the drive capacity holds all of the - // data and the bytes per setor are equal - // - - if (DriveMediaConstants[index].NumberOfHeads == numberOfHeads && - DriveMediaConstants[index].MaximumTrack == maximumTrack && - DriveMediaConstants[index].SectorsPerTrack ==sectorsPerTrack) { - - ExFreePool(modeData); - - // - // index is now a drive media combination. Compare this to - // the maximum drive media type in the drive media table. - // - - for (length = 0; length < NUMBER_OF_DRIVE_TYPES; length++) { - - if (DriveMediaLimits[length].HighestDriveMediaType == index) { - return(length); - } - } - return(DRIVE_TYPE_NONE); - } - } - - // If the maximum track is greater than 8 bits then divide the - // number of tracks by 3 and multiply the number of heads by 3. - // This is a special case for the 20.8 MB floppy. - // - - if (!applyFix && maximumTrack >= 0x0100) { - maximumTrack++; - maximumTrack /= 3; - maximumTrack--; - numberOfHeads *= 3; - } else { - ExFreePool(modeData); - return(DRIVE_TYPE_NONE); - } - - } - - ExFreePool(modeData); - return(DRIVE_TYPE_NONE); -} - - -BOOLEAN -FlCheckFormatParameters( - IN PDEVICE_OBJECT DeviceObject, - IN PFORMAT_PARAMETERS FormatParameters - ) - -/*++ - -Routine Description: - - This routine checks the supplied format parameters to make sure that - they'll work on the drive to be formatted. - -Arguments: - - DeviceObject - Pointer to the device object to be formated. - - FormatParameters - a pointer to the caller's parameters for the FORMAT. - -Return Value: - - TRUE if parameters are OK. - FALSE if the parameters are bad. - ---*/ - -{ - PDRIVE_MEDIA_CONSTANTS driveMediaConstants; - DRIVE_MEDIA_TYPE driveMediaType; - ULONG index; - - PAGED_CODE(); - - // - // Get the device type. - // - - index = DetermineDriveType(DeviceObject); - - if (index == DRIVE_TYPE_NONE) { - - // - // If the determine device type failed then just use the media type - // and try the parameters. - // - - driveMediaType = Drive360Media160; - - while (( DriveMediaConstants[driveMediaType].MediaType != - FormatParameters->MediaType ) && - ( driveMediaType < Drive288Media288) ) { - - driveMediaType++; - } - - } else { - - // - // Figure out which entry in the DriveMediaConstants table to use. - // - - driveMediaType = - DriveMediaLimits[index].HighestDriveMediaType; - - while ( ( DriveMediaConstants[driveMediaType].MediaType != - FormatParameters->MediaType ) && - ( driveMediaType > DriveMediaLimits[index]. - LowestDriveMediaType ) ) { - - driveMediaType--; - } - - } - - - // driveMediaType is bounded below by DriveMediaLimits[].LowestDriveMediaType -#pragma warning(push) -#pragma warning(disable:33010) // 33010: Enum used as array index may be negative - if ( DriveMediaConstants[driveMediaType].MediaType != - FormatParameters->MediaType ) { - return FALSE; - - } else { - - driveMediaConstants = &DriveMediaConstants[driveMediaType]; - - if ( ( FormatParameters->StartHeadNumber > - (ULONG)( driveMediaConstants->NumberOfHeads - 1 ) ) || - ( FormatParameters->EndHeadNumber > - (ULONG)( driveMediaConstants->NumberOfHeads - 1 ) ) || - ( FormatParameters->StartCylinderNumber > - driveMediaConstants->MaximumTrack ) || - ( FormatParameters->EndCylinderNumber > - driveMediaConstants->MaximumTrack ) || - ( FormatParameters->EndCylinderNumber < - FormatParameters->StartCylinderNumber ) ) { - - return FALSE; - - } else { - - return TRUE; - } - } -#pragma warning(pop) -} - -NTSTATUS -FormatMedia( - PDEVICE_OBJECT DeviceObject, - MEDIA_TYPE MediaType - ) -/*++ - -Routine Description: - - This routine formats the floppy disk. The entire floppy is formated in - one shot. - -Arguments: - - DeviceObject - Supplies the device object to be tested. - - Irp - Supplies a pointer to the requesting Irp. - - MediaType - Supplies the media type format the device for. - -Return Value: - - Returns a status for the operation. - ---*/ -{ - PVOID modeData; - PSCSI_REQUEST_BLOCK srb; - PMODE_FLEXIBLE_DISK_PAGE pageData; - DRIVE_MEDIA_TYPE driveMediaType; - PDRIVE_MEDIA_CONSTANTS driveMediaConstants; - ULONG length; - NTSTATUS status; - - PAGED_CODE(); - - modeData = ExAllocatePool(NonPagedPoolNxCacheAligned, MODE_DATA_SIZE); - - if (modeData == NULL) { - return(STATUS_INSUFFICIENT_RESOURCES); - } - - RtlZeroMemory(modeData, MODE_DATA_SIZE); - - length = ClassModeSense(DeviceObject, - modeData, - MODE_DATA_SIZE, - MODE_PAGE_FLEXIBILE); - - if (length < sizeof(MODE_PARAMETER_HEADER)) { - ExFreePool(modeData); - return(STATUS_INVALID_DEVICE_REQUEST); - } - - // - // Look for the flexible disk mode page. - // - - pageData = ClassFindModePage( modeData, length, MODE_PAGE_FLEXIBILE, TRUE); - - // - // Make sure the page is returned and is large enough. - // - - if ((pageData == NULL) || - (pageData->PageLength + 2 < - (UCHAR)offsetof(MODE_FLEXIBLE_DISK_PAGE, StartWritePrecom))) { - - ExFreePool(modeData); - return(STATUS_INVALID_DEVICE_REQUEST); - - } - - // - // Look for a drive media type which matches the requested media type. - // - // - //start from Drive120MMedia120M instead of Drive2080Media2080 - // - for (driveMediaType = Drive120MMedia120M; - DriveMediaConstants[driveMediaType].MediaType != MediaType; - driveMediaType--) { - if (driveMediaType == Drive360Media160) { - - ExFreePool(modeData); - return(STATUS_INVALID_PARAMETER); - - } - } - - driveMediaConstants = &DriveMediaConstants[driveMediaType]; - - if ((pageData->NumberOfHeads != driveMediaConstants->NumberOfHeads) || - (pageData->SectorsPerTrack != driveMediaConstants->SectorsPerTrack) || - ((pageData->NumberOfCylinders[0] != (UCHAR)((driveMediaConstants->MaximumTrack+1) >> 8)) && - (pageData->NumberOfCylinders[1] != (UCHAR)driveMediaConstants->MaximumTrack+1)) || - (pageData->BytesPerSector[0] != driveMediaConstants->BytesPerSector >> 8 )) { - - // - // Update the flexible parameters page with the new parameters. - // - - pageData->NumberOfHeads = driveMediaConstants->NumberOfHeads; - pageData->SectorsPerTrack = driveMediaConstants->SectorsPerTrack; - pageData->NumberOfCylinders[0] = (UCHAR)((driveMediaConstants->MaximumTrack+1) >> 8); - pageData->NumberOfCylinders[1] = (UCHAR)driveMediaConstants->MaximumTrack+1; - pageData->BytesPerSector[0] = driveMediaConstants->BytesPerSector >> 8; - - // - // Clear the mode parameter header. - // - - RtlZeroMemory(modeData, sizeof(MODE_PARAMETER_HEADER)); - - // - // Set the length equal to the length returned for the flexible page. - // - - length = pageData->PageLength + 2; - - // - // Copy the page after the mode parameter header. - // - - RtlMoveMemory((PCHAR) modeData + sizeof(MODE_PARAMETER_HEADER), - pageData, - length - ); - length += sizeof(MODE_PARAMETER_HEADER); - - - // - // Allocate a Srb for the format command. - // - - srb = ExAllocatePool(NonPagedPoolNx, SCSI_REQUEST_BLOCK_SIZE); - - if (srb == NULL) { - - ExFreePool(modeData); - return(STATUS_INSUFFICIENT_RESOURCES); - } - - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - srb->CdbLength = 6; - srb->Cdb[0] = SCSIOP_MODE_SELECT; - srb->Cdb[4] = (UCHAR) length; - - // - // Set the PF bit. - // - - srb->Cdb[1] |= 0x10; - - // - // Set timeout value. - // - - srb->TimeOutValue = 2; - - // - // Send the mode select data. - // - - status = ClassSendSrbSynchronous(DeviceObject, - srb, - modeData, - length, - TRUE - ); - - // - // The mode data not needed any more so free it. - // - - ExFreePool(modeData); - - if (!NT_SUCCESS(status)) { - ExFreePool(srb); - return(status); - } - - } else { - - // - // The mode data not needed any more so free it. - // - - ExFreePool(modeData); - - // - // Allocate a Srb for the format command. - // - - srb = ExAllocatePool(NonPagedPoolNx, SCSI_REQUEST_BLOCK_SIZE); - - if (srb == NULL) { - return(STATUS_INSUFFICIENT_RESOURCES); - } - - } - - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - srb->CdbLength = 6; - - srb->Cdb[0] = SCSIOP_FORMAT_UNIT; - - // - // Set timeout value. - // - - srb->TimeOutValue = 10 * 60; - - status = ClassSendSrbSynchronous(DeviceObject, - srb, - NULL, - 0, - FALSE - ); - ExFreePool(srb); - - return(status); - -} - -VOID -ScsiFlopProcessError( - PDEVICE_OBJECT DeviceObject, - PSCSI_REQUEST_BLOCK Srb, - NTSTATUS *Status, - BOOLEAN *Retry - ) -/*++ - -Routine Description: - - This routine checks the type of error. If the error indicate the floppy - controller needs to be reinitialize a command is made to do it. - -Arguments: - - DeviceObject - Supplies a pointer to the device object. - - Srb - Supplies a pointer to the failing Srb. - - Status - Status with which the IRP will be completed. - - Retry - Indication of whether the request will be retried. - -Return Value: - - None. - ---*/ - -{ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension; - PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; - PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer; - PIO_STACK_LOCATION irpStack; - PIRP irp; - PSCSI_REQUEST_BLOCK srb; - LARGE_INTEGER largeInt; - PCOMPLETION_CONTEXT context; - PCDB cdb; - ULONG_PTR alignment; - ULONG majorFunction; - - UNREFERENCED_PARAMETER(Status); - UNREFERENCED_PARAMETER(Retry); - - largeInt.QuadPart = 1; - - // - // Check the status. The initialization command only needs to be sent - // if UNIT ATTENTION or LUN NOT READY is returned. - // - - if (!(Srb->SrbStatus & SRB_STATUS_AUTOSENSE_VALID)) { - - // - // The drive does not require reinitialization. - // - - return; - } - - // - // Reset the drive type. - // - - diskData->DriveType = DRIVE_TYPE_NONE; - diskData->IsDMF = FALSE; - - fdoExtension->DiskGeometry.MediaType = Unknown; - - if (fdoExtension->AdapterDescriptor->BusType == BusTypeUsb) { - - // FLPYDISK.SYS never returns a non-zero value for the ChangeCount - // on an IOCTL_DISK_CHECK_VERIFY. Some things seem to work better - // if we do the same. In particular, FatVerifyVolume() can exit between - // the IOCTL_DISK_CHECK_VERIFY and the IOCTL_DISK_GET_DRIVE_GEOMETRY - // if a non-zero ChangeCount is returned, and this appears to cause - // issues formatting unformatted media in some situations. - // - // This is something that should probably be revisited at some point. - // - fdoExtension->MediaChangeCount = 0; - - if (((senseBuffer->SenseKey & 0xf) == SCSI_SENSE_UNIT_ATTENTION) && - (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_MEDIUM_CHANGED)) { - - struct _START_STOP *startStopCdb; - - DebugPrint((2,"Sending SCSIOP_START_STOP_UNIT\n")); - - context = ExAllocatePool(NonPagedPoolNx, - sizeof(COMPLETION_CONTEXT)); - - if (context == NULL) { - - return; - } -#if (NTDDI_VERSION >= NTDDI_WIN8) - srb = &context->Srb.Srb; -#else - srb = &context->Srb; -#endif - - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - srb->SrbFlags = SRB_FLAGS_DISABLE_AUTOSENSE; - - srb->CdbLength = 6; - - startStopCdb = (struct _START_STOP *)srb->Cdb; - - startStopCdb->OperationCode = SCSIOP_START_STOP_UNIT; - startStopCdb->Start = 1; - - // A Start Stop Unit request has no transfer buffer. - // Set the request to IRP_MJ_FLUSH_BUFFERS when calling - // IoBuildAsynchronousFsdRequest() so that it ignores - // the buffer pointer and buffer length parameters. - // - majorFunction = IRP_MJ_FLUSH_BUFFERS; - - } else if ((senseBuffer->SenseKey & 0xf) == SCSI_SENSE_MEDIUM_ERROR) { - - // Return ERROR_UNRECOGNIZED_MEDIA instead of - // STATUS_DEVICE_DATA_ERROR to make shell happy. - // - *Status = STATUS_UNRECOGNIZED_MEDIA; - return; - - } else { - - return; - } - - } else if (((senseBuffer->SenseKey & 0xf) == SCSI_SENSE_NOT_READY) && - senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_INIT_COMMAND_REQUIRED || - (senseBuffer->SenseKey & 0xf) == SCSI_SENSE_UNIT_ATTENTION) { - - ULONG sizeNeeded; - ULONG tmpSize; - BOOLEAN overFlow; - - DebugPrint((1, "ScsiFlopProcessError: Reinitializing the floppy.\n")); - - // - // Send the special mode sense command to enable writes on the - // floptical drive. - // - - alignment = DeviceObject->AlignmentRequirement ? - DeviceObject->AlignmentRequirement : 1; - - sizeNeeded = 0; - overFlow = TRUE; - if (SUCCEEDED(ULongAdd(sizeof(COMPLETION_CONTEXT), 0x2a, &tmpSize))) { - - if (SUCCEEDED(ULongAdd(tmpSize, (ULONG) alignment, &sizeNeeded))) { - overFlow = FALSE; - } - } - - context = NULL; - - if (!overFlow) { - context = ExAllocatePool(NonPagedPoolNx, sizeNeeded); - } - - if (context == NULL) { - - // - // If there is not enough memory to fulfill this request, - // simply return. A subsequent retry will fail and another - // chance to start the unit. - // - - return; - } - -#if (NTDDI_VERSION >= NTDDI_WIN8) - srb = &context->Srb.Srb; -#else - srb = &context->Srb; -#endif - - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - // - // Set the transfer length. - // - - srb->DataTransferLength = 0x2a; - srb->SrbFlags = SRB_FLAGS_DATA_IN | SRB_FLAGS_DISABLE_AUTOSENSE | SRB_FLAGS_DISABLE_SYNCH_TRANSFER; - - // - // The data buffer must be aligned. - // - - srb->DataBuffer = (PVOID) (((ULONG_PTR) (context + 1) + (alignment - 1)) & - ~(alignment - 1)); - - - // - // Build the start unit CDB. - // - - srb->CdbLength = 6; - cdb = (PCDB)srb->Cdb; - cdb->MODE_SENSE.OperationCode = SCSIOP_MODE_SENSE; - cdb->MODE_SENSE.PageCode = 0x2e; - cdb->MODE_SENSE.AllocationLength = 0x2a; - - majorFunction = IRP_MJ_READ; - - } else { - - return; - } - - context->DeviceObject = DeviceObject; - - // - // Write length to SRB. - // - - srb->Length = SCSI_REQUEST_BLOCK_SIZE; - - srb->Function = SRB_FUNCTION_EXECUTE_SCSI; - srb->TimeOutValue = fdoExtension->TimeOutValue; - - // - // Build the asynchronous request - // to be sent to the port driver. - // - - irp = IoBuildAsynchronousFsdRequest(majorFunction, - DeviceObject, - srb->DataBuffer, - srb->DataTransferLength, - &largeInt, - NULL); - - if(irp == NULL) { - ExFreePool(context); - return; - } - - - IoSetCompletionRoutine(irp, - (PIO_COMPLETION_ROUTINE)ClassAsynchronousCompletion, - context, - TRUE, - TRUE, - TRUE); - - ClassAcquireRemoveLock(DeviceObject, irp); - - irpStack = IoGetNextIrpStackLocation(irp); - - irpStack->MajorFunction = IRP_MJ_SCSI; - - srb->OriginalRequest = irp; - - // - // Save SRB address in next stack for port driver. - // - - irpStack->Parameters.Others.Argument1 = (PVOID)srb; - - // - // Can't release the remove lock yet - let ClassAsynchronousCompletion - // take care of that for us. - // - - (VOID)IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, irp); - - return; -} - -NTSTATUS -FlopticalFormatMedia( - PDEVICE_OBJECT DeviceObject, - PFORMAT_PARAMETERS Format - ) -/*++ - -Routine Description: - - This routine is used to do perform a format tracks for the 20.8 MB - floppy. Because the device does not support format tracks and the full - format takes a long time a write of zeros is done instead. - -Arguments: - - DeviceObject - Supplies the device object to be tested. - - Format - Supplies the format parameters. - -Return Value: - - Returns a status for the operation. - ---*/ -{ - IO_STATUS_BLOCK ioStatus; - PIRP irp; - KEVENT event; - LARGE_INTEGER offset; - ULONG length; - PVOID buffer; - PDRIVE_MEDIA_CONSTANTS driveMediaConstants; - NTSTATUS status; - - PAGED_CODE(); - - driveMediaConstants = &DriveMediaConstants[Drive2080Media2080]; - - // - // Calculate the length of the buffer. - // - - length = ((Format->EndCylinderNumber - Format->StartCylinderNumber) * - driveMediaConstants->NumberOfHeads + - Format->EndHeadNumber - Format->StartHeadNumber + 1) * - driveMediaConstants->SectorsPerTrack * - driveMediaConstants->BytesPerSector; - - buffer = ExAllocatePool(NonPagedPoolNxCacheAligned, length); - - if (buffer == NULL) { - return(STATUS_INSUFFICIENT_RESOURCES); - } - - RtlZeroMemory(buffer, length); - - offset.QuadPart = - (Format->StartCylinderNumber * driveMediaConstants->NumberOfHeads + - Format->StartHeadNumber) * driveMediaConstants->SectorsPerTrack * - driveMediaConstants->BytesPerSector; - - // - // Set the event object to the unsignaled state. - // It will be used to signal request completion. - // - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - // - // Build the synchronous request with data transfer. - // - - irp = IoBuildSynchronousFsdRequest( - IRP_MJ_WRITE, - DeviceObject, - buffer, - length, - &offset, - &event, - &ioStatus); - - if (irp != NULL) { - status = IoCallDriver(DeviceObject, irp); - - if (status == STATUS_PENDING) { - - // - // Wait for the request to complete if necessary. - // - - KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); - } - - // - // If the call driver suceeded then set the status to the status block. - // - - if (NT_SUCCESS(status)) { - status = ioStatus.Status; - } - } else { - status = STATUS_INSUFFICIENT_RESOURCES; - } - - ExFreePool(buffer); - - return(status); - -} - - -NTSTATUS -ScsiFlopRemoveDevice( - IN PDEVICE_OBJECT DeviceObject, - IN UCHAR Type - ) -/*++ - -Routine Description: - - This routine is responsible for releasing any resources in use by the - sfloppy driver. This routine is called - when all outstanding requests have been completed and the driver has - disappeared - no requests may be issued to the lower drivers. - -Arguments: - - DeviceObject - the device object being removed - - Type - the type of remove operation (QUERY, REMOVE or CANCEL) - -Return Value: - - for a query - success if the device can be removed or a failure code - indiciating why not. - - for a remove or cancel - STATUS_SUCCESS - ---*/ - -{ - PFUNCTIONAL_DEVICE_EXTENSION deviceExtension = - DeviceObject->DeviceExtension; - PDISK_DATA diskData = deviceExtension->CommonExtension.DriverData; - NTSTATUS status; - - PAGED_CODE(); - - if((Type == IRP_MN_QUERY_REMOVE_DEVICE) || - (Type == IRP_MN_CANCEL_REMOVE_DEVICE)) { - return STATUS_SUCCESS; - } - - if (Type == IRP_MN_REMOVE_DEVICE){ - if(deviceExtension->DeviceDescriptor) { - ExFreePool(deviceExtension->DeviceDescriptor); - deviceExtension->DeviceDescriptor = NULL; - } - - if(deviceExtension->AdapterDescriptor) { - ExFreePool(deviceExtension->AdapterDescriptor); - deviceExtension->AdapterDescriptor = NULL; - } - - if(deviceExtension->SenseData) { - ExFreePool(deviceExtension->SenseData); - deviceExtension->SenseData = NULL; - } - - ClassDeleteSrbLookasideList(&deviceExtension->CommonExtension); - } - - if(diskData->FloppyInterfaceString.Buffer != NULL) { - - status = IoSetDeviceInterfaceState( - &(diskData->FloppyInterfaceString), - FALSE); - - if (!NT_SUCCESS(status)) { - // Failed to disable device interface during removal. Not a fatal error. - DebugPrint((1, "ScsiFlopRemoveDevice: Unable to set device " - "interface state to FALSE for fdo %p " - "[%08lx]\n", - DeviceObject, status)); - } - - RtlFreeUnicodeString(&(diskData->FloppyInterfaceString)); - RtlInitUnicodeString(&(diskData->FloppyInterfaceString), NULL); - } - - if(Type == IRP_MN_REMOVE_DEVICE) { - IoGetConfigurationInformation()->FloppyCount--; - } - - return STATUS_SUCCESS; -} - - -NTSTATUS -ScsiFlopStopDevice( - IN PDEVICE_OBJECT DeviceObject, - IN UCHAR Type - ) -{ - UNREFERENCED_PARAMETER(DeviceObject); - UNREFERENCED_PARAMETER(Type); - - return STATUS_SUCCESS; -} - - -NTSTATUS -USBFlopGetMediaTypes( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ) -{ -/*++ - -Routine Description: - - This routines determines the current or default geometry of the drive - for IOCTL_DISK_GET_DRIVE_GEOMETRY, or all currently supported geometries - of the drive (which is determined by its currently inserted media) for - IOCTL_DISK_GET_MEDIA_TYPES. - - The returned geometries are determined by issuing a Read Format Capacities - request and then matching the returned {Number of Blocks, Block Length} - pairs in a table of known floppy geometries. - -Arguments: - - DeviceObject - Supplies the device object. - - Irp - A IOCTL_DISK_GET_DRIVE_GEOMETRY or a IOCTL_DISK_GET_MEDIA_TYPES Irp. - If NULL, the device geometry is updated with the current device - geometry. - -Return Value: - - Status is returned. - ---*/ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension; - PIO_STACK_LOCATION irpStack; - ULONG ioControlCode; - PDISK_GEOMETRY outputBuffer; - PDISK_GEOMETRY outputBufferEnd; - ULONG outputBufferLength; - PSCSI_REQUEST_BLOCK srb; - PVOID dataBuffer; - ULONG dataTransferLength; - struct _READ_FORMATTED_CAPACITIES *cdb; - PFORMATTED_CAPACITY_LIST capList; - NTSTATUS status; - - PAGED_CODE(); - - fdoExtension = DeviceObject->DeviceExtension; - - if (Irp != NULL) { - - // Get the Irp parameters - // - irpStack = IoGetCurrentIrpStackLocation(Irp); - - ioControlCode = irpStack->Parameters.DeviceIoControl.IoControlCode; - - Irp->IoStatus.Information = 0; - - outputBuffer = (PDISK_GEOMETRY) Irp->AssociatedIrp.SystemBuffer; - - outputBufferLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength; - - if (outputBufferLength < sizeof(DISK_GEOMETRY)) - { - return STATUS_BUFFER_TOO_SMALL; - } - - // Pointer arithmetic to allow multiple DISK_GEOMETRY's to be returned. - // Rounds BufferEnd down to integral multiple of DISK_GEOMETRY structs. - // - outputBufferEnd = outputBuffer + - outputBufferLength / sizeof(DISK_GEOMETRY); - - } else { - - // No Irp to return the result in, just update the current geometry - // in the device extension. - // - ioControlCode = IOCTL_DISK_GET_DRIVE_GEOMETRY; - - outputBuffer = NULL; - - outputBufferEnd = NULL; - - outputBufferLength = 0; - } - - if (ioControlCode == IOCTL_DISK_GET_DRIVE_GEOMETRY) { - - fdoExtension->DiskGeometry.MediaType = Unknown; - - status = ClassReadDriveCapacity(DeviceObject); - - if (!NT_SUCCESS(status)) - { - // If the media is not recongized, we want to return the default - // geometry so that the media can be formatted. Unrecognized media - // causes SCSI_SENSE_MEDIUM_ERROR, which gets reported as - // STATUS_DEVICE_DATA_ERROR. Ignore these errors, but return other - // errors, such as STATUS_NO_MEDIA_IN_DEVICE. - // - if (status != STATUS_UNRECOGNIZED_MEDIA) - { - DebugPrint((2,"IOCTL_DISK_GET_DRIVE_GEOMETRY returns %08X\n", status)); - - return status; - } - } - } - - // Allocate an SRB for the SCSIOP_READ_FORMATTED_CAPACITY request - // - srb = ExAllocatePool(NonPagedPoolNx, SCSI_REQUEST_BLOCK_SIZE); - - if (srb == NULL) - { - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Allocate a transfer buffer for the SCSIOP_READ_FORMATTED_CAPACITY request - // The length of the returned descriptor array is limited to a byte field - // in the capacity list header. - // - dataTransferLength = sizeof(FORMATTED_CAPACITY_LIST) + - 31 * sizeof(FORMATTED_CAPACITY_DESCRIPTOR); - - ASSERT(dataTransferLength < 0x100); - - dataBuffer = ExAllocatePool(NonPagedPoolNx, dataTransferLength); - - if (dataBuffer == NULL) - { - ExFreePool(srb); - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Initialize the SRB and CDB - // - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - RtlZeroMemory(dataBuffer, dataTransferLength); - - srb->CdbLength = sizeof(struct _READ_FORMATTED_CAPACITIES); - - srb->TimeOutValue = fdoExtension->TimeOutValue; - - cdb = (struct _READ_FORMATTED_CAPACITIES *)srb->Cdb; - - cdb->OperationCode = SCSIOP_READ_FORMATTED_CAPACITY; - cdb->AllocationLength[1] = (UCHAR)dataTransferLength; - - // - // Send down the SCSIOP_READ_FORMATTED_CAPACITY request - // - status = ClassSendSrbSynchronous(DeviceObject, - srb, - dataBuffer, - dataTransferLength, - FALSE); - - capList = (PFORMATTED_CAPACITY_LIST)dataBuffer; - - // If we don't get as much data as requested, it is not an error. - // - if (SRB_STATUS(srb->SrbStatus) == SRB_STATUS_DATA_OVERRUN) - { - status = STATUS_SUCCESS; - } - - if (NT_SUCCESS(status) && - srb->DataTransferLength >= sizeof(FORMATTED_CAPACITY_LIST) && - capList->CapacityListLength && - capList->CapacityListLength % sizeof(FORMATTED_CAPACITY_DESCRIPTOR) == 0) - { - ULONG NumberOfBlocks; - ULONG BlockLength; - ULONG count; - ULONG i, j; - LONG currentGeometry; - BOOLEAN capacityMatches[FLOPPY_CAPACITIES]; - - // Subtract the size of the Capacity List Header to get - // just the size of the Capacity List Descriptor array. - // - srb->DataTransferLength -= sizeof(FORMATTED_CAPACITY_LIST); - - // Only look at the Capacity List Descriptors that were actually - // returned. - // - if (srb->DataTransferLength < capList->CapacityListLength) - { - count = srb->DataTransferLength / - sizeof(FORMATTED_CAPACITY_DESCRIPTOR); - } - else - { - count = capList->CapacityListLength / - sizeof(FORMATTED_CAPACITY_DESCRIPTOR); - } - - // Updated only if a match is found for the first Capacity List - // Descriptor returned by the device. - // - currentGeometry = -1; - - // Initialize the array of capacities that hit a match. - // - RtlZeroMemory(capacityMatches, sizeof(capacityMatches)); - - // Iterate over each Capacity List Descriptor returned from the device - // and record matching capacities in the capacity match array. - // - for (i = 0; i < count; i++) - { - NumberOfBlocks = (capList->Descriptors[i].NumberOfBlocks[0] << 24) + - (capList->Descriptors[i].NumberOfBlocks[1] << 16) + - (capList->Descriptors[i].NumberOfBlocks[2] << 8) + - (capList->Descriptors[i].NumberOfBlocks[3]); - - BlockLength = (capList->Descriptors[i].BlockLength[0] << 16) + - (capList->Descriptors[i].BlockLength[1] << 8) + - (capList->Descriptors[i].BlockLength[2]); - - // Given the {NumberOfBlocks, BlockLength} from this Capacity List - // Descriptor, find a matching entry in FloppyCapacities[]. - // - for (j = 0; j < FLOPPY_CAPACITIES; j++) - { - if (NumberOfBlocks == FloppyCapacities[j].NumberOfBlocks && - BlockLength == FloppyCapacities[j].BlockLength) - { - // A matching capacity was found, record it. - // - capacityMatches[j] = TRUE; - - // A match was found for the first Capacity List - // Descriptor returned by the device. - // - if (i == 0) - { - currentGeometry = j; - } - } else if ((capList->Descriptors[i].Valid) && - (BlockLength == FloppyCapacities[j].BlockLength)) { - - ULONG inx; - ULONG mediaInx; - - // - // Check if this is 32MB media type. 32MB media - // reports variable NumberOfBlocks. So we cannot - // use that to determine the drive type - // - inx = DetermineDriveType(DeviceObject); - if (inx != DRIVE_TYPE_NONE) { - mediaInx = DriveMediaLimits[inx].HighestDriveMediaType; - if ((DriveMediaConstants[mediaInx].MediaType) - == F3_32M_512) { - capacityMatches[j] = TRUE; - - if (i == 0) { - currentGeometry = j; - } - } - } - } - } - } - - // Default status is STATUS_UNRECOGNIZED_MEDIA, unless we return - // either STATUS_SUCCESS or STATUS_BUFFER_OVERFLOW. - // - status = STATUS_UNRECOGNIZED_MEDIA; - - if (ioControlCode == IOCTL_DISK_GET_DRIVE_GEOMETRY) { - - if (currentGeometry != -1) - { - // Update the current device geometry - // - fdoExtension->DiskGeometry = FloppyGeometries[currentGeometry]; - - // - // Calculate sector to byte shift. - // - - WHICH_BIT(fdoExtension->DiskGeometry.BytesPerSector, - fdoExtension->SectorShift); - - fdoExtension->CommonExtension.PartitionLength.QuadPart = - (LONGLONG)FloppyCapacities[currentGeometry].NumberOfBlocks * - FloppyCapacities[currentGeometry].BlockLength; - - DebugPrint((2,"geometry is: %3d %2d %d %2d %4d %2d %08X\n", - fdoExtension->DiskGeometry.Cylinders.LowPart, - fdoExtension->DiskGeometry.MediaType, - fdoExtension->DiskGeometry.TracksPerCylinder, - fdoExtension->DiskGeometry.SectorsPerTrack, - fdoExtension->DiskGeometry.BytesPerSector, - fdoExtension->SectorShift, - fdoExtension->CommonExtension.PartitionLength.LowPart)); - - // Return the current device geometry - // - if (Irp != NULL) - { - *outputBuffer = FloppyGeometries[currentGeometry]; - - Irp->IoStatus.Information = sizeof(DISK_GEOMETRY); - } - - status = STATUS_SUCCESS; - } - - } else { - - // Iterate over the capacities and return the geometry - // corresponding to each matching Capacity List Descriptor - // returned from the device. - // - // The resulting list should be in sorted ascending order, - // assuming that the FloppyGeometries[] array is in sorted - // ascending order. - // - for (i = 0; i < FLOPPY_CAPACITIES; i++) - { - if (capacityMatches[i] && FloppyCapacities[i].CanFormat) - { - if (outputBuffer < outputBufferEnd) - { - *outputBuffer++ = FloppyGeometries[i]; - - Irp->IoStatus.Information += sizeof(DISK_GEOMETRY); - - DebugPrint((2,"geometry : %3d %2d %d %2d %4d\n", - FloppyGeometries[i].Cylinders.LowPart, - FloppyGeometries[i].MediaType, - FloppyGeometries[i].TracksPerCylinder, - FloppyGeometries[i].SectorsPerTrack, - FloppyGeometries[i].BytesPerSector)); - - status = STATUS_SUCCESS; - } - else - { - // We ran out of output buffer room before we ran out - // geometries to return. - // - status = STATUS_BUFFER_OVERFLOW; - } - } - } - } - } - else if (NT_SUCCESS(status)) - { - // The SCSIOP_READ_FORMATTED_CAPACITY request was successful, but - // returned data does not appear valid. - // - status = STATUS_UNSUCCESSFUL; - } - - ExFreePool(dataBuffer); - ExFreePool(srb); - - return status; -} - - -NTSTATUS -USBFlopFormatTracks( - IN PDEVICE_OBJECT DeviceObject, - IN PIRP Irp - ) -{ -/*++ - -Routine Description: - - This routines formats the specified tracks. If multiple tracks are - specified, each is formatted with a separate Format Unit request. - -Arguments: - - DeviceObject - Supplies the device object. - - Irp - A IOCTL_DISK_FORMAT_TRACKS Irp. - -Return Value: - - Status is returned. - ---*/ - PFUNCTIONAL_DEVICE_EXTENSION fdoExtension; - PIO_STACK_LOCATION irpStack; - PFORMAT_PARAMETERS formatParameters; - PDISK_GEOMETRY geometry; - PFORMATTED_CAPACITY capacity; - PSCSI_REQUEST_BLOCK srb; - PFORMAT_UNIT_PARAMETER_LIST parameterList; - PCDB12FORMAT cdb; - ULONG i; - ULONG cylinder, head; - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - fdoExtension = DeviceObject->DeviceExtension; - - // Get the Irp parameters - // - irpStack = IoGetCurrentIrpStackLocation(Irp); - - if (irpStack->Parameters.DeviceIoControl.InputBufferLength < - sizeof(FORMAT_PARAMETERS)) - { - return STATUS_INVALID_PARAMETER; - } - - formatParameters = (PFORMAT_PARAMETERS)Irp->AssociatedIrp.SystemBuffer; - - // Find the geometry / capacity entries corresponding to the format - // parameters MediaType - // - geometry = NULL; - capacity = NULL; - - for (i=0; iMediaType) - { - geometry = &FloppyGeometries[i]; - capacity = &FloppyCapacities[i]; - - break; - } - } - - if (geometry == NULL) - { - return STATUS_INVALID_PARAMETER; - } - - // Check if the format parameters are valid - // - if ((formatParameters->StartCylinderNumber > - geometry->Cylinders.LowPart - 1) || - - (formatParameters->EndCylinderNumber > - geometry->Cylinders.LowPart - 1) || - - (formatParameters->StartHeadNumber > - geometry->TracksPerCylinder - 1) || - - (formatParameters->EndHeadNumber > - geometry->TracksPerCylinder - 1) || - - (formatParameters->StartCylinderNumber > - formatParameters->EndCylinderNumber) || - - (formatParameters->StartHeadNumber > - formatParameters->EndHeadNumber)) - { - return STATUS_INVALID_PARAMETER; - } - - // Don't low level format LS-120 media, Imation says it's best to not - // do this. - // - if ((formatParameters->MediaType == F3_120M_512) || - (formatParameters->MediaType == F3_240M_512) || - (formatParameters->MediaType == F3_32M_512)) - { - return STATUS_SUCCESS; - } - - // Allocate an SRB for the SCSIOP_FORMAT_UNIT request - // - srb = ExAllocatePool(NonPagedPoolNx, SCSI_REQUEST_BLOCK_SIZE); - - if (srb == NULL) - { - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Allocate a transfer buffer for the SCSIOP_FORMAT_UNIT parameter list - // - parameterList = ExAllocatePool(NonPagedPoolNx, - sizeof(FORMAT_UNIT_PARAMETER_LIST)); - - if (parameterList == NULL) - { - ExFreePool(srb); - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Initialize the parameter list - // - RtlZeroMemory(parameterList, sizeof(FORMAT_UNIT_PARAMETER_LIST)); - - parameterList->DefectListHeader.SingleTrack = 1; - parameterList->DefectListHeader.DisableCert = 1; // TEAC requires this set - parameterList->DefectListHeader.FormatOptionsValid = 1; - parameterList->DefectListHeader.DefectListLengthLsb = 8; - - parameterList->FormatDescriptor.NumberOfBlocks[0] = - (UCHAR)((capacity->NumberOfBlocks >> 24) & 0xFF); - - parameterList->FormatDescriptor.NumberOfBlocks[1] = - (UCHAR)((capacity->NumberOfBlocks >> 16) & 0xFF); - - parameterList->FormatDescriptor.NumberOfBlocks[2] = - (UCHAR)((capacity->NumberOfBlocks >> 8) & 0xFF); - - parameterList->FormatDescriptor.NumberOfBlocks[3] = - (UCHAR)(capacity->NumberOfBlocks & 0xFF); - - parameterList->FormatDescriptor.BlockLength[0] = - (UCHAR)((capacity->BlockLength >> 16) & 0xFF); - - parameterList->FormatDescriptor.BlockLength[1] = - (UCHAR)((capacity->BlockLength >> 8) & 0xFF); - - parameterList->FormatDescriptor.BlockLength[2] = - (UCHAR)(capacity->BlockLength & 0xFF); - - - for (cylinder = formatParameters->StartCylinderNumber; - cylinder <= formatParameters->EndCylinderNumber; - cylinder++) - { - for (head = formatParameters->StartHeadNumber; - head <= formatParameters->EndHeadNumber; - head++) - { - // Initialize the SRB and CDB - // - RtlZeroMemory(srb, SCSI_REQUEST_BLOCK_SIZE); - - srb->CdbLength = sizeof(CDB12FORMAT); - - srb->TimeOutValue = fdoExtension->TimeOutValue; - - cdb = (PCDB12FORMAT)srb->Cdb; - - cdb->OperationCode = SCSIOP_FORMAT_UNIT; - cdb->DefectListFormat = 7; - cdb->FmtData = 1; - cdb->TrackNumber = (UCHAR)cylinder; - cdb->ParameterListLengthLsb = sizeof(FORMAT_UNIT_PARAMETER_LIST); - - parameterList->DefectListHeader.Side = (UCHAR)head; - - // - // Send down the SCSIOP_FORMAT_UNIT request - // - status = ClassSendSrbSynchronous(DeviceObject, - srb, - parameterList, - sizeof(FORMAT_UNIT_PARAMETER_LIST), - TRUE); - - if (!NT_SUCCESS(status)) - { - break; - } - } - if (!NT_SUCCESS(status)) - { - break; - } - } - - if (NT_SUCCESS(status) && formatParameters->StartCylinderNumber == 0) - { - // Update the device geometry - // - - DebugPrint((2,"geometry was: %3d %2d %d %2d %4d %2d %08X\n", - fdoExtension->DiskGeometry.Cylinders.LowPart, - fdoExtension->DiskGeometry.MediaType, - fdoExtension->DiskGeometry.TracksPerCylinder, - fdoExtension->DiskGeometry.SectorsPerTrack, - fdoExtension->DiskGeometry.BytesPerSector, - fdoExtension->SectorShift, - fdoExtension->CommonExtension.PartitionLength.LowPart)); - - fdoExtension->DiskGeometry = *geometry; - - // - // Calculate sector to byte shift. - // - - WHICH_BIT(fdoExtension->DiskGeometry.BytesPerSector, - fdoExtension->SectorShift); - - fdoExtension->CommonExtension.PartitionLength.QuadPart = - (LONGLONG)capacity->NumberOfBlocks * - capacity->BlockLength; - - DebugPrint((2,"geometry is: %3d %2d %d %2d %4d %2d %08X\n", - fdoExtension->DiskGeometry.Cylinders.LowPart, - fdoExtension->DiskGeometry.MediaType, - fdoExtension->DiskGeometry.TracksPerCylinder, - fdoExtension->DiskGeometry.SectorsPerTrack, - fdoExtension->DiskGeometry.BytesPerSector, - fdoExtension->SectorShift, - fdoExtension->CommonExtension.PartitionLength.LowPart)); - } - - // Free everything we allocated - // - ExFreePool(parameterList); - ExFreePool(srb); - - return status; -} diff --git a/storage/sfloppy/src/sfloppy.inf b/storage/sfloppy/src/sfloppy.inf deleted file mode 100644 index 2f5c4bbdf..000000000 --- a/storage/sfloppy/src/sfloppy.inf +++ /dev/null @@ -1,88 +0,0 @@ -; sfloppy.inf -; -; Installation inf for the Floppy Disk Driver (DDK Sample). -; -; (c) Copyright 2002 Microsoft -; -[Version] -Signature="$WINDOWS NT$" -Class=FloppyDisk -ClassGuid={4D36E980-E325-11CE-BFC1-08002BE10318} -Provider=%ProviderString% -CatalogFile=ddk_sample.cat -DriverVer=05/17/2002,5.2.3635.0 -PnpLockdown=1 - -;You must specify which platform is supported by each SourceDisksNames section -;Valid platform identifiers include .x86, .ia64, .alpha, .axp64 -[SourceDisksNames] -12=%floppyClassName%,,, - -;You must also specify which platform is supported by each SourceDisksFiles section -;Valid platform identifiers include .x86, .ia64, .alpha, .axp64 -[SourceDisksFiles] -sfloppy.sys=12 - -[ControlFlags] -ExcludeFromSelect=* - -[DestinationDirs] -sfloppy_copyfiles=12 -DefaultDestDir=12 - -[Manufacturer] -%ManufacturerName%=floppy_device,NTx86,NTia64,NTamd64 - -[floppy_device.NTx86] -%sfloppy_devdesc%=sfloppy_install,GenSFloppy -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_COSM___04 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_VER5___AB -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_HIMA___01 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_VER5___00 - -[floppy_device.NTia64] -%sfloppy_devdesc%=sfloppy_install,GenSFloppy -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_COSM___04 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_VER5___AB -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_HIMA___01 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_VER5___00 - -[floppy_device.NTamd64] -%sfloppy_devdesc%=sfloppy_install,GenSFloppy -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_COSM___04 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_VER5___AB -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskCOMPAQ__LS-120_HIMA___01 -%sfloppy_devdesc%=sfloppy_install,SCSI\DiskMATSHITALS-120_VER5___00 - -;; -;; super floppy -;; -[sfloppy_install.NT] -CopyFiles=sfloppy_copyfiles - -[sfloppy_copyfiles] -sfloppy.sys - -[sfloppy_install.NT.Services] -AddService=sfloppy,2,sfloppy_ServiceInstallSection - -[sfloppy_ServiceInstallSection] -DisplayName=%sfloppy_devdesc% -ServiceType=1 -StartType=3 -ErrorControl=1 -ServiceBinary = %12%\sfloppy.sys - -[sfloppy_install.NT.HW] -AddReg=sfloppyEnable.RegHW - -[sfloppyEnable.RegHW] -HKR,,SuperFloppy,%REG_DWORD%,0x00000001 - -[Strings] -ProviderString="TODO-Set-Provider" -ManufacturerName="TODO-Set-Manufacturer" -floppyClassName="Floppy disk drives" -sfloppy_devdesc="High-Capacity Floppy Disk Drive" - -REG_DWORD=0x00010001 diff --git a/storage/sfloppy/src/sfloppy.rc b/storage/sfloppy/src/sfloppy.rc deleted file mode 100644 index efe6c05c6..000000000 --- a/storage/sfloppy/src/sfloppy.rc +++ /dev/null @@ -1,23 +0,0 @@ -//+------------------------------------------------------------------------- -// -// Microsoft Windows -// -// Copyright (C) Microsoft Corporation, 1997 - 1999 -// -// File: sfloppy.rc -// -//-------------------------------------------------------------------------- - -#include - -#include - -#define VER_FILETYPE VFT_DRV -#define VER_FILESUBTYPE VFT2_DRV_SYSTEM -#define VER_FILEDESCRIPTION_STR "SCSI Floppy Driver" -#define VER_INTERNALNAME_STR "sfloppy.sys" -#define VER_ORIGINALFILENAME_STR "sfloppy.sys" -#define VER_LANGNEUTRAL - -#include "common.ver" - diff --git a/storage/sfloppy/src/sfloppy.vcxproj b/storage/sfloppy/src/sfloppy.vcxproj deleted file mode 100644 index abcc78d0b..000000000 --- a/storage/sfloppy/src/sfloppy.vcxproj +++ /dev/null @@ -1,192 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {97D2E67D-8E5F-43CD-B8EB-C5DBB43C7EB7} - $(MSBuildProjectName) - false - Debug - Win32 - {6B097D1A-972A-41E8-A5C4-3691455FBB8B} - - - - Windows10 - False - Universal - WDM - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Universal - WDM - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - False - Universal - WDM - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Universal - WDM - WindowsKernelModeDriver10.0 - Driver - - - - $(IntDir) - - - - - - - - - - - - - - - - sfloppy - - - sfloppy - - - sfloppy - - - sfloppy - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\classpnp.lib - - - %(AdditionalIncludeDirectories);..\inc - - - %(AdditionalIncludeDirectories);..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\inc - - - sha256 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\classpnp.lib - - - %(AdditionalIncludeDirectories);..\inc - - - %(AdditionalIncludeDirectories);..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\inc - - - sha256 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\classpnp.lib - - - %(AdditionalIncludeDirectories);..\inc - - - %(AdditionalIncludeDirectories);..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\inc - - - sha256 - - - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\classpnp.lib - - - %(AdditionalIncludeDirectories);..\inc - - - %(AdditionalIncludeDirectories);..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\inc - - - sha256 - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/storage/tools/spti/src/spti.vcxproj b/storage/tools/spti/src/spti.vcxproj index 25cb31d5d..6118b8d4a 100644 --- a/storage/tools/spti/src/spti.vcxproj +++ b/storage/tools/spti/src/spti.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/thermal/simsensor/simsensor.inf b/thermal/simsensor/simsensor.inf index 63f7a3689..9775caa5e 100644 Binary files a/thermal/simsensor/simsensor.inf and b/thermal/simsensor/simsensor.inf differ diff --git a/thermal/simsensor/simsensor.vcxproj b/thermal/simsensor/simsensor.vcxproj index efbdd2dc4..a155d12a3 100644 --- a/thermal/simsensor/simsensor.vcxproj +++ b/thermal/simsensor/simsensor.vcxproj @@ -105,6 +105,9 @@ %(PreprocessorDefinitions);DRIVER=1;STRICT=1 %(AdditionalIncludeDirectories);..\inc\ + + SHA256 + diff --git a/thermal/simsensor/simsensor.vcxproj.Filters b/thermal/simsensor/simsensor.vcxproj.Filters index c4d812c1c..20f76bc5a 100644 --- a/thermal/simsensor/simsensor.vcxproj.Filters +++ b/thermal/simsensor/simsensor.vcxproj.Filters @@ -28,4 +28,14 @@ Resource Files + + + Header Files + + + + + Driver Files + + \ No newline at end of file diff --git a/thermal/thermalclient/simtc.inf b/thermal/thermalclient/simtc.inf index 7e607612d..102a010ec 100644 Binary files a/thermal/thermalclient/simtc.inf and b/thermal/thermalclient/simtc.inf differ diff --git a/thermal/thermalclient/simtc.vcxproj b/thermal/thermalclient/simtc.vcxproj index b3ac67437..2ce2a1dca 100644 --- a/thermal/thermalclient/simtc.vcxproj +++ b/thermal/thermalclient/simtc.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -105,6 +105,9 @@ %(PreprocessorDefinitions);DRIVER=1 %(AdditionalIncludeDirectories) + + SHA256 + @@ -123,6 +126,9 @@ %(PreprocessorDefinitions);DRIVER=1 %(AdditionalIncludeDirectories) + + SHA256 + @@ -141,6 +147,9 @@ %(PreprocessorDefinitions);DRIVER=1 %(AdditionalIncludeDirectories) + + SHA256 + @@ -159,6 +168,9 @@ %(PreprocessorDefinitions);DRIVER=1 %(AdditionalIncludeDirectories) + + SHA256 + diff --git a/thermal/thermalclient/simtc.vcxproj.Filters b/thermal/thermalclient/simtc.vcxproj.Filters index efa1939fd..2f8f2a5b4 100644 --- a/thermal/thermalclient/simtc.vcxproj.Filters +++ b/thermal/thermalclient/simtc.vcxproj.Filters @@ -28,4 +28,14 @@ Resource Files + + + Header Files + + + + + Driver Files + + \ No newline at end of file diff --git a/tools/dv/samples/DV-FailDriver-WDM/README.md b/tools/dv/samples/DV-FailDriver-WDM/README.md index 532071c7c..1272a296f 100644 --- a/tools/dv/samples/DV-FailDriver-WDM/README.md +++ b/tools/dv/samples/DV-FailDriver-WDM/README.md @@ -25,6 +25,22 @@ The DV-FailDriver-WDM sample driver contains intentional code errors that are de See [Deploying a Driver to a Test Computer](https://docs.microsoft.com/windows-hardware/drivers/develop/deploying-a-driver-to-a-test-computer) for details on how to deploy the sample. +#### New + +It is highly encouraged when testing a driver to use [DevGen](https://learn.microsoft.com/windows-hardware/drivers/devtest/devgen) to create a [SwDevice](https://learn.microsoft.com/windows/win32/api/_swdevice/). + +__DevGen Usage Example__ + +1. From a terminal (running as admin) on test computer go to the WDK tools path and run `.\devgen /add /bus SWD /hardwareid root\defect_toastmon`. ***If WDK is not available on test computer, simply copy over `devgen.exe`*** + +2. There is now a `Generic software device` available in the system. ***Use Device Manager as a simple means to inspect or from a terminal run `pnputil /enum-devices /deviceid "root\defect_toastmon"`.*** + +3. Now that there is a device with the appropriate hardware ID, deploy/install driver sample accordingly. + +> Note: Use `.\devgen /remove ""` to remove SW device (the path can be copied from output of `.\devgen /add` or from Device Manager). +> +> Device instance path example `"SWD\DEVGEN\{D0299946-2EC2-C146-B00B-E01144166F8B}"` + ## Test the sample See [How to test a driver at runtime](https://docs.microsoft.com/windows-hardware/drivers/develop/how-to-test-a-driver-at-runtime-from-a-command-prompt) for details on how to run tests on the Toastmon driver. diff --git a/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.inf b/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.inf index 44975b918..4af8f55b7 100644 Binary files a/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.inf and b/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.inf differ diff --git a/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.vcxproj b/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.vcxproj index 3a8a6d16a..ad363b30f 100644 --- a/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.vcxproj +++ b/tools/dv/samples/DV-FailDriver-WDM/driver/defect_toastmon.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver diff --git a/tools/sdv/samples/SDV-FailDriver-KMDF/driver/fail_driver1.vcxproj b/tools/sdv/samples/SDV-FailDriver-KMDF/driver/fail_driver1.vcxproj index 912be491d..62362adb0 100644 --- a/tools/sdv/samples/SDV-FailDriver-KMDF/driver/fail_driver1.vcxproj +++ b/tools/sdv/samples/SDV-FailDriver-KMDF/driver/fail_driver1.vcxproj @@ -31,7 +31,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -39,7 +39,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -47,7 +47,7 @@ Windows10 False - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver @@ -55,7 +55,7 @@ Windows10 True - Desktop + Universal KMDF WindowsKernelModeDriver10.0 Driver diff --git a/tools/sdv/samples/SDV-FailDriver-NDIS/driver/sdvmp.vcxproj b/tools/sdv/samples/SDV-FailDriver-NDIS/driver/sdvmp.vcxproj index f89012d11..9489a2280 100644 --- a/tools/sdv/samples/SDV-FailDriver-NDIS/driver/sdvmp.vcxproj +++ b/tools/sdv/samples/SDV-FailDriver-NDIS/driver/sdvmp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver diff --git a/tools/sdv/samples/SDV-FailDriver-STORPORT/driver/lsi_u3.vcxproj b/tools/sdv/samples/SDV-FailDriver-STORPORT/driver/lsi_u3.vcxproj index ca461e0aa..af3b63a8e 100644 --- a/tools/sdv/samples/SDV-FailDriver-STORPORT/driver/lsi_u3.vcxproj +++ b/tools/sdv/samples/SDV-FailDriver-STORPORT/driver/lsi_u3.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal Miniport WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal Miniport WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal Miniport WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal Miniport WindowsKernelModeDriver10.0 Driver diff --git a/tools/sdv/samples/SDV-FailDriver-WDM/driver/fail_driver1.vcxproj b/tools/sdv/samples/SDV-FailDriver-WDM/driver/fail_driver1.vcxproj index 5a45eb5bb..2f57650e4 100644 --- a/tools/sdv/samples/SDV-FailDriver-WDM/driver/fail_driver1.vcxproj +++ b/tools/sdv/samples/SDV-FailDriver-WDM/driver/fail_driver1.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Desktop + Universal WDM WindowsKernelModeDriver10.0 Driver diff --git a/usb/UcmCxUcsi/UcmCxUcsi.inf b/usb/UcmCxUcsi/UcmCxUcsi.inf index 9e8769468..661424db5 100644 Binary files a/usb/UcmCxUcsi/UcmCxUcsi.inf and b/usb/UcmCxUcsi/UcmCxUcsi.inf differ diff --git a/usb/UcmCxUcsi/UcmCxUcsi.vcxproj b/usb/UcmCxUcsi/UcmCxUcsi.vcxproj index c7371dd57..66355942b 100644 --- a/usb/UcmCxUcsi/UcmCxUcsi.vcxproj +++ b/usb/UcmCxUcsi/UcmCxUcsi.vcxproj @@ -50,7 +50,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver true 1 0 diff --git a/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.inf b/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.inf index 9fbeeeec7..5a526ab95 100644 Binary files a/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.inf and b/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.inf differ diff --git a/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.vcxproj b/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.vcxproj index d7722879f..f6433899d 100644 --- a/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.vcxproj +++ b/usb/UcmTcpciCxClientSample/UcmTcpciCxClientSample.vcxproj @@ -74,7 +74,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -82,7 +82,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -90,7 +90,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -98,7 +98,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -106,7 +106,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -114,7 +114,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -122,7 +122,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -130,7 +130,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver diff --git a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Acpi.h b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Acpi.h index 469fbb0a2..7fcadc510 100644 --- a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Acpi.h +++ b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Acpi.h @@ -113,6 +113,7 @@ class Acpi _In_ PACPI_NOTIFICATION_CALLBACK_CONTEXT CallbackConext ) { + PAGED_CODE(); return RegisterNotificationCallbackInternal(CallbackConext); } diff --git a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Fdo.cpp b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Fdo.cpp index 2b01bb022..7133c8d6e 100644 --- a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Fdo.cpp +++ b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Fdo.cpp @@ -372,6 +372,7 @@ VOID Fdo::DestroyPpmObject() { TRACE_FUNC_ENTRY(TRACE_FLAG_FDO); + PAGED_CODE(); WDFDEVICE device = GetObjectHandle(); diff --git a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Ppm.cpp b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Ppm.cpp index c04931a05..a0acee7a8 100644 --- a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Ppm.cpp +++ b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/Ppm.cpp @@ -160,6 +160,7 @@ Ppm::PreparePpmConfig( ) { TRACE_FUNC_ENTRY(TRACE_FLAG_PPM); + PAGED_CODE(); NTSTATUS status; bool IsUsbDeviceControllerEnabled; @@ -500,6 +501,7 @@ Ppm::EvtSendData( ) { TRACE_FUNC_ENTRY(TRACE_FLAG_PPM); + PAGED_CODE(); NTSTATUS status; PUCMUCSI_PPM_SEND_UCSI_DATA_BLOCK_IN_PARAMS inParams; @@ -533,6 +535,7 @@ Ppm::EvtReceiveData( ) { TRACE_FUNC_ENTRY(TRACE_FLAG_PPM); + PAGED_CODE(); NTSTATUS status; diff --git a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.inf b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.inf index 04be1394d..c52e7865e 100644 Binary files a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.inf and b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.inf differ diff --git a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.vcxproj b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.vcxproj index d08edaa3c..136932e7f 100644 --- a/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.vcxproj +++ b/usb/UcmUcsiAcpiSample/UcmUcsiAcpiSample/UcmUcsiAcpiSample.vcxproj @@ -34,7 +34,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -42,7 +42,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -50,7 +50,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver Windows10 @@ -58,7 +58,7 @@ WindowsKernelModeDriver10.0 Driver KMDF - Universal + Windows Driver diff --git a/usb/kmdf_enumswitches/sys/kmdf_enumswitches.inx b/usb/kmdf_enumswitches/sys/kmdf_enumswitches.inx index 4ba231a7b..d9d1366b8 100644 Binary files a/usb/kmdf_enumswitches/sys/kmdf_enumswitches.inx and b/usb/kmdf_enumswitches/sys/kmdf_enumswitches.inx differ diff --git a/usb/kmdf_enumswitches/sys/kmdf_enumswitches.vcxproj b/usb/kmdf_enumswitches/sys/kmdf_enumswitches.vcxproj index 883f548cf..9f2c505ce 100644 --- a/usb/kmdf_enumswitches/sys/kmdf_enumswitches.vcxproj +++ b/usb/kmdf_enumswitches/sys/kmdf_enumswitches.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/kmdf_fx2/driver/osrusbfx2.inx b/usb/kmdf_fx2/driver/osrusbfx2.inx index c40a91926..1185053ec 100644 Binary files a/usb/kmdf_fx2/driver/osrusbfx2.inx and b/usb/kmdf_fx2/driver/osrusbfx2.inx differ diff --git a/usb/kmdf_fx2/driver/osrusbfx2.vcxproj b/usb/kmdf_fx2/driver/osrusbfx2.vcxproj index 747de89e1..de6d26273 100644 --- a/usb/kmdf_fx2/driver/osrusbfx2.vcxproj +++ b/usb/kmdf_fx2/driver/osrusbfx2.vcxproj @@ -32,7 +32,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -40,7 +40,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -48,7 +48,7 @@ Windows10 False - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -56,7 +56,7 @@ Windows10 True - Desktop + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/kmdf_fx2/exe/osrusbfx2.vcxproj b/usb/kmdf_fx2/exe/osrusbfx2.vcxproj index 379f780d8..dfcc81e15 100644 --- a/usb/kmdf_fx2/exe/osrusbfx2.vcxproj +++ b/usb/kmdf_fx2/exe/osrusbfx2.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/usb/ufxclientsample/UfxClientSample.inx b/usb/ufxclientsample/UfxClientSample.inx index 7ee9f649d..01c37a10b 100644 Binary files a/usb/ufxclientsample/UfxClientSample.inx and b/usb/ufxclientsample/UfxClientSample.inx differ diff --git a/usb/ufxclientsample/ufxclientsample.vcxproj b/usb/ufxclientsample/ufxclientsample.vcxproj index 4d2164ba2..47191de81 100644 --- a/usb/ufxclientsample/ufxclientsample.vcxproj +++ b/usb/ufxclientsample/ufxclientsample.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/umdf2_fx2/driver/osrusbfx2um.inx b/usb/umdf2_fx2/driver/osrusbfx2um.inx index baa04707b..4d22fdbe8 100644 Binary files a/usb/umdf2_fx2/driver/osrusbfx2um.inx and b/usb/umdf2_fx2/driver/osrusbfx2um.inx differ diff --git a/usb/umdf2_fx2/exe/osrusbfx2.vcxproj b/usb/umdf2_fx2/exe/osrusbfx2.vcxproj index 379f780d8..dfcc81e15 100644 --- a/usb/umdf2_fx2/exe/osrusbfx2.vcxproj +++ b/usb/umdf2_fx2/exe/osrusbfx2.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/usb/umdf_filter_kmdf/Package/package.VcxProj b/usb/umdf_filter_kmdf/Package/package.VcxProj deleted file mode 100644 index 128c8ff60..000000000 --- a/usb/umdf_filter_kmdf/Package/package.VcxProj +++ /dev/null @@ -1,90 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - {837F98CF-D3A4-472C-BACC-47950340E57B} - - - {ADCCB27A-E522-4367-86B9-9C9DF2636B93} - - - - WindowsKernelModeDriver10.0 - Utility - Package - true - Debug - - - - {10E372EF-AE85-4528-919C-A261253EDDAE} - {4535F3DF-5A13-4953-9565-74B05B8FA4C6} - $(MSBuildProjectName) - - - Windows10 - true - - - Windows10 - false - - - Windows10 - true - - - Windows10 - false - - - - - - - - - - - DbgengKernelDebugger - False - None - - - - - - %PathToInf% - False - False - True - - 133563 - - - - sha256 - - - - - - \ No newline at end of file diff --git a/usb/umdf_filter_kmdf/Package/package.VcxProj.Filters b/usb/umdf_filter_kmdf/Package/package.VcxProj.Filters deleted file mode 100644 index fde842eb9..000000000 --- a/usb/umdf_filter_kmdf/Package/package.VcxProj.Filters +++ /dev/null @@ -1,21 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {0ED5A10B-EA82-464B-939C-FD3665A42A97} - - - h;hpp;hxx;hm;inl;inc;xsd - {8283F5F0-093B-48C9-A2FC-EA7455F9A36D} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {0B52CF91-796F-49F5-9C6E-23FC9C521570} - - - inf;inv;inx;mof;mc; - {7C0D1D60-5B24-411C-BA58-9FED667338B0} - - - \ No newline at end of file diff --git a/usb/umdf_filter_kmdf/README.md b/usb/umdf_filter_kmdf/README.md deleted file mode 100644 index 4f7d0e416..000000000 --- a/usb/umdf_filter_kmdf/README.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -page_type: sample -description: "Demonstrates how to load a UMDF filter driver as an upper filter driver above the kmdf_fx2 sample driver." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Sample UMDF Filter above KMDF Function Driver for OSR USB-FX2 (UMDF Version 1) - -The umdf\_filter\_kmdf sample demonstrates how to load a UMDF filter driver as an upper filter driver above the kmdf\_fx2 sample driver. - -The sample includes Event Tracing for Windows (ETW) tracing support, and is written for the [OSR USB-FX2 Learning Kit](https://www.osronline.com/hardware/OSRFX2_32.pdf0. - -## Build the sample - -The default Solution build configuration is **Debug** and **Win32**. - -1. Open the driver project or solution in Visual Studio (find *filtername*.sln or *filtername*.vcxproj). - -1. Right-click the solution in the **Solutions Explorer** and select **Configuration Manager**. - -1. From the **Configuration Manager**, select the **Active Solution Configuration** (for example, Debug or Release) and the **Active Solution Platform** (for example, Win32) that correspond to the type of build you are interested in. - -1. From the **Build** menu, click **Build Solution** (Ctrl+Shift+B). - -## Overview - -- The device is based on the development board supplied with the Cypress EZ-USB FX2 Development Kit (CY3681). - -- It contains 1 interface and 3 endpoints (Interrupt IN, Bulk Out, Bulk IN). - -- Firmware supports vendor commands to query or set LED Bar graph display and 7-segment LED display, and to query toggle switch states. - -- Interrupt Endpoint: - - - Sends an 8-bit value that represents the state of the switches. - - - Sent on startup, resume from suspend, and whenever the switch pack setting changes. - - - Firmware does not de-bounce the switch pack. - - - One switch change can result in multiple bytes being sent. - - - Bits are in the reverse order of the labels on the pack (for example, bit 0x80 is labeled 1 on the pack). - -- Bulk Endpoints are configured for loopback: - - - The device moves data from IN endpoint to OUT endpoint. - - - The device does not change the values of the data it receives nor does it internally create any data. - - - Endpoints are always double buffered. - - - Maximum packet size depends on speed (64 full speed, 512 high speed). - -- ETW events: - - - Included osrusbfx2.man, which describes events added. - - - Three events are targeted to the event log: - - - Failure during the add device routine. - - - Failure to start the OSR device on a USB 1.1 controller. - - - Invocation of the "re-enumerate device" IOCTL. - - - Read/write start/stop events can be used to measure the time taken. - -## Testing the driver - -You can test this sample either by using the [Custom driver access](https://go.microsoft.com/fwlink/p/?linkid=2114373) sample application, or by using the osrusbfx2.exe test application. For information on how to build and use the osrusbfx2.exe application, see the test instructions for the [kmdf\_fx2](https://docs.microsoft.com/samples/microsoft/windows-driver-samples/sample-kmdf-function-driver-for-osr-usb-fx2/) sample. - -## Code tour - -| Folder | Description | -| --- | --- | -| usb\umdf_filter_kmdf\kmdf_driver | This directory contains source code for the kmdf_fx2 sample driver. | -| usb\umdf_filter_kmdf\umdf_filter | This directory contains the UMDF filter driver. | diff --git a/usb/umdf_filter_kmdf/inc/WUDFOsrUsbPublic.h b/usb/umdf_filter_kmdf/inc/WUDFOsrUsbPublic.h deleted file mode 100644 index 6681fa146..000000000 --- a/usb/umdf_filter_kmdf/inc/WUDFOsrUsbPublic.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - WUDFOsrUsbPublic.h - -Abstract: - - This module contains the common declarations shared by driver - and user applications for the UMDF OSR device sample. - - Note that this driver does NOT use the same device interface GUID - as the KMDF OSR USB sample. - -Environment: - - user and kernel - ---*/ - -#pragma once - -// -// Define an Interface Guid so that app can find the device and talk to it. -// - -// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} -DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, - 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); - diff --git a/usb/umdf_filter_kmdf/inc/list.h b/usb/umdf_filter_kmdf/inc/list.h deleted file mode 100644 index 38d0b1e90..000000000 --- a/usb/umdf_filter_kmdf/inc/list.h +++ /dev/null @@ -1,77 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - list.h - -Abstract: - - This module contains doubly linked list macros - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -FORCEINLINE -VOID -InitializeListHead( - IN PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -VOID -InsertHeadList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -InsertTailList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} diff --git a/usb/umdf_filter_kmdf/inc/public.h b/usb/umdf_filter_kmdf/inc/public.h deleted file mode 100644 index 2c3f6805c..000000000 --- a/usb/umdf_filter_kmdf/inc/public.h +++ /dev/null @@ -1,217 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - public.h - -Abstract: - - Public definitions for the OSR_FX2 device operations. - -Environment: - - User & Kernel mode - ---*/ - -#ifndef _PUBLIC_H -#define _PUBLIC_H - -#include - -#include "WudfOsrUsbPublic.h" - - -// -// Define the structures that will be used by the IOCTL -// interface to the driver -// - -// -// BAR_GRAPH_STATE -// -// BAR_GRAPH_STATE is a bit field structure with each -// bit corresponding to one of the bar graph on the -// OSRFX2 Development Board -// -#include - -#pragma warning( push ) -#pragma warning( disable : 4201 ) // nameless struct/union -#pragma warning( disable : 4214 ) // bit-field type other than int - -typedef struct _BAR_GRAPH_STATE { - - union { - - struct { - // - // Individual bars starting from the - // top of the stack of bars - // - // NOTE: There are actually 10 bars, - // but the very top two do not light - // and are not counted here - // - UCHAR Bar1 : 1; - UCHAR Bar2 : 1; - UCHAR Bar3 : 1; - UCHAR Bar4 : 1; - UCHAR Bar5 : 1; - UCHAR Bar6 : 1; - UCHAR Bar7 : 1; - UCHAR Bar8 : 1; - }; - - // - // The state of all the bar graph as a single - // UCHAR - // - UCHAR BarsAsUChar; - - }; - -}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; - -// -// SWITCH_STATE -// -// SWITCH_STATE is a bit field structure with each -// bit corresponding to one of the switches on the -// OSRFX2 Development Board -// -typedef struct _SWITCH_STATE { - - union { - struct { - // - // Individual switches starting from the - // left of the set of switches - // - UCHAR Switch1 : 1; - UCHAR Switch2 : 1; - UCHAR Switch3 : 1; - UCHAR Switch4 : 1; - UCHAR Switch5 : 1; - UCHAR Switch6 : 1; - UCHAR Switch7 : 1; - UCHAR Switch8 : 1; - }; - - // - // The state of all the switches as a single - // UCHAR - // - UCHAR SwitchesAsUChar; - - }; - - -}SWITCH_STATE, *PSWITCH_STATE; - -// -// Seven segment display bit values. -// - -// -// Undefine conflicting MFC constant -// -#undef SS_CENTER -#undef SS_LEFT -#undef SS_RIGHT - -#define SS_TOP 0x01 -#define SS_TOP_LEFT 0x40 -#define SS_TOP_RIGHT 0x02 -#define SS_CENTER 0x20 -#define SS_BOTTOM_LEFT 0x10 -#define SS_BOTTOM_RIGHT 0x04 -#define SS_BOTTOM 0x80 -#define SS_DOT 0x08 - -// -// FILE_PLAYBACK -// -// FILE_PLAYBACK structure contains the parameters for the PLAY_FILE I/O Control. -// - -typedef struct _FILE_PLAYBACK -{ - // - // The delay between changes in the display, in milliseconds. - // - - USHORT Delay; - - // - // The data file path. - // - - WCHAR Path[1]; -} FILE_PLAYBACK, *PFILE_PLAYBACK; - -#include - -#define IOCTL_INDEX 0x800 -#define FILE_DEVICE_OSRUSBFX2 65500U - -#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 1, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 3, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 4, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 5, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - - -#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 6, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 7, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 8, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 9, \ - METHOD_OUT_DIRECT, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_PLAY_FILE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 10, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#pragma warning(pop) - -#endif - diff --git a/usb/umdf_filter_kmdf/inc/usb_hw.h b/usb/umdf_filter_kmdf/inc/usb_hw.h deleted file mode 100644 index d6e983f1a..000000000 --- a/usb/umdf_filter_kmdf/inc/usb_hw.h +++ /dev/null @@ -1,233 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Usb.h - -Abstract: - - Contains prototypes for interfacing with a USB connected device. These - are copied from the KMDF WDFUSB.H header file (but with the WDF specific - portions removed) - -Environment: - - kernel mode only - ---*/ - -#pragma once - -typedef enum _WINUSB_BMREQUEST_DIRECTION { - BmRequestHostToDevice = BMREQUEST_HOST_TO_DEVICE, - BmRequestDeviceToHost = BMREQUEST_DEVICE_TO_HOST, -} WINUSB_BMREQUEST_DIRECTION; - -typedef enum _WINUSB_BMREQUEST_TYPE { - BmRequestStandard = BMREQUEST_STANDARD, - BmRequestClass = BMREQUEST_CLASS, - BmRequestVendor = BMREQUEST_VENDOR, -} WINUSB_BMREQUEST_TYPE; - -typedef enum _WINUSB_BMREQUEST_RECIPIENT { - BmRequestToDevice = BMREQUEST_TO_DEVICE, - BmRequestToInterface = BMREQUEST_TO_INTERFACE, - BmRequestToEndpoint = BMREQUEST_TO_ENDPOINT, - BmRequestToOther = BMREQUEST_TO_OTHER, -} WINUSB_BMREQUEST_RECIPIENT; - -typedef enum _WINUSB_DEVICE_TRAITS { - WINUSB_DEVICE_TRAIT_SELF_POWERED = 0x00000001, - WINUSB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE = 0x00000002, - WINUSB_DEVICE_TRAIT_AT_HIGH_SPEED = 0x00000004, -} WINUSB_DEVICE_TRAITS; - -typedef enum _WdfUsbTargetDeviceSelectInterfaceType { - WdfUsbTargetDeviceSelectInterfaceTypeInterface = 0x10, - WdfUsbTargetDeviceSelectInterfaceTypeUrb = 0x11, -} WdfUsbTargetDeviceSelectInterfaceType; - - - -typedef union _WINUSB_CONTROL_SETUP_PACKET { - struct { - union { - #pragma warning(disable:4214) // bit field types other than int - struct { - // - // Valid values are BMREQUEST_TO_DEVICE, BMREQUEST_TO_INTERFACE, - // BMREQUEST_TO_ENDPOINT, BMREQUEST_TO_OTHER - // - BYTE Recipient:2; - - BYTE Reserved:3; - - // - // Valid values are BMREQUEST_STANDARD, BMREQUEST_CLASS, - // BMREQUEST_VENDOR - // - BYTE Type:2; - - // - // Valid values are BMREQUEST_HOST_TO_DEVICE, - // BMREQUEST_DEVICE_TO_HOST - // - BYTE Dir:1; - } Request; - #pragma warning(default:4214) // bit field types other than int - BYTE Byte; - } bm; - - BYTE bRequest; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wValue; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wIndex; - - USHORT wLength; - } Packet; - - struct { - BYTE Bytes[8]; - } Generic; - - WINUSB_SETUP_PACKET WinUsb; - -} WINUSB_CONTROL_SETUP_PACKET, *PWINUSB_CONTROL_SETUP_PACKET; - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_CLASS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestClass; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_VENDOR( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestVendor; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_FEATURE( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT FeatureSelector, - USHORT Index, - BOOLEAN SetFeature - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestHostToDevice; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - if (SetFeature) { - Packet->Packet.bRequest = USB_REQUEST_SET_FEATURE; - } - else { - Packet->Packet.bRequest = USB_REQUEST_CLEAR_FEATURE; - } - - Packet->Packet.wValue.Value = FeatureSelector; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_GET_STATUS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestDeviceToHost; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - Packet->Packet.bRequest = USB_REQUEST_GET_STATUS; - Packet->Packet.wIndex.Value = Index; - Packet->Packet.wValue.Value = 0; - - // Packet->Packet.wLength will be set by the formatting function -} - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/Device.c b/usb/umdf_filter_kmdf/kmdf_driver/Device.c deleted file mode 100644 index 8516ef097..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/Device.c +++ /dev/null @@ -1,1051 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - Device.c - -Abstract: - - USB device driver for OSR USB-FX2 Learning Kit - -Environment: - - Kernel mode only - - ---*/ - -#include -#include - -#if defined(EVENT_TRACING) -#include "device.tmh" -#endif - -#ifdef ALLOC_PRAGMA -#pragma alloc_text(PAGE, OsrFxEvtDeviceAdd) -#pragma alloc_text(PAGE, OsrFxEvtDevicePrepareHardware) -#pragma alloc_text(PAGE, OsrFxEvtDeviceD0Exit) -#pragma alloc_text(PAGE, SelectInterfaces) -#pragma alloc_text(PAGE, OsrFxSetPowerPolicy) -#pragma alloc_text(PAGE, OsrFxReadFdoRegistryKeyValue) -#pragma alloc_text(PAGE, GetDeviceEventLoggingNames) -#pragma alloc_text(PAGE, OsrFxValidateConfigurationDescriptor) -#endif - - -NTSTATUS -OsrFxEvtDeviceAdd( - WDFDRIVER Driver, - PWDFDEVICE_INIT DeviceInit - ) -/*++ -Routine Description: - - EvtDeviceAdd is called by the framework in response to AddDevice - call from the PnP manager. We create and initialize a device object to - represent a new instance of the device. All the software resources - should be allocated in this callback. - -Arguments: - - Driver - Handle to a framework driver object created in DriverEntry - - DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. - -Return Value: - - NTSTATUS - ---*/ -{ - WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; - WDF_OBJECT_ATTRIBUTES attributes; - NTSTATUS status; - WDFDEVICE device; - WDF_DEVICE_PNP_CAPABILITIES pnpCaps; - WDF_IO_QUEUE_CONFIG ioQueueConfig; - PDEVICE_CONTEXT pDevContext; - WDFQUEUE queue; - GUID activity; - UNICODE_STRING symbolicLinkName; - WDFSTRING symbolicLinkString; - DEVPROP_BOOLEAN isRestricted; - - UNREFERENCED_PARAMETER(Driver); - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"--> OsrFxEvtDeviceAdd routine\n"); - - // - // Initialize the pnpPowerCallbacks structure. Callback events for PNP - // and Power are specified here. If you don't supply any callbacks, - // the Framework will take appropriate default actions based on whether - // DeviceInit is initialized to be an FDO, a PDO or a filter device - // object. - // - - WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); - // - // For usb devices, PrepareHardware callback is the to place select the - // interface and configure the device. - // - pnpPowerCallbacks.EvtDevicePrepareHardware = OsrFxEvtDevicePrepareHardware; - - // - // These two callbacks start and stop the wdfusb pipe continuous reader - // as we go in and out of the D0-working state. - // - - pnpPowerCallbacks.EvtDeviceD0Entry = OsrFxEvtDeviceD0Entry; - pnpPowerCallbacks.EvtDeviceD0Exit = OsrFxEvtDeviceD0Exit; - pnpPowerCallbacks.EvtDeviceSelfManagedIoFlush = OsrFxEvtDeviceSelfManagedIoFlush; - - WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks); - - WdfDeviceInitSetIoType(DeviceInit, WdfDeviceIoBuffered); - - // - // Now specify the size of device extension where we track per device - // context.DeviceInit is completely initialized. So call the framework - // to create the device and attach it to the lower stack. - // - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, DEVICE_CONTEXT); - - status = WdfDeviceCreate(&DeviceInit, &attributes, &device); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreate failed with Status code %!STATUS!\n", status); - return status; - } - - // - // Setup the activity ID so that we can log events using it. - // - - activity = DeviceToActivityId(device); - - // - // Get the DeviceObject context by using accessor function specified in - // the WDF_DECLARE_CONTEXT_TYPE_WITH_NAME macro for DEVICE_CONTEXT. - // - pDevContext = GetDeviceContext(device); - - // - // Get the device's friendly name and location so that we can use it in - // error logging. If this fails then it will setup dummy strings. - // - - GetDeviceEventLoggingNames(device); - - // - // Tell the framework to set the SurpriseRemovalOK in the DeviceCaps so - // that you don't get the popup in usermode when you surprise remove the device. - // - WDF_DEVICE_PNP_CAPABILITIES_INIT(&pnpCaps); - pnpCaps.SurpriseRemovalOK = WdfTrue; - - WdfDeviceSetPnpCapabilities(device, &pnpCaps); - - // - // Create a parallel default queue and register an event callback to - // receive ioctl requests. We will create separate queues for - // handling read and write requests. All other requests will be - // completed with error status automatically by the framework. - // - WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&ioQueueConfig, - WdfIoQueueDispatchParallel); - - ioQueueConfig.EvtIoDeviceControl = OsrFxEvtIoDeviceControl; - - // - // By default, Static Driver Verifier (SDV) displays a warning if it - // doesn't find the EvtIoStop callback on a power-managed queue. - // The 'assume' below causes SDV to suppress this warning. If the driver - // has not explicitly set PowerManaged to WdfFalse, the framework creates - // power-managed queues when the device is not a filter driver. Normally - // the EvtIoStop is required for power-managed queues, but for this driver - // it is not needed b/c the driver doesn't hold on to the requests for - // long time or forward them to other drivers. - // If the EvtIoStop callback is not implemented, the framework waits for - // all driver-owned requests to be done before moving in the Dx/sleep - // states or before removing the device, which is the correct behavior - // for this type of driver. If the requests were taking an indeterminate - // amount of time to complete, or if the driver forwarded the requests - // to a lower driver/another stack, the queue should have an - // EvtIoStop/EvtIoResume. - // - __analysis_assume(ioQueueConfig.EvtIoStop != 0); - status = WdfIoQueueCreate(device, - &ioQueueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &queue);// pointer to default queue - __analysis_assume(ioQueueConfig.EvtIoStop == 0); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed %!STATUS!\n", status); - goto Error; - } - - // - // We will create a separate sequential queue and configure it - // to receive read requests. We also need to register a EvtIoStop - // handler so that we can acknowledge requests that are pending - // at the target driver. - // - WDF_IO_QUEUE_CONFIG_INIT(&ioQueueConfig, WdfIoQueueDispatchSequential); - - ioQueueConfig.EvtIoRead = OsrFxEvtIoRead; - ioQueueConfig.EvtIoStop = OsrFxEvtIoStop; - - status = WdfIoQueueCreate( - device, - &ioQueueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &queue // queue handle - ); - - if (!NT_SUCCESS (status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed 0x%x\n", status); - goto Error; - } - - status = WdfDeviceConfigureRequestDispatching( - device, - queue, - WdfRequestTypeRead); - - if(!NT_SUCCESS (status)){ - NT_ASSERT(NT_SUCCESS(status)); - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceConfigureRequestDispatching failed 0x%x\n", status); - goto Error; - } - - - // - // We will create another sequential queue and configure it - // to receive write requests. - // - WDF_IO_QUEUE_CONFIG_INIT(&ioQueueConfig, WdfIoQueueDispatchSequential); - - ioQueueConfig.EvtIoWrite = OsrFxEvtIoWrite; - ioQueueConfig.EvtIoStop = OsrFxEvtIoStop; - - status = WdfIoQueueCreate( - device, - &ioQueueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &queue // queue handle - ); - - if (!NT_SUCCESS (status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed 0x%x\n", status); - goto Error; - } - - status = WdfDeviceConfigureRequestDispatching( - device, - queue, - WdfRequestTypeWrite); - - if(!NT_SUCCESS (status)){ - NT_ASSERT(NT_SUCCESS(status)); - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceConfigureRequestDispatching failed 0x%x\n", status); - goto Error; - } - - // - // Register a manual I/O queue for handling Interrupt Message Read Requests. - // This queue will be used for storing Requests that need to wait for an - // interrupt to occur before they can be completed. - // - WDF_IO_QUEUE_CONFIG_INIT(&ioQueueConfig, WdfIoQueueDispatchManual); - - // - // This queue is used for requests that dont directly access the device. The - // requests in this queue are serviced only when the device is in a fully - // powered state and sends an interrupt. So we can use a non-power managed - // queue to park the requests since we dont care whether the device is idle - // or fully powered up. - // - ioQueueConfig.PowerManaged = WdfFalse; - - status = WdfIoQueueCreate(device, - &ioQueueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &pDevContext->InterruptMsgQueue - ); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed 0x%x\n", status); - goto Error; - } - - // - // Register a device interface so that app can find our device and talk to it. - // - status = WdfDeviceCreateDeviceInterface(device, - (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, - NULL); // Reference String - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreateDeviceInterface failed %!STATUS!\n", status); - goto Error; - } - - // - // Create the lock that we use to serialize calls to ResetDevice(). As an - // alternative to using a WDFWAITLOCK to serialize the calls, a sequential - // WDFQUEUE can be created and reset IOCTLs would be forwarded to it. - // - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.ParentObject = device; - - status = WdfWaitLockCreate(&attributes, &pDevContext->ResetDeviceWaitLock); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfWaitLockCreate failed %!STATUS!\n", status); - goto Error; - } - - // - // Get the string for the device interface and set the restricted - // property on it to allow applications bound with device metadata - // to access the interface. - // - if (g_pIoSetDeviceInterfacePropertyData != NULL) { - - status = WdfStringCreate(NULL, - WDF_NO_OBJECT_ATTRIBUTES, - &symbolicLinkString); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfStringCreate failed %!STATUS!\n", status); - goto Error; - } - - status = WdfDeviceRetrieveDeviceInterfaceString(device, - (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, - NULL, - symbolicLinkString); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceRetrieveDeviceInterfaceString failed %!STATUS!\n", status); - goto Error; - } - - WdfStringGetUnicodeString(symbolicLinkString, &symbolicLinkName); - - isRestricted = DEVPROP_TRUE; - - status = g_pIoSetDeviceInterfacePropertyData(&symbolicLinkName, - &DEVPKEY_DeviceInterface_Restricted, - 0, - 0, - DEVPROP_TYPE_BOOLEAN, - sizeof(isRestricted), - &isRestricted ); - - WdfObjectDelete(symbolicLinkString); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "IoSetDeviceInterfacePropertyData failed %!STATUS!\n", status); - goto Error; - } - } - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- OsrFxEvtDeviceAdd\n"); - - return status; - -Error: - - // - // Log fail to add device to the event log - // - EventWriteFailAddDevice(&activity, - pDevContext->DeviceName, - pDevContext->Location, - status); - - return status; -} - -NTSTATUS -OsrFxEvtDevicePrepareHardware( - WDFDEVICE Device, - WDFCMRESLIST ResourceList, - WDFCMRESLIST ResourceListTranslated - ) -/*++ - -Routine Description: - - In this callback, the driver does whatever is necessary to make the - hardware ready to use. In the case of a USB device, this involves - reading and selecting descriptors. - -Arguments: - - Device - handle to a device - - ResourceList - handle to a resource-list object that identifies the - raw hardware resources that the PnP manager assigned - to the device - - ResourceListTranslated - handle to a resource-list object that - identifies the translated hardware resources - that the PnP manager assigned to the device - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - PDEVICE_CONTEXT pDeviceContext; - WDF_USB_DEVICE_INFORMATION deviceInfo; - ULONG waitWakeEnable; - - UNREFERENCED_PARAMETER(ResourceList); - UNREFERENCED_PARAMETER(ResourceListTranslated); - waitWakeEnable = FALSE; - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> EvtDevicePrepareHardware\n"); - - pDeviceContext = GetDeviceContext(Device); - - // - // Create a USB device handle so that we can communicate with the - // underlying USB stack. The WDFUSBDEVICE handle is used to query, - // configure, and manage all aspects of the USB device. - // These aspects include device properties, bus properties, - // and I/O creation and synchronization. We only create device the first - // the PrepareHardware is called. If the device is restarted by pnp manager - // for resource rebalance, we will use the same device handle but then select - // the interfaces again because the USB stack could reconfigure the device on - // restart. - // - if (pDeviceContext->UsbDevice == NULL) { - WDF_USB_DEVICE_CREATE_CONFIG config; - - WDF_USB_DEVICE_CREATE_CONFIG_INIT(&config, - USBD_CLIENT_CONTRACT_VERSION_602); - - status = WdfUsbTargetDeviceCreateWithParameters(Device, - &config, - WDF_NO_OBJECT_ATTRIBUTES, - &pDeviceContext->UsbDevice); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfUsbTargetDeviceCreateWithParameters failed with Status code %!STATUS!\n", status); - return status; - } - - // - // TODO: If you are fetching configuration descriptor from device for - // selecting a configuration or to parse other descriptors, call OsrFxValidateConfigurationDescriptor - // to do basic validation on the descriptors before you access them . - // - } - - // - // Retrieve USBD version information, port driver capabilites and device - // capabilites such as speed, power, etc. - // - WDF_USB_DEVICE_INFORMATION_INIT(&deviceInfo); - - status = WdfUsbTargetDeviceRetrieveInformation( - pDeviceContext->UsbDevice, - &deviceInfo); - if (NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "IsDeviceHighSpeed: %s\n", - (deviceInfo.Traits & WDF_USB_DEVICE_TRAIT_AT_HIGH_SPEED) ? "TRUE" : "FALSE"); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "IsDeviceSelfPowered: %s\n", - (deviceInfo.Traits & WDF_USB_DEVICE_TRAIT_SELF_POWERED) ? "TRUE" : "FALSE"); - - waitWakeEnable = deviceInfo.Traits & - WDF_USB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE; - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "IsDeviceRemoteWakeable: %s\n", - waitWakeEnable ? "TRUE" : "FALSE"); - // - // Save these for use later. - // - pDeviceContext->UsbDeviceTraits = deviceInfo.Traits; - } - else { - pDeviceContext->UsbDeviceTraits = 0; - } - - status = SelectInterfaces(Device); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "SelectInterfaces failed 0x%x\n", status); - return status; - } - - // - // Enable wait-wake and idle timeout if the device supports it - // - if (waitWakeEnable) { - status = OsrFxSetPowerPolicy(Device); - if (!NT_SUCCESS (status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "OsrFxSetPowerPolicy failed %!STATUS!\n", status); - return status; - } - } - - status = OsrFxConfigContReaderForInterruptEndPoint(pDeviceContext); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- EvtDevicePrepareHardware\n"); - - return status; -} - - -NTSTATUS -OsrFxEvtDeviceD0Entry( - WDFDEVICE Device, - WDF_POWER_DEVICE_STATE PreviousState - ) -/*++ - -Routine Description: - - EvtDeviceD0Entry event callback must perform any operations that are - necessary before the specified device is used. It will be called every - time the hardware needs to be (re-)initialized. - - This function is not marked pageable because this function is in the - device power up path. When a function is marked pagable and the code - section is paged out, it will generate a page fault which could impact - the fast resume behavior because the client driver will have to wait - until the system drivers can service this page fault. - - This function runs at PASSIVE_LEVEL, even though it is not paged. A - driver can optionally make this function pageable if DO_POWER_PAGABLE - is set. Even if DO_POWER_PAGABLE isn't set, this function still runs - at PASSIVE_LEVEL. In this case, though, the function absolutely must - not do anything that will cause a page fault. - -Arguments: - - Device - Handle to a framework device object. - - PreviousState - Device power state which the device was in most recently. - If the device is being newly started, this will be - PowerDeviceUnspecified. - -Return Value: - - NTSTATUS - ---*/ -{ - PDEVICE_CONTEXT pDeviceContext; - NTSTATUS status; - BOOLEAN isTargetStarted; - - pDeviceContext = GetDeviceContext(Device); - isTargetStarted = FALSE; - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, - "-->OsrFxEvtEvtDeviceD0Entry - coming from %s\n", - DbgDevicePowerString(PreviousState)); - - // - // Since continuous reader is configured for this interrupt-pipe, we must explicitly start - // the I/O target to get the framework to post read requests. - // - status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(pDeviceContext->InterruptPipe)); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_POWER, "Failed to start interrupt pipe %!STATUS!\n", status); - goto End; - } - - isTargetStarted = TRUE; - -End: - - if (!NT_SUCCESS(status)) { - // - // Failure in D0Entry will lead to device being removed. So let us stop the continuous - // reader in preparation for the ensuing remove. - // - if (isTargetStarted) { - WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(pDeviceContext->InterruptPipe), WdfIoTargetCancelSentIo); - } - } - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, "<--OsrFxEvtEvtDeviceD0Entry\n"); - - return status; -} - - -NTSTATUS -OsrFxEvtDeviceD0Exit( - WDFDEVICE Device, - WDF_POWER_DEVICE_STATE TargetState - ) -/*++ - -Routine Description: - - This routine undoes anything done in EvtDeviceD0Entry. It is called - whenever the device leaves the D0 state, which happens when the device is - stopped, when it is removed, and when it is powered off. - - The device is still in D0 when this callback is invoked, which means that - the driver can still touch hardware in this routine. - - - EvtDeviceD0Exit event callback must perform any operations that are - necessary before the specified device is moved out of the D0 state. If the - driver needs to save hardware state before the device is powered down, then - that should be done here. - - This function runs at PASSIVE_LEVEL, though it is generally not paged. A - driver can optionally make this function pageable if DO_POWER_PAGABLE is set. - - Even if DO_POWER_PAGABLE isn't set, this function still runs at - PASSIVE_LEVEL. In this case, though, the function absolutely must not do - anything that will cause a page fault. - -Arguments: - - Device - Handle to a framework device object. - - TargetState - Device power state which the device will be put in once this - callback is complete. - -Return Value: - - Success implies that the device can be used. Failure will result in the - device stack being torn down. - ---*/ -{ - PDEVICE_CONTEXT pDeviceContext; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, - "-->OsrFxEvtDeviceD0Exit - moving to %s\n", - DbgDevicePowerString(TargetState)); - - pDeviceContext = GetDeviceContext(Device); - - WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(pDeviceContext->InterruptPipe), WdfIoTargetCancelSentIo); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, "<--OsrFxEvtDeviceD0Exit\n"); - - return STATUS_SUCCESS; -} - -VOID -OsrFxEvtDeviceSelfManagedIoFlush( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine handles flush activity for the device's - self-managed I/O operations. - -Arguments: - - Device - Handle to a framework device object. - -Return Value: - - None - ---*/ -{ - // Service the interrupt message queue to drain any outstanding - // requests - OsrUsbIoctlGetInterruptMessage(Device, STATUS_DEVICE_REMOVED); -} - -_IRQL_requires_(PASSIVE_LEVEL) -USBD_STATUS -OsrFxValidateConfigurationDescriptor( - _In_reads_bytes_(BufferLength) PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc, - _In_ ULONG BufferLength, - _Inout_ PUCHAR *Offset - ) -/*++ - -Routine Description: - - Validates a USB Configuration Descriptor - -Parameters: - - ConfigDesc: Pointer to the entire USB Configuration descriptor returned by the device - - BufferLength: Known size of buffer pointed to by ConfigDesc (Not wTotalLength) - - Offset: if the USBD_STATUS returned is not USBD_STATUS_SUCCESS, offet will - be set to the address within the ConfigDesc buffer where the failure occured. - -Return Value: - - USBD_STATUS - Success implies the configuration descriptor is valid. - ---*/ -{ - - - USBD_STATUS status = USBD_STATUS_SUCCESS; - USHORT ValidationLevel = 3; - - PAGED_CODE(); - - // - // Call USBD_ValidateConfigurationDescriptor to validate the descriptors which are present in this supplied configuration descriptor. - // USBD_ValidateConfigurationDescriptor validates that all descriptors are completely contained within the configuration descriptor buffer. - // It also checks for interface numbers, number of endpoints in an interface etc. - // Please refer to msdn documentation for this function for more information. - // - - status = USBD_ValidateConfigurationDescriptor( ConfigDesc, BufferLength , ValidationLevel , Offset , POOL_TAG ); - if (!(NT_SUCCESS (status)) ){ - return status; - } - - // - // TODO: You should validate the correctness of other descriptors which are not taken care by USBD_ValidateConfigurationDescriptor - // Check that all such descriptors have size >= sizeof(the descriptor they point to) - // Check for any association between them if required - // - - return status; -} - - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -OsrFxSetPowerPolicy( - _In_ WDFDEVICE Device - ) -{ - WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; - WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS wakeSettings; - NTSTATUS status = STATUS_SUCCESS; - - PAGED_CODE(); - - // - // Init the idle policy structure. - // - WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleUsbSelectiveSuspend); - idleSettings.IdleTimeout = 10000; // 10-sec - - status = WdfDeviceAssignS0IdleSettings(Device, &idleSettings); - if ( !NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceSetPowerPolicyS0IdlePolicy failed %x\n", status); - return status; - } - - // - // Init wait-wake policy structure. - // - WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings); - - status = WdfDeviceAssignSxWakeSettings(Device, &wakeSettings); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceAssignSxWakeSettings failed %x\n", status); - return status; - } - - return status; -} - - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SelectInterfaces( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This helper routine selects the configuration, interface and - creates a context for every pipe (end point) in that interface. - -Arguments: - - Device - Handle to a framework device - -Return Value: - - NT status value - ---*/ -{ - WDF_USB_DEVICE_SELECT_CONFIG_PARAMS configParams; - NTSTATUS status = STATUS_SUCCESS; - PDEVICE_CONTEXT pDeviceContext; - WDFUSBPIPE pipe; - WDF_USB_PIPE_INFORMATION pipeInfo; - UCHAR index; - UCHAR numberConfiguredPipes; - - PAGED_CODE(); - - pDeviceContext = GetDeviceContext(Device); - - WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_SINGLE_INTERFACE( &configParams); - - status = WdfUsbTargetDeviceSelectConfig(pDeviceContext->UsbDevice, - WDF_NO_OBJECT_ATTRIBUTES, - &configParams); - if(!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfUsbTargetDeviceSelectConfig failed %!STATUS! \n", - status); - - // - // Since the Osr USB fx2 device is capable of working at high speed, the only reason - // the device would not be working at high speed is if the port doesn't - // support it. If the port doesn't support high speed it is a 1.1 port - // - if ((pDeviceContext->UsbDeviceTraits & WDF_USB_DEVICE_TRAIT_AT_HIGH_SPEED) == 0) { - GUID activity = DeviceToActivityId(Device); - - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - " On a 1.1 USB port on Windows Vista" - " this is expected as the OSR USB Fx2 board's Interrupt EndPoint descriptor" - " doesn't conform to the USB specification. Windows Vista detects this and" - " returns an error. \n" - ); - EventWriteSelectConfigFailure( - &activity, - pDeviceContext->DeviceName, - pDeviceContext->Location, - status - ); - } - - return status; - } - - pDeviceContext->UsbInterface = - configParams.Types.SingleInterface.ConfiguredUsbInterface; - - numberConfiguredPipes = configParams.Types.SingleInterface.NumberConfiguredPipes; - - // - // Get pipe handles - // - for(index=0; index < numberConfiguredPipes; index++) { - - WDF_USB_PIPE_INFORMATION_INIT(&pipeInfo); - - pipe = WdfUsbInterfaceGetConfiguredPipe( - pDeviceContext->UsbInterface, - index, //PipeIndex, - &pipeInfo - ); - // - // Tell the framework that it's okay to read less than - // MaximumPacketSize - // - WdfUsbTargetPipeSetNoMaximumPacketSizeCheck(pipe); - - if(WdfUsbPipeTypeInterrupt == pipeInfo.PipeType) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, - "Interrupt Pipe is 0x%p\n", pipe); - pDeviceContext->InterruptPipe = pipe; - } - - if(WdfUsbPipeTypeBulk == pipeInfo.PipeType && - WdfUsbTargetPipeIsInEndpoint(pipe)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, - "BulkInput Pipe is 0x%p\n", pipe); - pDeviceContext->BulkReadPipe = pipe; - } - - if(WdfUsbPipeTypeBulk == pipeInfo.PipeType && - WdfUsbTargetPipeIsOutEndpoint(pipe)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, - "BulkOutput Pipe is 0x%p\n", pipe); - pDeviceContext->BulkWritePipe = pipe; - } - - } - - // - // If we didn't find all the 3 pipes, fail the start. - // - if(!(pDeviceContext->BulkWritePipe - && pDeviceContext->BulkReadPipe && pDeviceContext->InterruptPipe)) { - status = STATUS_INVALID_DEVICE_STATE; - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "Device is not configured properly %!STATUS!\n", - status); - - return status; - } - - return status; -} - -_IRQL_requires_(PASSIVE_LEVEL) -VOID -GetDeviceEventLoggingNames( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - Retrieve the friendly name and the location string into WDFMEMORY objects - and store them in the device context. - -Arguments: - -Return Value: - - None - ---*/ -{ - PDEVICE_CONTEXT pDevContext = GetDeviceContext(Device); - - WDF_OBJECT_ATTRIBUTES objectAttributes; - - WDFMEMORY deviceNameMemory = NULL; - WDFMEMORY locationMemory = NULL; - - NTSTATUS status; - - PAGED_CODE(); - - // - // We want both memory objects to be children of the device so they will - // be deleted automatically when the device is removed. - // - - WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes); - objectAttributes.ParentObject = Device; - - // - // First get the length of the string. If the FriendlyName - // is not there then get the lenght of device description. - // - - status = WdfDeviceAllocAndQueryProperty(Device, - DevicePropertyFriendlyName, - NonPagedPoolNx, - &objectAttributes, - &deviceNameMemory); - - if (!NT_SUCCESS(status)) - { - status = WdfDeviceAllocAndQueryProperty(Device, - DevicePropertyDeviceDescription, - NonPagedPoolNx, - &objectAttributes, - &deviceNameMemory); - } - - if (NT_SUCCESS(status)) - { - pDevContext->DeviceNameMemory = deviceNameMemory; - pDevContext->DeviceName = WdfMemoryGetBuffer(deviceNameMemory, NULL); - } - else - { - pDevContext->DeviceNameMemory = NULL; - pDevContext->DeviceName = L"(error retrieving name)"; - } - - // - // Retrieve the device location string. - // - - status = WdfDeviceAllocAndQueryProperty(Device, - DevicePropertyLocationInformation, - NonPagedPoolNx, - WDF_NO_OBJECT_ATTRIBUTES, - &locationMemory); - - if (NT_SUCCESS(status)) - { - pDevContext->LocationMemory = locationMemory; - pDevContext->Location = WdfMemoryGetBuffer(locationMemory, NULL); - } - else - { - pDevContext->LocationMemory = NULL; - pDevContext->Location = L"(error retrieving location)"; - } - - return; -} - -_IRQL_requires_(PASSIVE_LEVEL) -PCHAR -DbgDevicePowerString( - _In_ WDF_POWER_DEVICE_STATE Type - ) -{ - switch (Type) - { - case WdfPowerDeviceInvalid: - return "WdfPowerDeviceInvalid"; - case WdfPowerDeviceD0: - return "WdfPowerDeviceD0"; - case WdfPowerDeviceD1: - return "WdfPowerDeviceD1"; - case WdfPowerDeviceD2: - return "WdfPowerDeviceD2"; - case WdfPowerDeviceD3: - return "WdfPowerDeviceD3"; - case WdfPowerDeviceD3Final: - return "WdfPowerDeviceD3Final"; - case WdfPowerDevicePrepareForHibernation: - return "WdfPowerDevicePrepareForHibernation"; - case WdfPowerDeviceMaximum: - return "WdfPowerDeviceMaximum"; - default: - return "UnKnown Device Power State"; - } -} - - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c b/usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c deleted file mode 100644 index eabda1925..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c +++ /dev/null @@ -1,436 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - bulkrwr.c - -Abstract: - - This file has routines to perform reads and writes. - The read and writes are targeted bulk to endpoints. - -Environment: - - Kernel mode - ---*/ - -#include - - -#if defined(EVENT_TRACING) -#include "bulkrwr.tmh" -#endif - -#pragma warning(disable:4267) - -VOID -OsrFxEvtIoRead( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t Length - ) -/*++ - -Routine Description: - - Called by the framework when it receives Read or Write requests. - -Arguments: - - Queue - Default queue handle - Request - Handle to the read/write request - Lenght - Length of the data buffer associated with the request. - The default property of the queue is to not dispatch - zero lenght read & write requests to the driver and - complete is with status success. So we will never get - a zero length request. - -Return Value: - - ---*/ -{ - WDFUSBPIPE pipe; - NTSTATUS status; - WDFMEMORY reqMemory; - PDEVICE_CONTEXT pDeviceContext; - GUID activity = RequestToActivityId(Request); - - UNREFERENCED_PARAMETER(Queue); - - // - // Log read start event, using IRP activity ID if available or request - // handle otherwise. - // - - EventWriteReadStart(&activity, WdfIoQueueGetDevice(Queue), (ULONG)Length); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "-->OsrFxEvtIoRead\n"); - - // - // First validate input parameters. - // - if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Transfer exceeds %d\n", - TEST_BOARD_TRANSFER_BUFFER_SIZE); - status = STATUS_INVALID_PARAMETER; - goto Exit; - } - - pDeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); - - pipe = pDeviceContext->BulkReadPipe; - - status = WdfRequestRetrieveOutputMemory(Request, &reqMemory); - if(!NT_SUCCESS(status)){ - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, - "WdfRequestRetrieveOutputMemory failed %!STATUS!\n", status); - goto Exit; - } - - // - // The format call validates to make sure that you are reading or - // writing to the right pipe type, sets the appropriate transfer flags, - // creates an URB and initializes the request. - // - status = WdfUsbTargetPipeFormatRequestForRead(pipe, - Request, - reqMemory, - NULL // Offsets - ); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, - "WdfUsbTargetPipeFormatRequestForRead failed 0x%x\n", status); - goto Exit; - } - - WdfRequestSetCompletionRoutine( - Request, - EvtRequestReadCompletionRoutine, - pipe); - // - // Send the request asynchronously. - // - if (WdfRequestSend(Request, WdfUsbTargetPipeGetIoTarget(pipe), WDF_NO_SEND_OPTIONS) == FALSE) { - // - // Framework couldn't send the request for some reason. - // - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestSend failed\n"); - status = WdfRequestGetStatus(Request); - goto Exit; - } - - -Exit: - if (!NT_SUCCESS(status)) { - // - // log event read failed - // - EventWriteReadFail(&activity, WdfIoQueueGetDevice(Queue), status); - WdfRequestCompleteWithInformation(Request, status, 0); - } - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "<-- OsrFxEvtIoRead\n"); - - return; -} - -VOID -EvtRequestReadCompletionRoutine( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This is the completion routine for reads - If the irp completes with success, we check if we - need to recirculate this irp for another stage of - transfer. - -Arguments: - - Context - Driver supplied context - Device - Device handle - Request - Request handle - Params - request completion params - -Return Value: - None - ---*/ -{ - NTSTATUS status; - size_t bytesRead = 0; - GUID activity = RequestToActivityId(Request); - PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams; - - UNREFERENCED_PARAMETER(Target); - UNREFERENCED_PARAMETER(Context); - - status = CompletionParams->IoStatus.Status; - - usbCompletionParams = CompletionParams->Parameters.Usb.Completion; - - bytesRead = usbCompletionParams->Parameters.PipeRead.Length; - - if (NT_SUCCESS(status)){ - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, - "Number of bytes read: %I64d\n", (INT64)bytesRead); - } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, - "Read failed - request status 0x%x UsbdStatus 0x%x\n", - status, usbCompletionParams->UsbdStatus); - - } - - // - // Log read stop event, using IRP activity ID if available or request - // handle otherwise. - // - - EventWriteReadStop(&activity, - WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), - bytesRead, - status, - usbCompletionParams->UsbdStatus); - - WdfRequestCompleteWithInformation(Request, status, bytesRead); - - return; -} - -VOID -OsrFxEvtIoWrite( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t Length - ) -/*++ - -Routine Description: - - Called by the framework when it receives Read or Write requests. - -Arguments: - - Queue - Default queue handle - Request - Handle to the read/write request - Lenght - Length of the data buffer associated with the request. - The default property of the queue is to not dispatch - zero lenght read & write requests to the driver and - complete is with status success. So we will never get - a zero length request. - -Return Value: - - ---*/ -{ - NTSTATUS status; - WDFUSBPIPE pipe; - WDFMEMORY reqMemory; - PDEVICE_CONTEXT pDeviceContext; - GUID activity = RequestToActivityId(Request); - - UNREFERENCED_PARAMETER(Queue); - - - // - // Log write start event, using IRP activity ID if available or request - // handle otherwise. - // - EventWriteWriteStart(&activity, WdfIoQueueGetDevice(Queue), (ULONG)Length); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "-->OsrFxEvtIoWrite\n"); - - // - // First validate input parameters. - // - if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Transfer exceeds %d\n", - TEST_BOARD_TRANSFER_BUFFER_SIZE); - status = STATUS_INVALID_PARAMETER; - goto Exit; - } - - pDeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); - - pipe = pDeviceContext->BulkWritePipe; - - status = WdfRequestRetrieveInputMemory(Request, &reqMemory); - if(!NT_SUCCESS(status)){ - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestRetrieveInputBuffer failed\n"); - goto Exit; - } - - status = WdfUsbTargetPipeFormatRequestForWrite(pipe, - Request, - reqMemory, - NULL); // Offset - - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "WdfUsbTargetPipeFormatRequestForWrite failed 0x%x\n", status); - goto Exit; - } - - WdfRequestSetCompletionRoutine( - Request, - EvtRequestWriteCompletionRoutine, - pipe); - - // - // Send the request asynchronously. - // - if (WdfRequestSend(Request, WdfUsbTargetPipeGetIoTarget(pipe), WDF_NO_SEND_OPTIONS) == FALSE) { - // - // Framework couldn't send the request for some reason. - // - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestSend failed\n"); - status = WdfRequestGetStatus(Request); - goto Exit; - } - -Exit: - - if (!NT_SUCCESS(status)) { - // - // log event write failed - // - EventWriteWriteFail(&activity, WdfIoQueueGetDevice(Queue), status); - - WdfRequestCompleteWithInformation(Request, status, 0); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "<-- OsrFxEvtIoWrite\n"); - - return; -} - -VOID -EvtRequestWriteCompletionRoutine( - _In_ WDFREQUEST Request, - _In_ WDFIOTARGET Target, - _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, - _In_ WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This is the completion routine for writes - If the irp completes with success, we check if we - need to recirculate this irp for another stage of - transfer. - -Arguments: - - Context - Driver supplied context - Device - Device handle - Request - Request handle - Params - request completion params - -Return Value: - None - ---*/ -{ - NTSTATUS status; - size_t bytesWritten = 0; - GUID activity = RequestToActivityId(Request); - PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams; - - UNREFERENCED_PARAMETER(Target); - UNREFERENCED_PARAMETER(Context); - - status = CompletionParams->IoStatus.Status; - - // - // For usb devices, we should look at the Usb.Completion param. - // - usbCompletionParams = CompletionParams->Parameters.Usb.Completion; - - bytesWritten = usbCompletionParams->Parameters.PipeWrite.Length; - - if (NT_SUCCESS(status)){ - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, - "Number of bytes written: %I64d\n", (INT64)bytesWritten); - } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "Write failed: request Status 0x%x UsbdStatus 0x%x\n", - status, usbCompletionParams->UsbdStatus); - } - - // - // Log write stop event, using IRP activtiy ID if available or request - // handle otherwise - // - EventWriteWriteStop(&activity, - WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), - bytesWritten, - status, - usbCompletionParams->UsbdStatus); - - - WdfRequestCompleteWithInformation(Request, status, bytesWritten); - - return; -} - - -VOID -OsrFxEvtIoStop( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ ULONG ActionFlags - ) -/*++ - -Routine Description: - - This callback is invoked on every inflight request when the device - is suspended or removed. Since our inflight read and write requests - are actually pending in the target device, we will just acknowledge - its presence. Until we acknowledge, complete, or requeue the requests - framework will wait before allowing the device suspend or remove to - proceeed. When the underlying USB stack gets the request to suspend or - remove, it will fail all the pending requests. - -Arguments: - - Queue - handle to queue object that is associated with the I/O request - - Request - handle to a request object - - ActionFlags - bitwise OR of one or more WDF_REQUEST_STOP_ACTION_FLAGS flags - -Return Value: - None - ---*/ -{ - UNREFERENCED_PARAMETER(Queue); - UNREFERENCED_PARAMETER(ActionFlags); - - if (ActionFlags & WdfRequestStopActionSuspend ) { - WdfRequestStopAcknowledge(Request, FALSE); // Don't requeue - } else if(ActionFlags & WdfRequestStopActionPurge) { - WdfRequestCancelSentRequest(Request); - } - return; -} - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/driver.c b/usb/umdf_filter_kmdf/kmdf_driver/driver.c deleted file mode 100644 index 25be851e5..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/driver.c +++ /dev/null @@ -1,301 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - Driver.c - -Abstract: - - Main module. - - This driver is for Open System Resources USB-FX2 Learning Kit designed - and built by OSR specifically for use in teaching software developers how to write - drivers for USB devices. - - The board supports a single configuration. The board automatically - detects the speed of the host controller, and supplies either the - high or full speed configuration based on the host controller's speed. - - The firmware supports 3 endpoints: - - Endpoint number 1 is used to indicate the state of the 8-switch - switch-pack on the OSR USB-FX2 board. A single byte representing - the switch state is sent (a) when the board is first started, - (b) when the board resumes after selective-suspend, - (c) whenever the state of the switches is changed. - - Endpoints 6 and 8 perform an internal loop-back function. - Data that is sent to the board at EP6 is returned to the host on EP8. - - For further information on the endpoints, please refer to the spec - http://www.osronline.com/hardware/OSRFX2_32.pdf. - - Vendor ID of the device is 0x4705 and Product ID is 0x210. - -Environment: - - Kernel mode only - ---*/ - -#include - -#if defined(EVENT_TRACING) -// -// The trace message header (.tmh) file must be included in a source file -// before any WPP macro calls and after defining a WPP_CONTROL_GUIDS -// macro (defined in trace.h). During the compilation, WPP scans the source -// files for DoTraceMessage() calls and builds a .tmh file which stores a unique -// data GUID for each message, the text resource string for each message, -// and the data types of the variables passed in for each message. This file -// is automatically generated and used during post-processing. -// -#include "driver.tmh" -#else -ULONG DebugLevel = TRACE_LEVEL_INFORMATION; -ULONG DebugFlag = 0xff; -#endif - -PFN_IO_GET_ACTIVITY_ID_IRP g_pIoGetActivityIdIrp; -PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA g_pIoSetDeviceInterfacePropertyData; - -#ifdef ALLOC_PRAGMA -#pragma alloc_text(INIT, DriverEntry) -#pragma alloc_text(PAGE, OsrFxEvtDriverContextCleanup) -#endif - -NTSTATUS -DriverEntry( - PDRIVER_OBJECT DriverObject, - PUNICODE_STRING RegistryPath - ) -/*++ - -Routine Description: - DriverEntry initializes the driver and is the first routine called by the - system after the driver is loaded. - -Parameters Description: - - DriverObject - represents the instance of the function driver that is loaded - into memory. DriverEntry must initialize members of DriverObject before it - returns to the caller. DriverObject is allocated by the system before the - driver is loaded, and it is released by the system after the system unloads - the function driver from memory. - - RegistryPath - represents the driver specific path in the Registry. - The function driver can use the path to store driver related data between - reboots. The path does not store hardware instance specific data. - -Return Value: - - STATUS_SUCCESS if successful, - STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. - ---*/ -{ - WDF_DRIVER_CONFIG config; - NTSTATUS status; - WDF_OBJECT_ATTRIBUTES attributes; - UNICODE_STRING funcName; - - // - // Initialize WPP Tracing - // - WPP_INIT_TRACING( DriverObject, RegistryPath ); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, - "OSRUSBFX2 Driver Sample - Driver Framework Edition.\n"); - - // - // IRP activity ID functions are available on some versions, save them into - // globals (or NULL if not available) - // - RtlInitUnicodeString(&funcName, L"IoGetActivityIdIrp"); - g_pIoGetActivityIdIrp = (PFN_IO_GET_ACTIVITY_ID_IRP) (ULONG_PTR) - MmGetSystemRoutineAddress(&funcName); - - // - // The Device interface property set is available on some version, save it - // into globals (or NULL if not available) - // - RtlInitUnicodeString(&funcName, L"IoSetDeviceInterfacePropertyData"); - g_pIoSetDeviceInterfacePropertyData = (PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA) (ULONG_PTR) - MmGetSystemRoutineAddress(&funcName); - - // - // Register with ETW (unified tracing) - // - EventRegisterOSRUSBFX2(); - - // - // Initialize driver config to control the attributes that - // are global to the driver. Note that framework by default - // provides a driver unload routine. If you create any resources - // in the DriverEntry and want to be cleaned in driver unload, - // you can override that by manually setting the EvtDriverUnload in the - // config structure. In general xxx_CONFIG_INIT macros are provided to - // initialize most commonly used members. - // - - WDF_DRIVER_CONFIG_INIT( - &config, - OsrFxEvtDeviceAdd - ); - - // - // Register a cleanup callback so that we can call WPP_CLEANUP when - // the framework driver object is deleted during driver unload. - // - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.EvtCleanupCallback = OsrFxEvtDriverContextCleanup; - - // - // Create a framework driver object to represent our driver. - // - status = WdfDriverCreate( - DriverObject, - RegistryPath, - &attributes, // Driver Object Attributes - &config, // Driver Config Info - WDF_NO_HANDLE // hDriver - ); - - if (!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, - "WdfDriverCreate failed with status 0x%x\n", status); - // - // Cleanup tracing here because DriverContextCleanup will not be called - // as we have failed to create WDFDRIVER object itself. - // Please note that if your return failure from DriverEntry after the - // WDFDRIVER object is created successfully, you don't have to - // call WPP cleanup because in those cases DriverContextCleanup - // will be executed when the framework deletes the DriverObject. - // - WPP_CLEANUP(DriverObject); - EventUnregisterOSRUSBFX2(); - } - - return status; -} - -VOID -OsrFxEvtDriverContextCleanup( - WDFOBJECT Driver - ) -/*++ -Routine Description: - - Free resources allocated in DriverEntry that are not automatically - cleaned up by the framework. - -Arguments: - - Driver - handle to a WDF Driver object. - -Return Value: - - VOID. - ---*/ -{ - // - // EvtCleanupCallback for WDFDRIVER is always called at PASSIVE_LEVEL - // - _IRQL_limited_to_(PASSIVE_LEVEL); - - PAGED_CODE (); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, - "--> OsrFxEvtDriverContextCleanup\n"); - - WPP_CLEANUP( WdfDriverWdmGetDriverObject( (WDFDRIVER)Driver )); - - UNREFERENCED_PARAMETER(Driver); // For the case when WPP is not being used. - - EventUnregisterOSRUSBFX2(); -} - -#if !defined(EVENT_TRACING) - -VOID -TraceEvents ( - _In_ ULONG DebugPrintLevel, - _In_ ULONG DebugPrintFlag, - _Printf_format_string_ - _In_ PCSTR DebugMessage, - ... - ) - -/*++ - -Routine Description: - - Debug print for the sample driver. - -Arguments: - - DebugPrintLevel - print level between 0 and 3, with 3 the most verbose - DebugPrintFlag - message mask - DebugMessage - format string of the message to print - ... - values used by the format string - -Return Value: - - None. - - --*/ - { -#if DBG -#define TEMP_BUFFER_SIZE 1024 - va_list list; - CHAR debugMessageBuffer[TEMP_BUFFER_SIZE]; - NTSTATUS status; - - va_start(list, DebugMessage); - - if (DebugMessage) { - - // - // Using new safe string functions instead of _vsnprintf. - // This function takes care of NULL terminating if the message - // is longer than the buffer. - // - status = RtlStringCbVPrintfA( debugMessageBuffer, - sizeof(debugMessageBuffer), - DebugMessage, - list ); - if(!NT_SUCCESS(status)) { - - DbgPrint (_DRIVER_NAME_": RtlStringCbVPrintfA failed 0x%x\n", status); - return; - } - if (DebugPrintLevel <= TRACE_LEVEL_ERROR || - (DebugPrintLevel <= DebugLevel && - ((DebugPrintFlag & DebugFlag) == DebugPrintFlag))) { - DbgPrint("%s %s", _DRIVER_NAME_, debugMessageBuffer); - } - } - va_end(list); - - return; -#else - UNREFERENCED_PARAMETER(DebugPrintLevel); - UNREFERENCED_PARAMETER(DebugPrintFlag); - UNREFERENCED_PARAMETER(DebugMessage); -#endif -} - -#endif - - - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/interrupt.c b/usb/umdf_filter_kmdf/kmdf_driver/interrupt.c deleted file mode 100644 index 00ea35505..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/interrupt.c +++ /dev/null @@ -1,184 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - Interrupt.c - -Abstract: - - This modules has routines configure a continuous reader on an - interrupt pipe to asynchronously read toggle switch states. - -Environment: - - Kernel mode - ---*/ - -#include - -#if defined(EVENT_TRACING) -#include "interrupt.tmh" -#endif - - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -OsrFxConfigContReaderForInterruptEndPoint( - _In_ PDEVICE_CONTEXT DeviceContext - ) -/*++ - -Routine Description: - - This routine configures a continuous reader on the - interrupt endpoint. It's called from the PrepareHarware event. - -Arguments: - - -Return Value: - - NT status value - ---*/ -{ - WDF_USB_CONTINUOUS_READER_CONFIG contReaderConfig; - NTSTATUS status; - - WDF_USB_CONTINUOUS_READER_CONFIG_INIT(&contReaderConfig, - OsrFxEvtUsbInterruptPipeReadComplete, - DeviceContext, // Context - sizeof(UCHAR)); // TransferLength - - contReaderConfig.EvtUsbTargetPipeReadersFailed = OsrFxEvtUsbInterruptReadersFailed; - - // - // Reader requests are not posted to the target automatically. - // Driver must explictly call WdfIoTargetStart to kick start the - // reader. In this sample, it's done in D0Entry. - // By defaut, framework queues two requests to the target - // endpoint. Driver can configure up to 10 requests with CONFIG macro. - // - status = WdfUsbTargetPipeConfigContinuousReader(DeviceContext->InterruptPipe, - &contReaderConfig); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "OsrFxConfigContReaderForInterruptEndPoint failed %x\n", - status); - return status; - } - - return status; -} - -VOID -OsrFxEvtUsbInterruptPipeReadComplete( - WDFUSBPIPE Pipe, - WDFMEMORY Buffer, - size_t NumBytesTransferred, - WDFCONTEXT Context - ) -/*++ - -Routine Description: - - This the completion routine of the continour reader. This can - called concurrently on multiprocessor system if there are - more than one readers configured. So make sure to protect - access to global resources. - -Arguments: - - Buffer - This buffer is freed when this call returns. - If the driver wants to delay processing of the buffer, it - can take an additional referrence. - - Context - Provided in the WDF_USB_CONTINUOUS_READER_CONFIG_INIT macro - -Return Value: - - NT status value - ---*/ -{ - PUCHAR switchState = NULL; - WDFDEVICE device; - PDEVICE_CONTEXT pDeviceContext = Context; - - UNREFERENCED_PARAMETER(Pipe); - - device = WdfObjectContextGetObject(pDeviceContext); - - // - // Make sure that there is data in the read packet. Depending on the device - // specification, it is possible for it to return a 0 length read in - // certain conditions. - // - - if (NumBytesTransferred == 0) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_INIT, - "OsrFxEvtUsbInterruptPipeReadComplete Zero length read " - "occured on the Interrupt Pipe's Continuous Reader\n" - ); - return; - } - - - NT_ASSERT(NumBytesTransferred == sizeof(UCHAR)); - - switchState = WdfMemoryGetBuffer(Buffer, NULL); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, - "OsrFxEvtUsbInterruptPipeReadComplete SwitchState %x\n", - *switchState); - - pDeviceContext->CurrentSwitchState = *switchState; - - // - // Handle any pending Interrupt Message IOCTLs. Note that the OSR USB device - // will generate an interrupt message when the the device resumes from a low - // power state. So if the Interrupt Message IOCTL was sent after the device - // has gone to a low power state, the pending Interrupt Message IOCTL will - // get completed in the function call below, before the user twiddles the - // dip switches on the OSR USB device. If this is not the desired behavior - // for your driver, then you could handle this condition by maintaining a - // state variable on D0Entry to track interrupt messages caused by power up. - // - OsrUsbIoctlGetInterruptMessage(device, STATUS_SUCCESS); - -} - -BOOLEAN -OsrFxEvtUsbInterruptReadersFailed( - _In_ WDFUSBPIPE Pipe, - _In_ NTSTATUS Status, - _In_ USBD_STATUS UsbdStatus - ) -{ - WDFDEVICE device = WdfIoTargetGetDevice(WdfUsbTargetPipeGetIoTarget(Pipe)); - PDEVICE_CONTEXT pDeviceContext = GetDeviceContext(device); - - UNREFERENCED_PARAMETER(UsbdStatus); - - // - // Clear the current switch state. - // - pDeviceContext->CurrentSwitchState = 0; - - // - // Service the pending interrupt switch change request - // - OsrUsbIoctlGetInterruptMessage(device, Status); - - return TRUE; -} - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/ioctl.c b/usb/umdf_filter_kmdf/kmdf_driver/ioctl.c deleted file mode 100644 index e36bcef1a..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/ioctl.c +++ /dev/null @@ -1,1063 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - Ioctl.c - -Abstract: - - USB device driver for OSR USB-FX2 Learning Kit - -Environment: - - Kernel mode only - ---*/ - -#include - -#if defined(EVENT_TRACING) -#include "ioctl.tmh" -#endif - -#pragma alloc_text(PAGE, OsrFxEvtIoDeviceControl) -#pragma alloc_text(PAGE, ResetPipe) -#pragma alloc_text(PAGE, ResetDevice) -#pragma alloc_text(PAGE, ReenumerateDevice) -#pragma alloc_text(PAGE, GetBarGraphState) -#pragma alloc_text(PAGE, SetBarGraphState) -#pragma alloc_text(PAGE, GetSevenSegmentState) -#pragma alloc_text(PAGE, SetSevenSegmentState) -#pragma alloc_text(PAGE, GetSwitchState) - -VOID -OsrFxEvtIoDeviceControl( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t OutputBufferLength, - _In_ size_t InputBufferLength, - _In_ ULONG IoControlCode - ) -/*++ - -Routine Description: - - This event is called when the framework receives IRP_MJ_DEVICE_CONTROL - requests from the system. - -Arguments: - - Queue - Handle to the framework queue object that is associated - with the I/O request. - Request - Handle to a framework request object. - - OutputBufferLength - length of the request's output buffer, - if an output buffer is available. - InputBufferLength - length of the request's input buffer, - if an input buffer is available. - - IoControlCode - the driver-defined or system-defined I/O control code - (IOCTL) that is associated with the request. -Return Value: - - VOID - ---*/ -{ - WDFDEVICE device; - PDEVICE_CONTEXT pDevContext; - size_t bytesReturned = 0; - PBAR_GRAPH_STATE barGraphState = NULL; - PSWITCH_STATE switchState = NULL; - PUCHAR sevenSegment = NULL; - BOOLEAN requestPending = FALSE; - NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; - - UNREFERENCED_PARAMETER(InputBufferLength); - UNREFERENCED_PARAMETER(OutputBufferLength); - - // - // If your driver is at the top of its driver stack, EvtIoDeviceControl is called - // at IRQL = PASSIVE_LEVEL. - // - _IRQL_limited_to_(PASSIVE_LEVEL); - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, "--> OsrFxEvtIoDeviceControl\n"); - // - // initialize variables - // - device = WdfIoQueueGetDevice(Queue); - pDevContext = GetDeviceContext(device); - - switch(IoControlCode) { - - case IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR: { - - PUSB_CONFIGURATION_DESCRIPTOR configurationDescriptor = NULL; - USHORT requiredSize = 0; - - // - // First get the size of the config descriptor - // - status = WdfUsbTargetDeviceRetrieveConfigDescriptor( - pDevContext->UsbDevice, - NULL, - &requiredSize); - - if (status != STATUS_BUFFER_TOO_SMALL) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "WdfUsbTargetDeviceRetrieveConfigDescriptor failed 0x%x\n", status); - break; - } - - // - // Get the buffer - make sure the buffer is big enough - // - status = WdfRequestRetrieveOutputBuffer(Request, - (size_t)requiredSize, // MinimumRequired - &configurationDescriptor, - NULL); - if(!NT_SUCCESS(status)){ - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "WdfRequestRetrieveOutputBuffer failed 0x%x\n", status); - break; - } - - status = WdfUsbTargetDeviceRetrieveConfigDescriptor( - pDevContext->UsbDevice, - configurationDescriptor, - &requiredSize); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "WdfUsbTargetDeviceRetrieveConfigDescriptor failed 0x%x\n", status); - break; - } - - bytesReturned = requiredSize; - - } - break; - - case IOCTL_OSRUSBFX2_RESET_DEVICE: - - status = ResetDevice(device); - break; - - case IOCTL_OSRUSBFX2_REENUMERATE_DEVICE: - - // - // Otherwise, call our function to reenumerate the - // device - // - status = ReenumerateDevice(pDevContext); - - bytesReturned = 0; - break; - - case IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY: - - // - // Make sure the caller's output buffer is large enough - // to hold the state of the bar graph - // - status = WdfRequestRetrieveOutputBuffer(Request, - sizeof(BAR_GRAPH_STATE), - &barGraphState, - NULL); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's output buffer is too small for this IOCTL, expecting an BAR_GRAPH_STATE\n"); - break; - } - // - // Call our function to get the bar graph state - // - status = GetBarGraphState(pDevContext, barGraphState); - - // - // If we succeeded return the user their data - // - if (NT_SUCCESS(status)) { - - bytesReturned = sizeof(BAR_GRAPH_STATE); - - } else { - - bytesReturned = 0; - - } - break; - - case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: - - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(BAR_GRAPH_STATE), - &barGraphState, - NULL); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's input buffer is too small for this IOCTL, expecting an BAR_GRAPH_STATE\n"); - break; - } - - // - // Call our routine to set the bar graph state - // - status = SetBarGraphState(pDevContext, barGraphState); - - // - // There's no data returned for this call - // - bytesReturned = 0; - break; - - case IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY: - - status = WdfRequestRetrieveOutputBuffer(Request, - sizeof(UCHAR), - &sevenSegment, - NULL); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's output buffer is too small for this IOCTL, expecting an UCHAR\n"); - break; - } - - // - // Call our function to get the 7 segment state - // - status = GetSevenSegmentState(pDevContext, sevenSegment); - - // - // If we succeeded return the user their data - // - if (NT_SUCCESS(status)) { - - bytesReturned = sizeof(UCHAR); - - } else { - - bytesReturned = 0; - - } - break; - - case IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY: - - status = WdfRequestRetrieveInputBuffer(Request, - sizeof(UCHAR), - &sevenSegment, - NULL); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's input buffer is too small for this IOCTL, expecting an UCHAR\n"); - bytesReturned = sizeof(UCHAR); - break; - } - - // - // Call our routine to set the 7 segment state - // - status = SetSevenSegmentState(pDevContext, sevenSegment); - - // - // There's no data returned for this call - // - bytesReturned = 0; - break; - - case IOCTL_OSRUSBFX2_READ_SWITCHES: - - status = WdfRequestRetrieveOutputBuffer(Request, - sizeof(SWITCH_STATE), - &switchState, - NULL);// BufferLength - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's output buffer is too small for this IOCTL, expecting a SWITCH_STATE\n"); - bytesReturned = sizeof(SWITCH_STATE); - break; - - } - - // - // Call our routine to get the state of the switches - // - status = GetSwitchState(pDevContext, switchState); - - // - // If successful, return the user their data - // - if (NT_SUCCESS(status)) { - - bytesReturned = sizeof(SWITCH_STATE); - - } else { - // - // Don't return any data - // - bytesReturned = 0; - } - break; - - case IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE: - - // - // Forward the request to an interrupt message queue and dont complete - // the request until an interrupt from the USB device occurs. - // - status = WdfRequestForwardToIoQueue(Request, pDevContext->InterruptMsgQueue); - if (NT_SUCCESS(status)) { - requestPending = TRUE; - } - - break; - - default : - status = STATUS_INVALID_DEVICE_REQUEST; - break; - } - - if (requestPending == FALSE) { - WdfRequestCompleteWithInformation(Request, status, bytesReturned); - } - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, "<-- OsrFxEvtIoDeviceControl\n"); - - return; -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ResetPipe( - _In_ WDFUSBPIPE Pipe - ) -/*++ - -Routine Description: - - This routine resets the pipe. - -Arguments: - - Pipe - framework pipe handle - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - - PAGED_CODE(); - - // - // This routine synchronously submits a URB_FUNCTION_RESET_PIPE - // request down the stack. - // - status = WdfUsbTargetPipeResetSynchronously(Pipe, - WDF_NO_HANDLE, // WDFREQUEST - NULL // PWDF_REQUEST_SEND_OPTIONS - ); - - if (NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, "ResetPipe - success\n"); - status = STATUS_SUCCESS; - } - else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "ResetPipe - failed\n"); - } - - return status; -} - -VOID -StopAllPipes( - IN PDEVICE_CONTEXT DeviceContext - ) -{ - WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe), - WdfIoTargetCancelSentIo); - WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkReadPipe), - WdfIoTargetCancelSentIo); - WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkWritePipe), - WdfIoTargetCancelSentIo); -} - -NTSTATUS -StartAllPipes( - IN PDEVICE_CONTEXT DeviceContext - ) -{ - NTSTATUS status; - - status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe)); - if (!NT_SUCCESS(status)) { - return status; - } - - status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkReadPipe)); - if (!NT_SUCCESS(status)) { - return status; - } - - status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkWritePipe)); - if (!NT_SUCCESS(status)) { - return status; - } - - return status; -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ResetDevice( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - This routine calls WdfUsbTargetDeviceResetPortSynchronously to reset the device if it's still - connected. - -Arguments: - - Device - Handle to a framework device - -Return Value: - - NT status value - ---*/ -{ - PDEVICE_CONTEXT pDeviceContext; - NTSTATUS status; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, "--> ResetDevice\n"); - - pDeviceContext = GetDeviceContext(Device); - - // - // A NULL timeout indicates an infinite wake - // - status = WdfWaitLockAcquire(pDeviceContext->ResetDeviceWaitLock, NULL); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "ResetDevice - could not acquire lock\n"); - return status; - } - - StopAllPipes(pDeviceContext); - - status = WdfUsbTargetDeviceResetPortSynchronously(pDeviceContext->UsbDevice); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "ResetDevice failed - 0x%x\n", status); - } - - status = StartAllPipes(pDeviceContext); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "Failed to start all pipes - 0x%x\n", status); - } - - WdfWaitLockRelease(pDeviceContext->ResetDeviceWaitLock); - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, "<-- ResetDevice\n"); - return status; -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ReenumerateDevice( - _In_ PDEVICE_CONTEXT DevContext - ) -/*++ - -Routine Description - - This routine re-enumerates the USB device. - -Arguments: - - pDevContext - One of our device extensions - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - GUID activity; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL,"--> ReenumerateDevice\n"); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_REENUMERATE, // Request - 0, // Value - 0); // Index - - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - WDF_NO_HANDLE, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - NULL, // MemoryDescriptor - NULL); // BytesTransferred - - if(!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "ReenumerateDevice: Failed to Reenumerate - 0x%x \n", status); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL,"<-- ReenumerateDevice\n"); - - // - // Send event to eventlog - // - - activity = DeviceToActivityId(WdfObjectContextGetObject(DevContext)); - EventWriteDeviceReenumerated(&activity, - DevContext->DeviceName, - DevContext->Location, - status); - - return status; - -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetBarGraphState( - _In_ PDEVICE_CONTEXT DevContext, - _Out_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - -Routine Description - - This routine gets the state of the bar graph on the board - -Arguments: - - DevContext - One of our device extensions - - BarGraphState - Struct that receives the bar graph's state - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - WDF_MEMORY_DESCRIPTOR memDesc; - ULONG bytesTransferred; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "--> GetBarGraphState\n"); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_BARGRAPH_DISPLAY, // Request - 0, // Value - 0); // Index - - // - // Set the buffer to 0, the board will OR in everything that is set - // - BarGraphState->BarsAsUChar = 0; - - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memDesc, - BarGraphState, - sizeof(BAR_GRAPH_STATE)); - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - WDF_NO_HANDLE, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - &memDesc, - &bytesTransferred); - - if(!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "GetBarGraphState: Failed to GetBarGraphState - 0x%x \n", status); - - } else { - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, - "GetBarGraphState: LED mask is 0x%x\n", BarGraphState->BarsAsUChar); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "<-- GetBarGraphState\n"); - - return status; - -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SetBarGraphState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - -Routine Description - - This routine sets the state of the bar graph on the board - -Arguments: - - DevContext - One of our device extensions - - BarGraphState - Struct that describes the bar graph's desired state - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - WDF_MEMORY_DESCRIPTOR memDesc; - ULONG bytesTransferred; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "--> SetBarGraphState\n"); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_BARGRAPH_DISPLAY, // Request - 0, // Value - 0); // Index - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memDesc, - BarGraphState, - sizeof(BAR_GRAPH_STATE)); - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - NULL, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - &memDesc, - &bytesTransferred); - - if(!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "SetBarGraphState: Failed - 0x%x \n", status); - - } else { - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, - "SetBarGraphState: LED mask is 0x%x\n", BarGraphState->BarsAsUChar); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "<-- SetBarGraphState\n"); - - return status; - -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetSevenSegmentState( - _In_ PDEVICE_CONTEXT DevContext, - _Out_ PUCHAR SevenSegment - ) -/*++ - -Routine Description - - This routine gets the state of the 7 segment display on the board - by sending a synchronous control command. - - NOTE: It's not a good practice to send a synchronous request in the - context of the user thread because if the transfer takes long - time to complete, you end up holding the user thread. - - I'm choosing to do synchronous transfer because a) I know this one - completes immediately b) and for demonstration. - -Arguments: - - DevContext - One of our device extensions - - SevenSegment - receives the state of the 7 segment display - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - - WDF_MEMORY_DESCRIPTOR memDesc; - ULONG bytesTransferred; - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "GetSetSevenSegmentState: Enter\n"); - - PAGED_CODE(); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_7SEGMENT_DISPLAY, // Request - 0, // Value - 0); // Index - - // - // Set the buffer to 0, the board will OR in everything that is set - // - *SevenSegment = 0; - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memDesc, - SevenSegment, - sizeof(UCHAR)); - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - NULL, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - &memDesc, - &bytesTransferred); - - if(!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "GetSevenSegmentState: Failed to get 7 Segment state - 0x%x \n", status); - } else { - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, - "GetSevenSegmentState: 7 Segment mask is 0x%x\n", *SevenSegment); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "GetSetSevenSegmentState: Exit\n"); - - return status; - -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SetSevenSegmentState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PUCHAR SevenSegment - ) -/*++ - -Routine Description - - This routine sets the state of the 7 segment display on the board - -Arguments: - - DevContext - One of our device extensions - - SevenSegment - desired state of the 7 segment display - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - WDF_MEMORY_DESCRIPTOR memDesc; - ULONG bytesTransferred; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "--> SetSevenSegmentState\n"); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_7SEGMENT_DISPLAY, // Request - 0, // Value - 0); // Index - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memDesc, - SevenSegment, - sizeof(UCHAR)); - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - NULL, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - &memDesc, - &bytesTransferred); - - if(!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "SetSevenSegmentState: Failed to set 7 Segment state - 0x%x \n", status); - - } else { - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, - "SetSevenSegmentState: 7 Segment mask is 0x%x\n", *SevenSegment); - - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "<-- SetSevenSegmentState\n"); - - return status; - -} - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetSwitchState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PSWITCH_STATE SwitchState - ) -/*++ - -Routine Description - - This routine gets the state of the switches on the board - -Arguments: - - DevContext - One of our device extensions - -Return Value: - - NT status value - ---*/ -{ - NTSTATUS status; - WDF_USB_CONTROL_SETUP_PACKET controlSetupPacket; - WDF_REQUEST_SEND_OPTIONS sendOptions; - WDF_MEMORY_DESCRIPTOR memDesc; - ULONG bytesTransferred; - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "--> GetSwitchState\n"); - - PAGED_CODE(); - - WDF_REQUEST_SEND_OPTIONS_INIT( - &sendOptions, - WDF_REQUEST_SEND_OPTION_TIMEOUT - ); - - WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT( - &sendOptions, - DEFAULT_CONTROL_TRANSFER_TIMEOUT - ); - - WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&controlSetupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_SWITCHES, // Request - 0, // Value - 0); // Index - - SwitchState->SwitchesAsUChar = 0; - - WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memDesc, - SwitchState, - sizeof(SWITCH_STATE)); - - status = WdfUsbTargetDeviceSendControlTransferSynchronously( - DevContext->UsbDevice, - NULL, // Optional WDFREQUEST - &sendOptions, - &controlSetupPacket, - &memDesc, - &bytesTransferred); - - if(!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "GetSwitchState: Failed to Get switches - 0x%x \n", status); - - } else { - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, - "GetSwitchState: Switch mask is 0x%x\n", SwitchState->SwitchesAsUChar); - } - - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "<-- GetSwitchState\n"); - - return status; - -} - - -VOID -OsrUsbIoctlGetInterruptMessage( - _In_ WDFDEVICE Device, - _In_ NTSTATUS ReaderStatus - ) -/*++ - -Routine Description - - This method handles the completion of the pended request for the IOCTL - IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE. - -Arguments: - - Device - Handle to a framework device. - -Return Value: - - None. - ---*/ -{ - NTSTATUS status; - WDFREQUEST request; - PDEVICE_CONTEXT pDevContext; - size_t bytesReturned = 0; - PSWITCH_STATE switchState = NULL; - - pDevContext = GetDeviceContext(Device); - - do { - - // - // Check if there are any pending requests in the Interrupt Message Queue. - // If a request is found then complete the pending request. - // - status = WdfIoQueueRetrieveNextRequest(pDevContext->InterruptMsgQueue, &request); - - if (NT_SUCCESS(status)) { - status = WdfRequestRetrieveOutputBuffer(request, - sizeof(SWITCH_STATE), - &switchState, - NULL);// BufferLength - - if (!NT_SUCCESS(status)) { - - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, - "User's output buffer is too small for this IOCTL, expecting a SWITCH_STATE\n"); - bytesReturned = sizeof(SWITCH_STATE); - - } else { - - // - // Copy the state information saved by the continuous reader. - // - if (NT_SUCCESS(ReaderStatus)) { - switchState->SwitchesAsUChar = pDevContext->CurrentSwitchState; - bytesReturned = sizeof(SWITCH_STATE); - } else { - bytesReturned = 0; - } - } - - // - // Complete the request. If we failed to get the output buffer then - // complete with that status. Otherwise complete with the status from the reader. - // - WdfRequestCompleteWithInformation(request, - NT_SUCCESS(status) ? ReaderStatus : status, - bytesReturned); - status = STATUS_SUCCESS; - - } else if (status != STATUS_NO_MORE_ENTRIES) { - KdPrint(("WdfIoQueueRetrieveNextRequest status %08x\n", status)); - } - - request = NULL; - - } while (status == STATUS_SUCCESS); - - return; - -} - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.h b/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.h deleted file mode 100644 index 909e347d4..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.h +++ /dev/null @@ -1,335 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - private.h - -Abstract: - - Contains structure definitions and function prototypes private to - the driver. - -Environment: - - Kernel mode - ---*/ - -#include -#include -#include "usbdi.h" -#include "usbdlib.h" -#include "public.h" -#include "driverspecs.h" -#include -#include -#define NTSTRSAFE_LIB -#include - -#include "trace.h" - -// -// Include auto-generated ETW event functions (created by MC.EXE from -// osrusbfx2.man) -// -#include "fx2Events.h" - -#ifndef _PRIVATE_H -#define _PRIVATE_H - -#define POOL_TAG (ULONG) 'FRSO' -#define _DRIVER_NAME_ "OSRUSBFX2" - -#define TEST_BOARD_TRANSFER_BUFFER_SIZE (64*1024) -#define DEVICE_DESC_LENGTH 256 - -extern const __declspec(selectany) LONGLONG DEFAULT_CONTROL_TRANSFER_TIMEOUT = 5 * -1 * WDF_TIMEOUT_TO_SEC; - -// -// Define the vendor commands supported by our device -// -#define USBFX2LK_READ_7SEGMENT_DISPLAY 0xD4 -#define USBFX2LK_READ_SWITCHES 0xD6 -#define USBFX2LK_READ_BARGRAPH_DISPLAY 0xD7 -#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 -#define USBFX2LK_IS_HIGH_SPEED 0xD9 -#define USBFX2LK_REENUMERATE 0xDA -#define USBFX2LK_SET_7SEGMENT_DISPLAY 0xDB - -// -// Define the features that we can clear -// and set on our device -// -#define USBFX2LK_FEATURE_EPSTALL 0x00 -#define USBFX2LK_FEATURE_WAKE 0x01 - -// -// Order of endpoints in the interface descriptor -// -#define INTERRUPT_IN_ENDPOINT_INDEX 0 -#define BULK_OUT_ENDPOINT_INDEX 1 -#define BULK_IN_ENDPOINT_INDEX 2 - -// -// A structure representing the instance information associated with -// this particular device. -// - -typedef struct _DEVICE_CONTEXT { - - WDFUSBDEVICE UsbDevice; - - WDFUSBINTERFACE UsbInterface; - - WDFUSBPIPE BulkReadPipe; - - WDFUSBPIPE BulkWritePipe; - - WDFUSBPIPE InterruptPipe; - - WDFWAITLOCK ResetDeviceWaitLock; - - UCHAR CurrentSwitchState; - - WDFQUEUE InterruptMsgQueue; - - ULONG UsbDeviceTraits; - - // - // The following fields are used during event logging to - // report the events relative to this specific instance - // of the device. - // - - WDFMEMORY DeviceNameMemory; - PCWSTR DeviceName; - - WDFMEMORY LocationMemory; - PCWSTR Location; - -} DEVICE_CONTEXT, *PDEVICE_CONTEXT; - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, GetDeviceContext) - -extern ULONG DebugLevel; - -typedef -NTSTATUS -(*PFN_IO_GET_ACTIVITY_ID_IRP) ( - _In_ PIRP Irp, - _Out_ LPGUID Guid - ); - -typedef -NTSTATUS -(*PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA) ( - _In_ PUNICODE_STRING SymbolicLinkName, - _In_ CONST DEVPROPKEY *PropertyKey, - _In_ LCID Lcid, - _In_ ULONG Flags, - _In_ DEVPROPTYPE Type, - _In_ ULONG Size, - _In_opt_ PVOID Data - ); - -// -// Global function pointer set in DriverEntry -// Check for NULL before using -// -extern PFN_IO_GET_ACTIVITY_ID_IRP g_pIoGetActivityIdIrp; - -extern PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA g_pIoSetDeviceInterfacePropertyData; - -DRIVER_INITIALIZE DriverEntry; - -EVT_WDF_OBJECT_CONTEXT_CLEANUP OsrFxEvtDriverContextCleanup; - -EVT_WDF_DRIVER_DEVICE_ADD OsrFxEvtDeviceAdd; - -EVT_WDF_DEVICE_PREPARE_HARDWARE OsrFxEvtDevicePrepareHardware; - -EVT_WDF_IO_QUEUE_IO_READ OsrFxEvtIoRead; - -EVT_WDF_IO_QUEUE_IO_WRITE OsrFxEvtIoWrite; - -EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL OsrFxEvtIoDeviceControl; - -EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestReadCompletionRoutine; - -EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestWriteCompletionRoutine; - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ResetPipe( - _In_ WDFUSBPIPE Pipe - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ResetDevice( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SelectInterfaces( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -ReenumerateDevice( - _In_ PDEVICE_CONTEXT DevContext - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetBarGraphState( - _In_ PDEVICE_CONTEXT DevContext, - _Out_ PBAR_GRAPH_STATE BarGraphState - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SetBarGraphState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PBAR_GRAPH_STATE BarGraphState - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetSevenSegmentState( - _In_ PDEVICE_CONTEXT DevContext, - _Out_ PUCHAR SevenSegment - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -SetSevenSegmentState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PUCHAR SevenSegment - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -GetSwitchState( - _In_ PDEVICE_CONTEXT DevContext, - _In_ PSWITCH_STATE SwitchState - ); - -VOID -OsrUsbIoctlGetInterruptMessage( - _In_ WDFDEVICE Device, - _In_ NTSTATUS ReaderStatus - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -OsrFxSetPowerPolicy( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_(PASSIVE_LEVEL) -NTSTATUS -OsrFxConfigContReaderForInterruptEndPoint( - _In_ PDEVICE_CONTEXT DeviceContext - ); - -EVT_WDF_USB_READER_COMPLETION_ROUTINE OsrFxEvtUsbInterruptPipeReadComplete; - -EVT_WDF_USB_READERS_FAILED OsrFxEvtUsbInterruptReadersFailed; - -EVT_WDF_IO_QUEUE_IO_STOP OsrFxEvtIoStop; - -EVT_WDF_DEVICE_D0_ENTRY OsrFxEvtDeviceD0Entry; - -EVT_WDF_DEVICE_D0_EXIT OsrFxEvtDeviceD0Exit; - -EVT_WDF_DEVICE_SELF_MANAGED_IO_FLUSH OsrFxEvtDeviceSelfManagedIoFlush; - -_IRQL_requires_(PASSIVE_LEVEL) -BOOLEAN -OsrFxReadFdoRegistryKeyValue( - _In_ PWDFDEVICE_INIT DeviceInit, - _In_ PWCHAR Name, - _Out_ PULONG Value - ); - -_IRQL_requires_max_(DISPATCH_LEVEL) -VOID -OsrFxEnumerateChildren( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_(PASSIVE_LEVEL) -VOID -GetDeviceEventLoggingNames( - _In_ WDFDEVICE Device - ); - -_IRQL_requires_(PASSIVE_LEVEL) -PCHAR -DbgDevicePowerString( - _In_ WDF_POWER_DEVICE_STATE Type - ); - - -_IRQL_requires_(PASSIVE_LEVEL) -USBD_STATUS -OsrFxValidateConfigurationDescriptor( - _In_reads_bytes_(BufferLength) PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc, - _In_ ULONG BufferLength, - _Inout_ PUCHAR *Offset - ); - -FORCEINLINE -GUID -RequestToActivityId( - _In_ WDFREQUEST Request - ) -{ - GUID activity = {0}; - NTSTATUS status = STATUS_SUCCESS; - - if (g_pIoGetActivityIdIrp != NULL) { - - // - // Use activity ID generated by application (or IO manager) - // - status = g_pIoGetActivityIdIrp(WdfRequestWdmGetIrp(Request), &activity); - } - - if (g_pIoGetActivityIdIrp == NULL || !NT_SUCCESS(status)) { - - // - // Fall back to using the WDFREQUEST handle as the activity ID - // - RtlCopyMemory(&activity, &Request, sizeof(WDFREQUEST)); - } - - - return activity; -} - -FORCEINLINE -GUID -DeviceToActivityId( - _In_ WDFDEVICE Device - ) -{ - GUID activity = {0}; - RtlCopyMemory(&activity, &Device, sizeof(WDFDEVICE)); - return activity; -} - - -#endif - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.man b/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.man deleted file mode 100644 index 176dfc896..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.man +++ /dev/null @@ -1,309 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.rc b/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.rc deleted file mode 100644 index 092ec1957..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.rc +++ /dev/null @@ -1,18 +0,0 @@ -#include - -#include - -#define VER_FILETYPE VFT_DRV -#define VER_FILESUBTYPE VFT2_DRV_SYSTEM -#define VER_FILEDESCRIPTION_STR "WDF Sample Driver for OSR USB-FX2 Learning Kit" -#define VER_INTERNALNAME_STR "osrusbfx2.sys" -#define VER_ORIGINALFILENAME_STR "osrusbfx2.sys" - -#include "common.ver" - -// -// Include auto-generated string resources (created by MC.EXE from -// osrusbfx2.man) -// - -#include "fx2Events.rc" diff --git a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj b/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj deleted file mode 100644 index bbceb79b7..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj +++ /dev/null @@ -1,256 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {837F98CF-D3A4-472C-BACC-47950340E57B} - $(MSBuildProjectName) - 1 - false - true - Debug - Win32 - {3EBA8CBF-2E65-4819-9EEA-E10825BB0705} - - - - Windows10 - False - Desktop - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Desktop - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - False - Desktop - KMDF - WindowsKernelModeDriver10.0 - Driver - - - Windows10 - True - Desktop - KMDF - WindowsKernelModeDriver10.0 - Driver - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - TraceEvents(LEVEL,FLAGS,MSG,...) - {km-WdfDefault.tpl}*.tmh - - - true - true - .\$(IntDir) - true - .\$(IntDir) - true - fx2Events - true - - - true - true - TraceEvents(LEVEL,FLAGS,MSG,...) - {km-WdfDefault.tpl}*.tmh - - - - osrusbfx2 - - - osrusbfx2 - - - osrusbfx2 - - - osrusbfx2 - - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - true - Level4 - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntstrsafe.lib;$(DDK_LIB_PATH)\usbd.lib - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - true - Level4 - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntstrsafe.lib;$(DDK_LIB_PATH)\usbd.lib - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - true - Level4 - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntstrsafe.lib;$(DDK_LIB_PATH)\usbd.lib - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - true - Level4 - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalIncludeDirectories);..\inc;. - %(PreprocessorDefinitions);EVENT_TRACING - - - %(AdditionalDependencies);$(DDK_LIB_PATH)\ntstrsafe.lib;$(DDK_LIB_PATH)\usbd.lib - - - sha256 - - - - 1 - - - 1 - - - 1 - - - 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj.Filters b/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj.Filters deleted file mode 100644 index baf7ab2e6..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/osrusbfx2.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {F859293F-10B7-4E6D-99E2-120A09448FF9} - - - h;hpp;hxx;hm;inl;inc;xsd - {3DCE0FEA-C37D-448E-B9E4-B69865E71B5F} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {A1BB449A-54EF-4B2B-BD68-2254963FF387} - - - inf;inv;inx;mof;mc; - {A03D3DFA-E9BD-48A3-BEDE-E8AAED283D03} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_filter_kmdf/kmdf_driver/trace.h b/usb/umdf_filter_kmdf/kmdf_driver/trace.h deleted file mode 100644 index 518ff5f17..000000000 --- a/usb/umdf_filter_kmdf/kmdf_driver/trace.h +++ /dev/null @@ -1,115 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - TRACE.h - -Abstract: - - Header file for the debug tracing related function defintions and macros. - -Environment: - - Kernel mode - ---*/ - -#include // For TRACE_LEVEL definitions - -#if !defined(EVENT_TRACING) - -// -// TODO: These defines are missing in evntrace.h -// in some DDK build environments (XP). -// -#if !defined(TRACE_LEVEL_NONE) - #define TRACE_LEVEL_NONE 0 - #define TRACE_LEVEL_CRITICAL 1 - #define TRACE_LEVEL_FATAL 1 - #define TRACE_LEVEL_ERROR 2 - #define TRACE_LEVEL_WARNING 3 - #define TRACE_LEVEL_INFORMATION 4 - #define TRACE_LEVEL_VERBOSE 5 - #define TRACE_LEVEL_RESERVED6 6 - #define TRACE_LEVEL_RESERVED7 7 - #define TRACE_LEVEL_RESERVED8 8 - #define TRACE_LEVEL_RESERVED9 9 -#endif - - -// -// Define Debug Flags -// -#define DBG_INIT 0x00000001 -#define DBG_PNP 0x00000002 -#define DBG_POWER 0x00000004 -#define DBG_WMI 0x00000008 -#define DBG_CREATE_CLOSE 0x00000010 -#define DBG_IOCTL 0x00000020 -#define DBG_WRITE 0x00000040 -#define DBG_READ 0x00000080 - - -VOID -TraceEvents ( - _In_ ULONG DebugPrintLevel, - _In_ ULONG DebugPrintFlag, - _Printf_format_string_ - _In_ PCSTR DebugMessage, - ... - ); - -#define WPP_INIT_TRACING(DriverObject, RegistryPath) -#define WPP_CLEANUP(DriverObject) - -#else -// -// If software tracing is defined in the sources file.. -// WPP_DEFINE_CONTROL_GUID specifies the GUID used for this driver. -// *** REPLACE THE GUID WITH YOUR OWN UNIQUE ID *** -// WPP_DEFINE_BIT allows setting debug bit masks to selectively print. -// The names defined in the WPP_DEFINE_BIT call define the actual names -// that are used to control the level of tracing for the control guid -// specified. -// -// NOTE: If you are adopting this sample for your driver, please generate -// a new guid, using tools\other\i386\guidgen.exe present in the -// DDK. -// -// Name of the logger is OSRUSBFX2 and the guid is -// {D23A0C5A-D307-4f0e-AE8E-E2A355AD5DAB} -// (0xd23a0c5a, 0xd307, 0x4f0e, 0xae, 0x8e, 0xe2, 0xa3, 0x55, 0xad, 0x5d, 0xab); -// - -#define WPP_CHECK_FOR_NULL_STRING //to prevent exceptions due to NULL strings - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID(OsrUsbFxTraceGuid,(d23a0c5a,d307,4f0e,ae8e,E2A355AD5DAB), \ - WPP_DEFINE_BIT(DBG_INIT) /* bit 0 = 0x00000001 */ \ - WPP_DEFINE_BIT(DBG_PNP) /* bit 1 = 0x00000002 */ \ - WPP_DEFINE_BIT(DBG_POWER) /* bit 2 = 0x00000004 */ \ - WPP_DEFINE_BIT(DBG_WMI) /* bit 3 = 0x00000008 */ \ - WPP_DEFINE_BIT(DBG_CREATE_CLOSE) /* bit 4 = 0x00000010 */ \ - WPP_DEFINE_BIT(DBG_IOCTL) /* bit 5 = 0x00000020 */ \ - WPP_DEFINE_BIT(DBG_WRITE) /* bit 6 = 0x00000040 */ \ - WPP_DEFINE_BIT(DBG_READ) /* bit 7 = 0x00000080 */ \ - /* You can have up to 32 defines. If you want more than that,\ - you have to provide another trace control GUID */\ - ) - - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) WPP_LEVEL_LOGGER(flags) -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - - -#endif - - - diff --git a/usb/umdf_filter_kmdf/umdf_filter/OsrUsbFilter.rc b/usb/umdf_filter_kmdf/umdf_filter/OsrUsbFilter.rc deleted file mode 100644 index cec032d97..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/OsrUsbFilter.rc +++ /dev/null @@ -1,17 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbFilter.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OsrUsbFilter User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "OsrUsbFilter" -#define VER_ORIGINALFILENAME_STR "OsrUsbFilter.dll" - -#include "common.ver" diff --git a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj b/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj deleted file mode 100644 index 38798dfef..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj +++ /dev/null @@ -1,293 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127} - $(MSBuildProjectName) - 1 - 1 - false - true - Debug - Win32 - {45297D7C-3015-4F09-B0E7-469440EB9458} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters b/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters deleted file mode 100644 index 7a4a8f8d7..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {3CE4C3CE-9C1D-4790-B2EF-784C3412310A} - - - h;hpp;hxx;hm;inl;inc;xsd - {4A9BD78B-5831-48AA-8C22-28BEBBC8A7AB} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {ACD57755-0E18-4D24-A740-0D944929A053} - - - inf;inv;inx;mof;mc; - {2084F476-D6F1-485F-B9A6-581DD86D24F1} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilterOnKmDriver.inx b/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilterOnKmDriver.inx deleted file mode 100644 index cc64a1d46..000000000 Binary files a/usb/umdf_filter_kmdf/umdf_filter/WUDFOsrUsbFilterOnKmDriver.inx and /dev/null differ diff --git a/usb/umdf_filter_kmdf/umdf_filter/comsup.cpp b/usb/umdf_filter_kmdf/umdf_filter/comsup.cpp deleted file mode 100644 index 76a4b940b..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/comsup.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// This is the number of characters in a GUID string including the trailing -// NULL. -// - -#define GUID_STRING_CCH (sizeof("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}")) - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -_Use_decl_annotations_ -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/umdf_filter_kmdf/umdf_filter/comsup.h b/usb/umdf_filter_kmdf/umdf_filter/comsup.h deleted file mode 100644 index 890b576a5..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/comsup.h +++ /dev/null @@ -1,216 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/umdf_filter_kmdf/umdf_filter/device.cpp b/usb/umdf_filter_kmdf/umdf_filter/device.cpp deleted file mode 100644 index 126637ce0..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/device.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR USB Sample Filter driver's - device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR USB Sample Filter driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // We don't need device level locking since we do not keep any state - // across the requests - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // Mark ourselves as a filter - // - - FxDeviceInit->SetFilter(); - - - // - // We are a filter; we don't want to be the power policy owner - // - - FxDeviceInit->SetPowerPolicyOwnership(FALSE); - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - PCMyQueue defaultQueue; - - HRESULT hr; - - hr = CMyQueue::CreateInstance(m_FxDevice, &defaultQueue); - - if (FAILED(hr)) - { - return hr; - } - - hr = defaultQueue->Configure(); - - defaultQueue->Release(); - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the OSR USB Sample Filter driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If OSR USB Sample Filter is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - return CUnknown::QueryInterface(InterfaceId, Object); -} diff --git a/usb/umdf_filter_kmdf/umdf_filter/device.h b/usb/umdf_filter_kmdf/umdf_filter/device.h deleted file mode 100644 index f7a50b1d0..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/device.h +++ /dev/null @@ -1,114 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF OSR USB Sample Filter - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the iotrace driver. -// - -class CMyDevice : public CUnknown -{ - -// -// Private data members. -// -private: - - IWDFDevice *m_FxDevice; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) - { - m_FxDevice = NULL; - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_kmdf/umdf_filter/dllsup.cpp b/usb/umdf_filter_kmdf/umdf_filter/dllsup.cpp deleted file mode 100644 index d71d5fe83..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/dllsup.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the OSR USB Sample Filter - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the OSR USB Sample Filter sample. If - you choose to use a different primary include file, you should ensure - they are defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -// -// Global variable to hold the module handle for this DLL. Initialized during -// DllMain and never cleared. This is used when registering and unregistering -// the driver's COM information. -// - -HINSTANCE g_ModuleHandle = NULL; - -BOOL -WINAPI -DllMain( - HINSTANCE /* ModuleHandle */, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the OSR USB Sample - Filter driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} - diff --git a/usb/umdf_filter_kmdf/umdf_filter/driver.cpp b/usb/umdf_filter_kmdf/umdf_filter/driver.cpp deleted file mode 100644 index c5910c05e..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/driver.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR USB Sample Filter - driver's core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/umdf_filter_kmdf/umdf_filter/driver.h b/usb/umdf_filter_kmdf/umdf_filter/driver.h deleted file mode 100644 index 08f36a712..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/driver.h +++ /dev/null @@ -1,145 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF OSR USB Sample Filter - driver's callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the OSR USB Sample Filter driver. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver* /*FxWdfDriver*/ - ) - { - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver * /*FxWdfDriver*/ - ) - { - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_kmdf/umdf_filter/exports.def b/usb/umdf_filter_kmdf/umdf_filter/exports.def deleted file mode 100644 index 0fc428179..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; Skeleton.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/umdf_filter_kmdf/umdf_filter/internal.h b/usb/umdf_filter_kmdf/umdf_filter/internal.h deleted file mode 100644 index 516f6d7fa..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/internal.h +++ /dev/null @@ -1,111 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF OSR USB Sample Filter - driver. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -// -// Define the tracing flags. -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (73cdcaa5,ce52,43f2,aa2d,5f5a84e22213), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsbFilter" -#define MYDRIVER_COM_DESCRIPTION L"UMDF OSR USB Sample Filter Driver" -#define MYDRIVER_CLASS_ID {0x422d8dbc, 0x520d, 0x4d7e, {0x8f, 0x53, 0x92, 0x0e, 0x5c, 0x86, 0x7e, 0x6c}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_SAMPLE_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/umdf_filter_kmdf/umdf_filter/queue.cpp b/usb/umdf_filter_kmdf/umdf_filter/queue.cpp deleted file mode 100644 index 5642ec744..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/queue.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Queue.cpp - -Abstract: - - This module contains the implementation of the OSR USB Filter Sample driver's - queue callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.h" - -#include "queue.tmh" - -HRESULT -CMyQueue::CreateInstance( - _In_ IWDFDevice * FxDevice, - _Out_ CMyQueue **Queue - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR USB Filter Sample driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - CMyQueue *queue; - - HRESULT hr = S_OK; - - // - // Allocate a new instance of the device class. - // - - queue = new CMyQueue(); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(FxDevice); - } - - if (SUCCEEDED(hr)) - { - queue->AddRef(); - *Queue = queue; - } - - if (NULL != queue) - { - queue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - - if(IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDefaultIoHandler))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDefaultIoHandler(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) - { - hr = S_OK; - *Object = QueryIQueueCallbackWrite(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - hr = S_OK; - *Object = QueryIRequestCallbackRequestCompletion(); - - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyQueue::Initialize( - _In_ IWDFDevice *FxDevice - ) -/*++ - - Routine Description: - - This method initializes the device callback object. Any operations which - need to be performed before the caller can use the callback object, but - which couldn't be done in the constructor becuase they could fail would - be placed here. - - Arguments: - - FxDevice - the device which this Queue is for. - - Return Value: - - status. - ---*/ -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the framework queue - // - - IUnknown *unknown = QueryIUnknown(); - hr = FxDevice->CreateIoQueue( - unknown, - TRUE, // bDefaultQueue - WdfIoQueueDispatchParallel, - FALSE, // bPowerManaged - TRUE, // bAllowZeroLengthRequests - &fxQueue - ); - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - "%!FUNC!: Could not create default I/O queue, %!hresult!", - hr - ); - } - - unknown->Release(); - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // m_FxQueue is kept as a Weak reference to framework Queue object to avoid - // circular reference. This object's lifetime is contained within - // framework Queue object's lifetime - // - - fxQueue->Release(); - } - - if (SUCCEEDED(hr)) - { - FxDevice->GetDefaultIoTarget(&m_FxIoTarget); - } - - return hr; -} - -void -CMyQueue::InvertBits( - _Inout_ IWDFMemory* FxMemory, - _In_ SIZE_T NumBytes - ) -/*++ - - Routine Description: - - This helper method inverts bits in the buffer of an FxMemory object - - Arguments: - - FxMemory - Framework memory object whose buffer's bits are to be inverted - - NumBytes - Number of bytes for which bits are to be inverted - - Return Value: - - None - ---*/ -{ - PBYTE Buffer = (PBYTE) - FxMemory->GetDataBuffer(NULL); - - for (SIZE_T i = 0; i < NumBytes; i++) - { - memset(Buffer + i, ~(Buffer[i]), sizeof(*Buffer)); - } -} - -void -CMyQueue::OnWrite( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest, - _In_ SIZE_T NumOfBytesToWrite - ) -/*++ - - Routine Description: - - This method is called by Framework Queue object to deliver the Write request - This method inverts the bits in write buffer and forwards the request down the device stack - In case of any failure prior to ForwardRequest, it completets the request with failure - - Arguments: - - pWdfQueue - Framework Queue which is delivering the request - - pWdfRequest - Framework Request - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - IWDFMemory * FxInputMemory = NULL; - - FxRequest->GetInputMemory(&FxInputMemory); - - // - // Invert bits of the buffer to be written to device - // - - InvertBits(FxInputMemory, NumOfBytesToWrite); - - // - // Forward request down the stack - // When the device below completes the request we will get notified in OnComplete - // and then we will complete the request - // - - ForwardRequest(FxRequest); - - FxInputMemory->Release(); -} - -// -// IQueueCallbackDefaultIoHandler method -// - -void -CMyQueue::OnDefaultIoHandler( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest - ) -/*++ - - Routine Description: - - This method is called by Framework Queue object to deliver all the I/O - Requests for which we do not have a specific handler - (In our case anything other than Write) - - Arguments: - - pWdfQueue - Framework Queue which is delivering the request - - pWdfRequest - Framework Request - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - // - // We just forward the request down the stack - // When the device below completes the request we will get notified in OnComplete - // and then we will complete the request - // - - ForwardRequest(FxRequest); -} - -void -CMyQueue::ForwardRequest( - _In_ IWDFIoRequest* FxRequest - ) -/*++ - - Routine Description: - - This helper method forwards the request down the stack - - Arguments: - - pWdfRequest - Request to be forwarded - - Return Value: - - None - - Remarks: - - The request gets forwarded to the next device in the stack which can be: - 1. Next device in user-mode stack - 2. Top device in kernel-mode stack (Redirector's Down Device) - - In this routine we: - 1. Set a completion callback - 2. Copy request parameters to next stack location - 3. Asynchronously send the request without any timeout - - When the lower request gets completed we will be notified via the - completion callback, where we will complete our request - - In case of failure this routine completes the request - ---*/ -{ - // - //First set the completion callback - // - - IRequestCallbackRequestCompletion *completionCallback = - QueryIRequestCallbackRequestCompletion(); - - FxRequest->SetCompletionCallback( - completionCallback, - NULL //pContext - ); - - completionCallback->Release(); - - // - //Copy current i/o stack locations parameters to the next stack location - // - - FxRequest->FormatUsingCurrentType( - ); - - // - //Send down the request - // - HRESULT hrSend = S_OK; - - hrSend = FxRequest->Send( - m_FxIoTarget, - 0, //No flag - 0 //No timeout - ); - - if (FAILED(hrSend)) - { - // - //If send failed we need to complete the request with failure - // - FxRequest->CompleteWithInformation(hrSend, 0); - } - - return; -} - -void -CMyQueue::HandleReadRequestCompletion( - IWDFIoRequest* FxRequest, - IWDFIoRequestCompletionParams* CompletionParams - ) -/*++ - - Routine Description: - - This helper method is called by OnCompletion method to complete Read request - We invert the bits in the read buffer - This is so that the client reads back the data it wrote since - we inverted bits during write to device - - Arguments: - - FxRequest - Request object of our layer - - CompletionParams - Parameters with which the lower Request got completed - - Return Value: - - None - - Remarks: - - This method always completes the request since no one else would get a chance to - complete the request - In case of failure it completes the request with failure - ---*/ -{ - HRESULT hrCompletion = CompletionParams->GetCompletionStatus(); - ULONG_PTR BytesRead = CompletionParams->GetInformation(); - - // - // Check - // 1. whether the lower device succeeded the Request (otherwise we will just complete - // the Request with failure - // 2. If data read is of non-zero length, for us to bother to invert its bits - // - - if (SUCCEEDED(hrCompletion) && - (0 != BytesRead) - ) - { - IWDFMemory *FxOutputMemory; - - FxRequest->GetOutputMemory(&FxOutputMemory ); - - InvertBits(FxOutputMemory, BytesRead); - - FxOutputMemory->Release(); - } - - // - // Complete the request - // - - FxRequest->CompleteWithInformation( - hrCompletion, - BytesRead - ); -} - - -void -CMyQueue::OnCompletion( - IWDFIoRequest* FxRequest, - IWDFIoTarget* FxIoTarget, - IWDFRequestCompletionParams* CompletionParams, - PVOID Context - ) -/*++ - - Routine Description: - - This method is called by Framework I/O Target object when - the lower device completets the Request - - Arguments: - - pWdfRequest - Request object of our layer - - pIoTarget - I/O Target object invoking this callback - - pParams - Parameters with which the lower Request got completed - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxIoTarget); - UNREFERENCED_PARAMETER(Context); - - // - // If it is a read request, we invert the bits read since we inverted them during write - // so that application would read the same data as it wrote - // - - if (WdfRequestRead == FxRequest->GetType()) - { - IWDFIoRequestCompletionParams * IoCompletionParams = NULL; - HRESULT hrQI = CompletionParams->QueryInterface(IID_PPV_ARGS(&IoCompletionParams)); - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - HandleReadRequestCompletion( - FxRequest, - IoCompletionParams - ); - - SAFE_RELEASE(IoCompletionParams); - } - else - { - - // - // Otherwise we just complete our Request object with the same parameters - // with which the lower Request got completed - // - - FxRequest->CompleteWithInformation( - CompletionParams->GetCompletionStatus(), - CompletionParams->GetInformation() - ); - } -} - diff --git a/usb/umdf_filter_kmdf/umdf_filter/queue.h b/usb/umdf_filter_kmdf/umdf_filter/queue.h deleted file mode 100644 index 216264e93..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter/queue.h +++ /dev/null @@ -1,253 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Queue.h - -Abstract: - - This module contains the type definitions for the OSR USB Filter Sample - driver's queue callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the queue callbacks. -// It implements -// IQueueCallbackDeviceIoControl -// IRequestCallbackRequestCompletion -// Queue callbacks -// -// This class also implements IRequestCallbackRequestCompletion callback -// to get the request completion notification when request is sent down the -// stack. This callback can be implemented on a separate object as well. -// This callback is implemented here only for conenience. -// -class CMyQueue : - public CUnknown, - public IQueueCallbackWrite, - public IQueueCallbackDefaultIoHandler, - public IRequestCallbackRequestCompletion -{ - -// -// Private data members. -// -private: - - // - // Weak reference to framework Queue object which this object implements callbacks for - // This is kept as a weak reference to avoid circular reference - // This object's lifetime is contained within framework Queue object's lifetime - // - - IWDFIoQueue *m_FxQueue; - - // - // I/O Target to which we forward requests. Represents next device in the - // device stack - // - - IWDFIoTarget *m_FxIoTarget; - -// -// Private methods. -// - -private: - - CMyQueue() : - m_FxQueue(NULL), - m_FxIoTarget(NULL) - { - } - - virtual ~CMyQueue() - { - if (NULL != m_FxIoTarget) - { - m_FxIoTarget->Release(); - } - } - - // - // QueryInterface helpers - // - - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackDefaultIoHandler * - QueryIQueueCallbackDefaultIoHandler( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // Initialize - // - - HRESULT - Initialize( - _In_ IWDFDevice *FxDevice - ); - - // - // Helper method to forward request down the stack - // - - void - ForwardRequest( - _In_ IWDFIoRequest *pWdfRequest - ); - - // - // Helper method to inverts bits in the buffer of a framework Memory object - // - - void - InvertBits( - _Inout_ IWDFMemory* FxMemory, - _In_ SIZE_T NumBytes - ); - - // - // Helper method to handle Read request completion - // - - void - HandleReadRequestCompletion( - IWDFIoRequest* FxRequest, - IWDFIoRequestCompletionParams* CompletionParams - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this class - // - - static - HRESULT - CreateInstance( - _In_ IWDFDevice *FxDevice, - _Out_ CMyQueue **Queue - ); - - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IQueueCallbackWrite method - // - - virtual - void - STDMETHODCALLTYPE - OnWrite( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - - // - // IQueueCallbackDefaultIoHandler method - // - - virtual - void - STDMETHODCALLTYPE - OnDefaultIoHandler( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest - ); - - // - //IRequestCallbackRequestCompletion - // - - virtual - void - STDMETHODCALLTYPE - OnCompletion( - IWDFIoRequest* FxRequest, - IWDFIoTarget* FxIoTarget, - IWDFRequestCompletionParams* CompletionParams, - PVOID Context - ); -}; - diff --git a/usb/umdf_filter_kmdf/umdf_filter_kmdf.sln b/usb/umdf_filter_kmdf/umdf_filter_kmdf.sln deleted file mode 100644 index 5a39a03d7..000000000 --- a/usb/umdf_filter_kmdf/umdf_filter_kmdf.sln +++ /dev/null @@ -1,59 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Package", "Package", "{0C11CE20-E0CC-403B-B957-FB72E3AD659A}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Umdf_filter", "Umdf_filter", "{FD04F724-4BA6-4E88-B269-53F28C44E2F2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Kmdf_driver", "Kmdf_driver", "{8FED241E-8771-423B-8ED2-EF4873FAED48}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "package", "Package\package.VcxProj", "{10E372EF-AE85-4528-919C-A261253EDDAE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFilter", "umdf_filter\WUDFOsrUsbFilter.vcxproj", "{ADCCB27A-E522-4367-86B9-9C9DF2636B93}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrusbfx2", "kmdf_driver\osrusbfx2.vcxproj", "{837F98CF-D3A4-472C-BACC-47950340E57B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10E372EF-AE85-4528-919C-A261253EDDAE}.Debug|Win32.ActiveCfg = Debug|Win32 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Debug|Win32.Build.0 = Debug|Win32 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Release|Win32.ActiveCfg = Release|Win32 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Release|Win32.Build.0 = Release|Win32 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Debug|x64.ActiveCfg = Debug|x64 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Debug|x64.Build.0 = Debug|x64 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Release|x64.ActiveCfg = Release|x64 - {10E372EF-AE85-4528-919C-A261253EDDAE}.Release|x64.Build.0 = Release|x64 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Debug|Win32.ActiveCfg = Debug|Win32 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Debug|Win32.Build.0 = Debug|Win32 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Release|Win32.ActiveCfg = Release|Win32 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Release|Win32.Build.0 = Release|Win32 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Debug|x64.ActiveCfg = Debug|x64 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Debug|x64.Build.0 = Debug|x64 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Release|x64.ActiveCfg = Release|x64 - {ADCCB27A-E522-4367-86B9-9C9DF2636B93}.Release|x64.Build.0 = Release|x64 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Debug|Win32.ActiveCfg = Debug|Win32 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Debug|Win32.Build.0 = Debug|Win32 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Release|Win32.ActiveCfg = Release|Win32 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Release|Win32.Build.0 = Release|Win32 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Debug|x64.ActiveCfg = Debug|x64 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Debug|x64.Build.0 = Debug|x64 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Release|x64.ActiveCfg = Release|x64 - {837F98CF-D3A4-472C-BACC-47950340E57B}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {10E372EF-AE85-4528-919C-A261253EDDAE} = {0C11CE20-E0CC-403B-B957-FB72E3AD659A} - {ADCCB27A-E522-4367-86B9-9C9DF2636B93} = {FD04F724-4BA6-4E88-B269-53F28C44E2F2} - {837F98CF-D3A4-472C-BACC-47950340E57B} = {8FED241E-8771-423B-8ED2-EF4873FAED48} - EndGlobalSection -EndGlobal diff --git a/usb/umdf_filter_umdf/Package/package.VcxProj b/usb/umdf_filter_umdf/Package/package.VcxProj deleted file mode 100644 index e659f6f2b..000000000 --- a/usb/umdf_filter_umdf/Package/package.VcxProj +++ /dev/null @@ -1,90 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98} - - - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127} - - - - WindowsKernelModeDriver10.0 - Utility - Package - true - Debug - - - - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7} - {46304089-31EE-4493-8063-28C9498B0AA5} - $(MSBuildProjectName) - - - Windows10 - true - - - Windows10 - false - - - Windows10 - true - - - Windows10 - false - - - - - - - - - - - DbgengRemoteDebugger - False - None - - - - - - %PathToInf% - False - False - True - - 133563 - - - - sha256 - - - - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/Package/package.VcxProj.Filters b/usb/umdf_filter_umdf/Package/package.VcxProj.Filters deleted file mode 100644 index c76e39bb4..000000000 --- a/usb/umdf_filter_umdf/Package/package.VcxProj.Filters +++ /dev/null @@ -1,21 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {C029FC84-457F-450E-ADA9-6D80AE7CD763} - - - h;hpp;hxx;hm;inl;inc;xsd - {7D823922-0DAE-4B96-8DB9-0746C3D33ACA} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {C9031396-E1B6-4B90-94EC-0D504E07410E} - - - inf;inv;inx;mof;mc; - {3B2590BD-4AA9-4039-8CA3-4C189ACEF76A} - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/README.md b/usb/umdf_filter_umdf/README.md deleted file mode 100644 index b16d86869..000000000 --- a/usb/umdf_filter_umdf/README.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -page_type: sample -description: "Demonstrates how to load a UMDF filter driver as an upper filter driver above the umdf_fx2 sample driver." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Sample UMDF Filter above UMDF Function Driver for OSR USB-FX2 (UMDF Version 1) - -The umdf\_filter\_umdf sample demonstrates how to load a User-Mode Driver Framework (UMDF) filter driver as an upper filter driver above the umdf\_fx2 sample driver. - -This sample is written for the [OSR USB-FX2 Learning Kit](https://www.osronline.com/hardware/OSRFX2_32.pdf). - -## Overview - -- The device is based on the development board supplied with the Cypress EZ-USB FX2 Development Kit (CY3681). - -- It contains 1 interface and 3 endpoints (Interrupt IN, Bulk Out, Bulk IN). - -- Firmware supports vendor commands to query or set LED Bar graph display and 7-segment LED display, and to query toggle switch states. - -- Interrupt Endpoint: - - - Sends an 8-bit value that represents the state of the switches. - - - Sent on startup, resume from suspend, and whenever the switch pack setting changes. - - - Firmware does not de-bounce the switch pack. - - - One switch change can result in multiple bytes being sent. - - - Bits are in the reverse order of the labels on the pack (for example, bit 0x80 is labeled 1 on the pack). - -- Bulk Endpoints are configured for loopback: - - - The device moves data from IN endpoint to OUT endpoint. - - - The device does not change the values of the data it receives nor does it internally create any data. - - - Endpoints are always double buffered. - - - Maximum packet size depends on speed (64 full speed, 512 high speed). - -## Testing the driver - -You can test this sample either by using the [Custom driver access](https://go.microsoft.com/fwlink/p/?linkid=2114373) sample application, or by using the osrusbfx2.exe test application. For information on how to build and use the osrusbfx2.exe application, see the test instructions for the [umdf\_fx2](https://docs.microsoft.com/samples/microsoft/windows-driver-samples/sample-umdf-filter-above-umdf-function-driver-for-osr-usb-fx2-umdf-version-1/) sample. - -## Sample Contents - -| Folder | Description | -| --- | --- | -| usb\umdf_filter_umdf\umdf_driver | This directory contains source code for the umdf_fx2 sample driver. | -| usb\umdf_filter_umdf\umdf_filter | This directory contains the UMDF filter driver. | diff --git a/usb/umdf_filter_umdf/inc/WUDFOsrUsbPublic.h b/usb/umdf_filter_umdf/inc/WUDFOsrUsbPublic.h deleted file mode 100644 index 6681fa146..000000000 --- a/usb/umdf_filter_umdf/inc/WUDFOsrUsbPublic.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - WUDFOsrUsbPublic.h - -Abstract: - - This module contains the common declarations shared by driver - and user applications for the UMDF OSR device sample. - - Note that this driver does NOT use the same device interface GUID - as the KMDF OSR USB sample. - -Environment: - - user and kernel - ---*/ - -#pragma once - -// -// Define an Interface Guid so that app can find the device and talk to it. -// - -// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} -DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, - 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); - diff --git a/usb/umdf_filter_umdf/inc/list.h b/usb/umdf_filter_umdf/inc/list.h deleted file mode 100644 index 38d0b1e90..000000000 --- a/usb/umdf_filter_umdf/inc/list.h +++ /dev/null @@ -1,77 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - list.h - -Abstract: - - This module contains doubly linked list macros - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -FORCEINLINE -VOID -InitializeListHead( - IN PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -VOID -InsertHeadList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -InsertTailList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} diff --git a/usb/umdf_filter_umdf/inc/public.h b/usb/umdf_filter_umdf/inc/public.h deleted file mode 100644 index 2c3f6805c..000000000 --- a/usb/umdf_filter_umdf/inc/public.h +++ /dev/null @@ -1,217 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - public.h - -Abstract: - - Public definitions for the OSR_FX2 device operations. - -Environment: - - User & Kernel mode - ---*/ - -#ifndef _PUBLIC_H -#define _PUBLIC_H - -#include - -#include "WudfOsrUsbPublic.h" - - -// -// Define the structures that will be used by the IOCTL -// interface to the driver -// - -// -// BAR_GRAPH_STATE -// -// BAR_GRAPH_STATE is a bit field structure with each -// bit corresponding to one of the bar graph on the -// OSRFX2 Development Board -// -#include - -#pragma warning( push ) -#pragma warning( disable : 4201 ) // nameless struct/union -#pragma warning( disable : 4214 ) // bit-field type other than int - -typedef struct _BAR_GRAPH_STATE { - - union { - - struct { - // - // Individual bars starting from the - // top of the stack of bars - // - // NOTE: There are actually 10 bars, - // but the very top two do not light - // and are not counted here - // - UCHAR Bar1 : 1; - UCHAR Bar2 : 1; - UCHAR Bar3 : 1; - UCHAR Bar4 : 1; - UCHAR Bar5 : 1; - UCHAR Bar6 : 1; - UCHAR Bar7 : 1; - UCHAR Bar8 : 1; - }; - - // - // The state of all the bar graph as a single - // UCHAR - // - UCHAR BarsAsUChar; - - }; - -}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; - -// -// SWITCH_STATE -// -// SWITCH_STATE is a bit field structure with each -// bit corresponding to one of the switches on the -// OSRFX2 Development Board -// -typedef struct _SWITCH_STATE { - - union { - struct { - // - // Individual switches starting from the - // left of the set of switches - // - UCHAR Switch1 : 1; - UCHAR Switch2 : 1; - UCHAR Switch3 : 1; - UCHAR Switch4 : 1; - UCHAR Switch5 : 1; - UCHAR Switch6 : 1; - UCHAR Switch7 : 1; - UCHAR Switch8 : 1; - }; - - // - // The state of all the switches as a single - // UCHAR - // - UCHAR SwitchesAsUChar; - - }; - - -}SWITCH_STATE, *PSWITCH_STATE; - -// -// Seven segment display bit values. -// - -// -// Undefine conflicting MFC constant -// -#undef SS_CENTER -#undef SS_LEFT -#undef SS_RIGHT - -#define SS_TOP 0x01 -#define SS_TOP_LEFT 0x40 -#define SS_TOP_RIGHT 0x02 -#define SS_CENTER 0x20 -#define SS_BOTTOM_LEFT 0x10 -#define SS_BOTTOM_RIGHT 0x04 -#define SS_BOTTOM 0x80 -#define SS_DOT 0x08 - -// -// FILE_PLAYBACK -// -// FILE_PLAYBACK structure contains the parameters for the PLAY_FILE I/O Control. -// - -typedef struct _FILE_PLAYBACK -{ - // - // The delay between changes in the display, in milliseconds. - // - - USHORT Delay; - - // - // The data file path. - // - - WCHAR Path[1]; -} FILE_PLAYBACK, *PFILE_PLAYBACK; - -#include - -#define IOCTL_INDEX 0x800 -#define FILE_DEVICE_OSRUSBFX2 65500U - -#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 1, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 3, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 4, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 5, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - - -#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 6, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 7, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 8, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 9, \ - METHOD_OUT_DIRECT, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_PLAY_FILE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 10, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#pragma warning(pop) - -#endif - diff --git a/usb/umdf_filter_umdf/inc/usb_hw.h b/usb/umdf_filter_umdf/inc/usb_hw.h deleted file mode 100644 index d6e983f1a..000000000 --- a/usb/umdf_filter_umdf/inc/usb_hw.h +++ /dev/null @@ -1,233 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Usb.h - -Abstract: - - Contains prototypes for interfacing with a USB connected device. These - are copied from the KMDF WDFUSB.H header file (but with the WDF specific - portions removed) - -Environment: - - kernel mode only - ---*/ - -#pragma once - -typedef enum _WINUSB_BMREQUEST_DIRECTION { - BmRequestHostToDevice = BMREQUEST_HOST_TO_DEVICE, - BmRequestDeviceToHost = BMREQUEST_DEVICE_TO_HOST, -} WINUSB_BMREQUEST_DIRECTION; - -typedef enum _WINUSB_BMREQUEST_TYPE { - BmRequestStandard = BMREQUEST_STANDARD, - BmRequestClass = BMREQUEST_CLASS, - BmRequestVendor = BMREQUEST_VENDOR, -} WINUSB_BMREQUEST_TYPE; - -typedef enum _WINUSB_BMREQUEST_RECIPIENT { - BmRequestToDevice = BMREQUEST_TO_DEVICE, - BmRequestToInterface = BMREQUEST_TO_INTERFACE, - BmRequestToEndpoint = BMREQUEST_TO_ENDPOINT, - BmRequestToOther = BMREQUEST_TO_OTHER, -} WINUSB_BMREQUEST_RECIPIENT; - -typedef enum _WINUSB_DEVICE_TRAITS { - WINUSB_DEVICE_TRAIT_SELF_POWERED = 0x00000001, - WINUSB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE = 0x00000002, - WINUSB_DEVICE_TRAIT_AT_HIGH_SPEED = 0x00000004, -} WINUSB_DEVICE_TRAITS; - -typedef enum _WdfUsbTargetDeviceSelectInterfaceType { - WdfUsbTargetDeviceSelectInterfaceTypeInterface = 0x10, - WdfUsbTargetDeviceSelectInterfaceTypeUrb = 0x11, -} WdfUsbTargetDeviceSelectInterfaceType; - - - -typedef union _WINUSB_CONTROL_SETUP_PACKET { - struct { - union { - #pragma warning(disable:4214) // bit field types other than int - struct { - // - // Valid values are BMREQUEST_TO_DEVICE, BMREQUEST_TO_INTERFACE, - // BMREQUEST_TO_ENDPOINT, BMREQUEST_TO_OTHER - // - BYTE Recipient:2; - - BYTE Reserved:3; - - // - // Valid values are BMREQUEST_STANDARD, BMREQUEST_CLASS, - // BMREQUEST_VENDOR - // - BYTE Type:2; - - // - // Valid values are BMREQUEST_HOST_TO_DEVICE, - // BMREQUEST_DEVICE_TO_HOST - // - BYTE Dir:1; - } Request; - #pragma warning(default:4214) // bit field types other than int - BYTE Byte; - } bm; - - BYTE bRequest; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wValue; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wIndex; - - USHORT wLength; - } Packet; - - struct { - BYTE Bytes[8]; - } Generic; - - WINUSB_SETUP_PACKET WinUsb; - -} WINUSB_CONTROL_SETUP_PACKET, *PWINUSB_CONTROL_SETUP_PACKET; - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_CLASS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestClass; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_VENDOR( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestVendor; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_FEATURE( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT FeatureSelector, - USHORT Index, - BOOLEAN SetFeature - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestHostToDevice; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - if (SetFeature) { - Packet->Packet.bRequest = USB_REQUEST_SET_FEATURE; - } - else { - Packet->Packet.bRequest = USB_REQUEST_CLEAR_FEATURE; - } - - Packet->Packet.wValue.Value = FeatureSelector; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_GET_STATUS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestDeviceToHost; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - Packet->Packet.bRequest = USB_REQUEST_GET_STATUS; - Packet->Packet.wIndex.Value = Index; - Packet->Packet.wValue.Value = 0; - - // Packet->Packet.wLength will be set by the formatting function -} - diff --git a/usb/umdf_filter_umdf/umdf_driver/ControlQueue.cpp b/usb/umdf_filter_umdf/umdf_driver/ControlQueue.cpp deleted file mode 100644 index f4058941f..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/ControlQueue.cpp +++ /dev/null @@ -1,564 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "winioctl.h" - -#include "ControlQueue.tmh" - -CMyControlQueue::CMyControlQueue( - _In_ PCMyDevice Device - ) : CMyQueue(Device) -{ - -} - -HRESULT -STDMETHODCALLTYPE -CMyControlQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDeviceIoControl(); - - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyControlQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyControlQueue queue = NULL; - HRESULT hr = S_OK; - - queue = new CMyControlQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyControlQueue::Initialize( - VOID - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - // - // The framework (UMDF) will not deliver a - // request to the driver that arrives on a power-managed queue, unless - // the device is in a powered-up state. If you receive a request on a - // power-managed queue after the device has idled out, - // the framework will not be able to power-up and present the request - // to the driver unless it is the power policy owner (PPO). - // Since this driver is the PPO it can use power managed queues - // - - hr = __super::Initialize(WdfIoQueueDispatchSequential, - false, - true /* use power managed queue */); - - // - // return the status. - // - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyControlQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *FxQueue, - _In_ IWDFIoRequest *FxRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Aruments: - - FxQueue - Framework Queue instance - FxRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Lenth of input buffer - OutputBufferSizeInBytes - Lenth of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - IWDFMemory *memory = NULL; - PVOID buffer; - - SIZE_T bigBufferCb; - - ULONG information = 0; - - bool completeRequest = true; - - HRESULT hr = S_OK; - - switch (ControlCode) - { - case IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR: - { - // - // Get the output buffer. - // - - FxRequest->GetOutputMemory(&memory ); - - // - // request the descriptor. - // - - ULONG bufferCb; - - // - // Get the buffer address then release the memory object. - // The memory object remains valid until the request is - // completed. - // - - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - if (bigBufferCb > ULONG_MAX) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - break; - } - else - { - bufferCb = (ULONG) bigBufferCb; - } - - hr = m_Device->GetUsbTargetDevice()->RetrieveDescriptor( - USB_CONFIGURATION_DESCRIPTOR_TYPE, - 0, - 0, - &bufferCb, - (PUCHAR) buffer - ); - - if (SUCCEEDED(hr)) - { - information = bufferCb; - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the result of the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->GetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - // - // If that worked then record how many bytes of data we're - // returning. - // - - if (SUCCEEDED(hr)) - { - information = sizeof(BAR_GRAPH_STATE); - } - - break; - } - - case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the result of the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(SEVEN_SEGMENT)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - hr = m_Device->GetSevenSegmentDisplay((PSEVEN_SEGMENT) buffer); - } - - // - // If that worked then record how many bytes of data we're - // returning. - // - - if (SUCCEEDED(hr)) - { - information = sizeof(SEVEN_SEGMENT); - } - - break; - } - - case IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(SEVEN_SEGMENT)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory ); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetSevenSegmentDisplay((PSEVEN_SEGMENT) buffer); - } - break; - } - - case IOCTL_OSRUSBFX2_READ_SWITCHES: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(SWITCH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->ReadSwitchState((PSWITCH_STATE) buffer); - } - - if (SUCCEEDED(hr)) - { - information = sizeof(SWITCH_STATE); - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE: - { - // - // Make sure the buffer is big enough to hold the switch - // state. - // - - if (OutputBufferSizeInBytes < sizeof(SWITCH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - // - // Forward the request to the switch state change queue. - // - - hr = FxRequest->ForwardToIoQueue( - m_Device->GetSwitchChangeQueue() - ); - - if (SUCCEEDED(hr)) - { - completeRequest = false; - } - } - - break; - } - - case IOCTL_OSRUSBFX2_RESET_DEVICE: - case IOCTL_OSRUSBFX2_REENUMERATE_DEVICE: - { - // - // WinUSB does not allow us to reset or re-enumerate the device. - // Return not-supported for the error in both of these cases. - // - - hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - break; - } - - case IOCTL_OSRUSBFX2_PLAY_FILE: - { - // - // This IOCTL demonstrates how to use impersonation to access - // resources using the credentials provided by the client. Note - // that for impersonation to work it has to be enabled in the device - // INF and the client must allow impersonation when they open the - // device. - // - // This IOCTL opens a file using the path provided by the client - // and then plays the characters in that file out to the seven segment - // display in a worker thread. - // - - PFILE_PLAYBACK playback; - SIZE_T playbackCb; - size_t realPlaybackCb; - - FxRequest->GetInputMemory(&memory); - - if (memory == NULL) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Get the playback structure from the input buffer. - // - - playback = (PFILE_PLAYBACK) memory->GetDataBuffer(&playbackCb); - - memory->Release(); - - // - // Make sure the length is at least as big as the fixed portion - // of the input structure. - // - - if (playbackCb < (FIELD_OFFSET(FILE_PLAYBACK, Path))) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Make sure the file name is at least one character long. - // - - playbackCb -= FIELD_OFFSET(FILE_PLAYBACK, Path); - - if (playbackCb < sizeof(WCHAR)) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Verify that the string provided is valid. - // - - hr = StringCbLength(playback->Path, - min(playbackCb, (STRSAFE_MAX_CCH * sizeof(WCHAR))), - &realPlaybackCb); - - if (FAILED(hr)) - { - break; - } - - hr = m_Device->PlaybackFile(playback, FxRequest); - - break; - } - - - - default: - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION); - break; - } - } - - if (completeRequest) - { - FxRequest->CompleteWithInformation(hr, information); - } - - return; -} diff --git a/usb/umdf_filter_umdf/umdf_driver/ControlQueue.h b/usb/umdf_filter_umdf/umdf_driver/ControlQueue.h deleted file mode 100644 index 251521e1b..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/ControlQueue.h +++ /dev/null @@ -1,101 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.h - -Abstract: - - This file defines the queue callback object for handling device I/O - control requests. This is a serialized queue. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyControlQueue : public IQueueCallbackDeviceIoControl, - public CMyQueue -{ - HRESULT - Initialize( - VOID - ); - -public: - - CMyControlQueue( - _In_ PCMyDevice Device - ); - - virtual - ~CMyControlQueue( - VOID - ) - { - return; - } - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // - // IQueueCallbackDeviceIoControl - // - STDMETHOD_ (void, OnDeviceIoControl)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); -}; - diff --git a/usb/umdf_filter_umdf/umdf_driver/Device.cpp b/usb/umdf_filter_umdf/umdf_driver/Device.cpp deleted file mode 100644 index 101b3b796..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/Device.cpp +++ /dev/null @@ -1,2091 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 driver's - device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" -#include - -#include "device.tmh" -#define CONCURRENT_READS 2 - -CMyDevice::~CMyDevice( - ) -{ - SAFE_RELEASE(m_pIoTargetInterruptPipeStateMgmt); -} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR Fx2 driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice2 *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: If you're writing a filter driver then indicate that here. - // And then don't claim power policy ownership below - // - // FxDeviceInit->SetFilter(); - // - - // - // Set the Fx2 driver as the power policy owner. - // - - FxDeviceInit->SetPowerPolicyOwnership(TRUE); - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - IWDFDevice* device1; - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &device1); - - // - // Convert the interface to version 2 - // - - if (SUCCEEDED(hr)) { - device1->QueryInterface(IID_PPV_ARGS(&fxDevice)); - _Analysis_assume_(fxDevice != NULL); - device1->Release(); - } - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - // - // Get the bus type GUID for the device and confirm that we're attached to - // USB. - // - // NOTE: Since this device only supports USB we'd normally trust our INF - // to ensure this. - // - // But if the device also supported 1394 then we could - // use this to determine which type of bus we were attached to. - // - - hr = GetBusTypeGuid(); - - if (FAILED(hr)) - { - return hr; - } - - // - // Create the read-write queue. - // - - hr = CMyReadWriteQueue::CreateInstance(this, &m_ReadWriteQueue); - - if (FAILED(hr)) - { - return hr; - } - - // - // We use default queue for read/write - // - - hr = m_ReadWriteQueue->Configure(); - - m_ReadWriteQueue->Release(); - - // - // Create the control queue and configure forwarding for IOCTL requests. - // - - if (SUCCEEDED(hr)) - { - hr = CMyControlQueue::CreateInstance(this, &m_ControlQueue); - - if (SUCCEEDED(hr)) - { - hr = m_ControlQueue->Configure(); - if (SUCCEEDED(hr)) - { - m_FxDevice->ConfigureRequestDispatching( - m_ControlQueue->GetFxQueue(), - WdfRequestDeviceIoControl, - true - ); - } - m_ControlQueue->Release(); - } - } - - // - // Create a manual I/O queue to hold requests for notification when - // the switch state changes. - // - - hr = m_FxDevice->CreateIoQueue(NULL, - FALSE, - WdfIoQueueDispatchManual, - FALSE, - FALSE, - &m_SwitchChangeQueue); - - - // - // Release creation reference as object tree will keep a reference - // - - m_SwitchChangeQueue->Release(); - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_OSRUSBFX2, - NULL); - } - - // - // Mark the interface as restricted to allow access to applications bound - // using device metadata. Failures here are not fatal so we log them but - // ignore them otherwise. - // - if (SUCCEEDED(hr)) - { - WDF_PROPERTY_STORE_ROOT RootSpecifier; - IWDFUnifiedPropertyStoreFactory * pUnifiedPropertyStoreFactory = NULL; - IWDFUnifiedPropertyStore * pUnifiedPropertyStore = NULL; - DEVPROP_BOOLEAN isRestricted = DEVPROP_TRUE; - HRESULT hrSetProp; - - hrSetProp = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pUnifiedPropertyStoreFactory)); - - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrSetProp)); - - RootSpecifier.LengthCb = sizeof(RootSpecifier); - RootSpecifier.RootClass = WdfPropertyStoreRootClassDeviceInterfaceKey; - RootSpecifier.Qualifier.DeviceInterfaceKey.InterfaceGUID = &GUID_DEVINTERFACE_OSRUSBFX2; - RootSpecifier.Qualifier.DeviceInterfaceKey.ReferenceString = NULL; - - hrSetProp = pUnifiedPropertyStoreFactory->RetrieveUnifiedDevicePropertyStore(&RootSpecifier, - &pUnifiedPropertyStore); - - if (SUCCEEDED(hrSetProp)) - { - hrSetProp = pUnifiedPropertyStore->SetPropertyData(&DEVPKEY_DeviceInterface_Restricted, - 0, // Lcid - 0, // Flags - DEVPROP_TYPE_BOOLEAN, - sizeof(isRestricted), - &isRestricted); - } - - if (FAILED(hrSetProp)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Could not set restricted property %!HRESULT!", - hrSetProp - ); - } - - SAFE_RELEASE(pUnifiedPropertyStoreFactory); - SAFE_RELEASE(pUnifiedPropertyStore); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackHardware))) - { - *Object = QueryIPnpCallbackHardware(); - hr = S_OK; - } - else if (IsEqualIID(InterfaceId, __uuidof(IPnpCallback))) - { - *Object = QueryIPnpCallback(); - hr = S_OK; - } - else if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackSelfManagedIo))) - { - *Object = QueryIPnpCallbackSelfManagedIo(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IUsbTargetPipeContinuousReaderCallbackReadersFailed))) - { - *Object = QueryContinousReaderFailureCompletion(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IUsbTargetPipeContinuousReaderCallbackReadComplete))) - { - *Object = QueryContinousReaderCompletion(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnPrepareHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked to ready the driver - to talk to hardware. It opens the handle to the - device and talks to it using the WINUSB interface. - It invokes WINUSB to discver the interfaces and stores - the information related to bulk endpoints. - -Arguments: - - FxDevice : Pointer to the WDF device interface - -Return Value: - - HRESULT - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - // - // Get the device name. - // Get the length to allocate first - // - - hr = m_FxDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!HRESULT!", - hr - ); - } - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Device name %S", - deviceName - ); - } - - // - // Create USB I/O Targets and configure them - // - - if (SUCCEEDED(hr)) - { - hr = CreateUsbIoTargets(); - } - - if (SUCCEEDED(hr)) - { - ULONG length = sizeof(m_Speed); - - hr = m_pIUsbTargetDevice->RetrieveDeviceInformation(DEVICE_SPEED, - &length, - &m_Speed); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb device speed information %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Speed - %x\n", - m_Speed - ); - } - - if (SUCCEEDED(hr)) - { - hr = ConfigureUsbPipes(); - } - - // Setup power-management settings on the device. - // - - if (SUCCEEDED(hr)) - { - hr = SetPowerManagement(); - } - - // - // - // Clear the seven segement display to indicate that we're done with - // prepare hardware. - // - - if (SUCCEEDED(hr)) - { - hr = IndicateDeviceReady(); - } - - if (SUCCEEDED(hr)) - { - hr = ConfigContReaderForInterruptEndPoint(); - } - - delete[] deviceName; - - return hr; -} - -HRESULT -CMyDevice::OnReleaseHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. - -Arguments: - - FxDevice - Pointer to the Device object. - -Return Value: - - HRESULT - Always succeeds. - ---*/ -{ - // - // Delete USB Target Device WDF Object, this will in turn - // delete all the children - interface and the pipe objects - // - // This makes sure that - // 1. We drain the the pending read which does not come from an I/O queue - // 2. We remove USB target objects from object tree (and thereby free them) - // before any potential subsequent OnPrepareHardware creates new ones - // - // m_pIUsbTargetDevice could be NULL if OnPrepareHardware failed so we need - // to guard against that - // - - if (m_pIUsbTargetDevice) - { - m_pIUsbTargetDevice->DeleteWdfObject(); - } - - return S_OK; -} - -HRESULT -CMyDevice::CreateUsbIoTargets( - ) -/*++ - -Routine Description: - - This routine creates Usb device, interface and pipe objects - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr; - UCHAR NumEndPoints = 0; - IWDFUsbTargetFactory * pIUsbTargetFactory = NULL; - IWDFUsbTargetDevice * pIUsbTargetDevice = NULL; - IWDFUsbInterface * pIUsbInterface = NULL; - IWDFUsbTargetPipe * pIUsbPipe = NULL; - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pIUsbTargetFactory)); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb target factory %!HRESULT!", - hr - ); - } - - if (SUCCEEDED(hr)) - { - hr = pIUsbTargetFactory->CreateUsbTargetDevice( - &pIUsbTargetDevice); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to create USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbTargetDevice = pIUsbTargetDevice; - - // - // Release the creation reference as object tree will maintain a reference - // - - pIUsbTargetDevice->Release(); - } - } - - if (SUCCEEDED(hr)) - { - UCHAR NumInterfaces = pIUsbTargetDevice->GetNumInterfaces(); - - WUDF_TEST_DRIVER_ASSERT(1 == NumInterfaces); - - hr = pIUsbTargetDevice->RetrieveUsbInterface(0, &pIUsbInterface); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB interface from USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbInterface = pIUsbInterface; - - pIUsbInterface->Release(); //release creation reference - } - } - - if (SUCCEEDED(hr)) - { - NumEndPoints = pIUsbInterface->GetNumEndPoints(); - - if (NumEndPoints != NUM_OSRUSB_ENDPOINTS) { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Has %d endpoints, expected %d, returning %!HRESULT! ", - NumEndPoints, - NUM_OSRUSB_ENDPOINTS, - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - for (UCHAR PipeIndex = 0; PipeIndex < NumEndPoints; PipeIndex++) - { - hr = pIUsbInterface->RetrieveUsbPipeObject(PipeIndex, - &pIUsbPipe); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB Pipe for PipeIndex %d, %!HRESULT!", - PipeIndex, - hr - ); - } - else - { - if ( pIUsbPipe->IsInEndPoint() ) - { - if ( UsbdPipeTypeInterrupt == pIUsbPipe->GetType() ) - { - m_pIUsbInterruptPipe = pIUsbPipe; - - WUDF_TEST_DRIVER_ASSERT (m_pIoTargetInterruptPipeStateMgmt == NULL); - - hr = m_pIUsbInterruptPipe->QueryInterface(__uuidof( - IWDFIoTargetStateManagement), - reinterpret_cast(&m_pIoTargetInterruptPipeStateMgmt) - ); - if (FAILED(hr)) - { - m_pIoTargetInterruptPipeStateMgmt = NULL; - } - } - else if ( UsbdPipeTypeBulk == pIUsbPipe->GetType() ) - { - m_pIUsbInputPipe = pIUsbPipe; - } - else - { - pIUsbPipe->DeleteWdfObject(); - } - } - else if ( pIUsbPipe->IsOutEndPoint() && (UsbdPipeTypeBulk == pIUsbPipe->GetType()) ) - { - m_pIUsbOutputPipe = pIUsbPipe; - } - else - { - pIUsbPipe->DeleteWdfObject(); - } - - SAFE_RELEASE(pIUsbPipe); //release creation reference - } - } - - if (NULL == m_pIUsbInputPipe || NULL == m_pIUsbOutputPipe) - { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Input or output pipe not found, returning %!HRESULT!", - hr - ); - } - } - - SAFE_RELEASE(pIUsbTargetFactory); - - return hr; -} - -HRESULT -CMyDevice::ConfigureUsbPipes( - ) -/*++ - -Routine Description: - - This routine retrieves the IDs for the bulk end points of the USB device. - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr = S_OK; - LONG timeout; - - // - // Set timeout policies for input/output pipes - // - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbInputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for input pipe %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbOutputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for output pipe %!HRESULT!", - hr - ); - } - } - - return hr; -} - -HRESULT -CMyDevice::IndicateDeviceReady( - VOID - ) -/*++ - - Routine Description: - - This method lights the period on the device's seven-segment display to - indicate that the driver's PrepareHardware method has completed. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - SEVEN_SEGMENT display = {0}; - - HRESULT hr; - - // - // First read the contents of the seven segment display. - // - - hr = GetSevenSegmentDisplay(&display); - - if (SUCCEEDED(hr)) - { - display.Segments |= 0x08; - - hr = SetSevenSegmentDisplay(&display); - } - - return hr; -} - -HRESULT -CMyDevice::GetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the contents of the buffer - the controller OR's in every - // light that's set. - // - - BarGraphState->BarsAsUChar = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesTransferred - ); - - - return hr; -} - -HRESULT -CMyDevice::GetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the output buffer - the device will or in the bits for - // the lights that are set. - // - - SevenSegment->Segments = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_7SEGMENT_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SevenSegment, - sizeof(SEVEN_SEGMENT), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_7SEGMENT_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SevenSegment, - sizeof(SEVEN_SEGMENT), - &bytesTransferred - ); - - return hr; -} - -HRESULT -CMyDevice::ReadSwitchState( - _In_ PSWITCH_STATE SwitchState - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the output buffer - the device will or in the bits for - // the lights that are set. - // - - SwitchState->SwitchesAsUChar = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_SWITCHES, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SwitchState, - sizeof(SWITCH_STATE), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ) -{ - HRESULT hr = S_OK; - HRESULT hrRequest = S_OK; - IWDFIoRequest *pWdfRequest = NULL; - IWDFDriver * FxDriver = NULL; - IWDFMemory * FxMemory = NULL; - IWDFRequestCompletionParams * FxComplParams = NULL; - IWDFUsbRequestCompletionParams * FxUsbComplParams = NULL; - - *LengthTransferred = 0; - - hr = m_FxDevice->CreateRequest( NULL, //pCallbackInterface - NULL, //pParentObject - &pWdfRequest); - hrRequest = hr; - - if (SUCCEEDED(hr)) - { - m_FxDevice->GetDriver(&FxDriver); - - hr = FxDriver->CreatePreallocatedWdfMemory( Buffer, - BufferLength, - NULL, //pCallbackInterface - pWdfRequest, //pParetObject - &FxMemory ); - } - - if (SUCCEEDED(hr)) - { - hr = m_pIUsbTargetDevice->FormatRequestForControlTransfer( pWdfRequest, - SetupPacket, - FxMemory, - NULL); //TransferOffset - } - - if (SUCCEEDED(hr)) - { - hr = pWdfRequest->Send( m_pIUsbTargetDevice, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - 0); //Timeout - } - - if (SUCCEEDED(hr)) - { - pWdfRequest->GetCompletionParams(&FxComplParams); - - hr = FxComplParams->GetCompletionStatus(); - } - - if (SUCCEEDED(hr)) - { - HRESULT hrQI = FxComplParams->QueryInterface(IID_PPV_ARGS(&FxUsbComplParams)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - WUDF_TEST_DRIVER_ASSERT( WdfUsbRequestTypeDeviceControlTransfer == - FxUsbComplParams->GetCompletedUsbRequestType() ); - - FxUsbComplParams->GetDeviceControlTransferParameters( NULL, - LengthTransferred, - NULL, - NULL ); - } - - SAFE_RELEASE(FxUsbComplParams); - SAFE_RELEASE(FxComplParams); - SAFE_RELEASE(FxMemory); - - if (SUCCEEDED(hrRequest)) - { - pWdfRequest->DeleteWdfObject(); - } - SAFE_RELEASE(pWdfRequest); - - SAFE_RELEASE(FxDriver); - - return hr; -} - -WDF_IO_TARGET_STATE -CMyDevice::GetTargetState( - IWDFIoTarget * pTarget - ) -{ - IWDFIoTargetStateManagement * pStateMgmt = NULL; - WDF_IO_TARGET_STATE state; - - HRESULT hrQI = pTarget->QueryInterface(IID_PPV_ARGS(&pStateMgmt)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pStateMgmt)); - - state = pStateMgmt->GetState(); - - SAFE_RELEASE(pStateMgmt); - - return state; -} - -VOID -CMyDevice::ServiceSwitchChangeQueue( - _In_ SWITCH_STATE NewState, - _In_ HRESULT CompletionStatus, - _In_opt_ IWDFFile *SpecificFile - ) -/*++ - - Routine Description: - - This method processes switch-state change notification requests as - part of reading the OSR device's interrupt pipe. As each read completes - this pulls all pending I/O off the switch change queue and completes - each request with the current switch state. - - Arguments: - - NewState - the state of the switches - - CompletionStatus - all pending operations are completed with this status. - - SpecificFile - if provided only requests for this file object will get - completed. - - Return Value: - - None - ---*/ -{ - IWDFIoRequest *fxRequest; - - HRESULT enumHr = S_OK; - - do - { - HRESULT hr; - - // - // Get the next request. - // - - if (NULL != SpecificFile) - { - enumHr = m_SwitchChangeQueue->RetrieveNextRequestByFileObject( - SpecificFile, - &fxRequest - ); - } - else - { - enumHr = m_SwitchChangeQueue->RetrieveNextRequest(&fxRequest); - } - - // - // if we got one then complete it. - // - - if (SUCCEEDED(enumHr)) - { - if (SUCCEEDED(CompletionStatus)) - { - IWDFMemory *fxMemory; - - // - // First copy the result to the request buffer. - // - - fxRequest->GetOutputMemory(&fxMemory ); - - hr = fxMemory->CopyFromBuffer(0, - &NewState, - sizeof(SWITCH_STATE)); - fxMemory->Release(); - } - else - { - hr = CompletionStatus; - } - - // - // Complete the request with the status of the copy (or the completion - // status if that was an error). - // - - if (SUCCEEDED(hr)) - { - fxRequest->CompleteWithInformation(hr, sizeof(SWITCH_STATE)); - } - else - { - fxRequest->Complete(hr); - } - - fxRequest->Release(); - } - } - while (SUCCEEDED(enumHr)); -} - -HRESULT -CMyDevice::SetPowerManagement( - VOID - ) -/*++ - - Routine Description: - - This method enables the idle and wake functionality - using UMDF. UMDF has been set as the power policy - owner (PPO) for the device stack and we are using power - managed queues. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - HRESULT hr; - - // - // Enable USB selective suspend on the device. - // - - hr = m_FxDevice->AssignS0IdleSettings( IdleUsbSelectiveSuspend, - PowerDeviceMaximum, - IDLE_TIMEOUT_IN_MSEC, - IdleAllowUserControl, - WdfUseDefault); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to assign S0 idle settings for the device %!HRESULT!", - hr - ); - } - - // - // Enable Sx wake settings - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->AssignSxWakeSettings( PowerDeviceMaximum, - WakeAllowUserControl, - WdfUseDefault); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set Sx Wake Settings for the device %!HRESULT!", - hr - ); - } - - } - - - return hr; -} - -HRESULT -CMyDevice::OnD0Entry( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - UNREFERENCED_PARAMETER(previousState); - - // - // Start/Stop the I/O target if you support a continuous reader. - // The rest of the I/O is fed through power managed queues. The queue - // itself will stop feeding I/O to targets (and will wait for any pending - // I/O to complete before going into low power state), hence targets - // don�t need to be stopped/started. The continuous reader I/O is outside - // of power managed queues so we need to Stop the I/O target on D0Exit and - // start it on D0Entry. Please note that bulk pipe target doesn't need to - // be stopped/started because I/O submitted to this pipe comes from power - // managed I/O queue, which delivers I/O only in power on state. - // - - m_pIoTargetInterruptPipeStateMgmt->Start(); - - return S_OK; -} - -HRESULT -CMyDevice::OnD0Exit( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - UNREFERENCED_PARAMETER(previousState); - - // - // Stop the I/O target always succeedes. - // - m_pIoTargetInterruptPipeStateMgmt->Stop(WdfIoTargetCancelSentIo); - return S_OK; -} - -void -CMyDevice::OnSurpriseRemoval( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return; -} - -HRESULT -CMyDevice::OnQueryRemove( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnQueryStop( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -// -// Self Managed Io Callbacks -// - -VOID -CMyDevice::OnSelfManagedIoCleanup( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return; -} - -VOID -CMyDevice::OnSelfManagedIoFlush( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - - // - // Complete every switch change operation with an error. - // - ServiceSwitchChangeQueue(m_SwitchState, - HRESULT_FROM_WIN32(ERROR_DEVICE_REMOVED), - NULL); - - return; -} - -HRESULT -CMyDevice::OnSelfManagedIoInit( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoRestart( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoStop( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoSuspend( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - - - -HRESULT -CMyDevice::ConfigContReaderForInterruptEndPoint( - VOID - ) -/*++ - -Routine Description: - - This routine configures a continuous reader on the - interrupt endpoint. It's called from the PrepareHarware event. - -Arguments: - - -Return Value: - - HRESULT value - ---*/ -{ - HRESULT hr, hrQI; - IUsbTargetPipeContinuousReaderCallbackReadComplete *pOnCompletionCallback = NULL; - IUsbTargetPipeContinuousReaderCallbackReadersFailed *pOnFailureCallback= NULL; - IWDFUsbTargetPipe2 * pIUsbInterruptPipe2; - - hrQI = this->QueryInterface(IID_PPV_ARGS(&pOnCompletionCallback)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pOnCompletionCallback)); - - hrQI = this->QueryInterface(IID_PPV_ARGS(&pOnFailureCallback)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pOnFailureCallback)); - - hrQI = m_pIUsbInterruptPipe->QueryInterface(IID_PPV_ARGS(&pIUsbInterruptPipe2)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pIUsbInterruptPipe2)); - - // - // Reader requests are not posted to the target automatically. - // Driver must explictly call WdfIoTargetStart to kick start the - // reader. In this sample, it's done in D0Entry. - // By defaut, framework queues two requests to the target - // endpoint. Driver can configure up to 10 requests with the - // parameter CONCURRENT_READS - // - hr = pIUsbInterruptPipe2->ConfigureContinuousReader( sizeof(m_SwitchStateBuffer), - 0,//header - 0,//trailer - CONCURRENT_READS, - NULL, - pOnCompletionCallback, - m_pIUsbInterruptPipe, - pOnFailureCallback - ); - - if (FAILED(hr)) { - TraceEvents(TRACE_LEVEL_ERROR, TEST_TRACE_DEVICE, - "OsrFxConfigContReaderForInterruptEndPoint failed %!HRESULT!", - hr); - } - - SAFE_RELEASE(pOnCompletionCallback); - SAFE_RELEASE(pOnFailureCallback); - SAFE_RELEASE(pIUsbInterruptPipe2); - - return hr; -} - - -BOOL -CMyDevice::OnReaderFailure( - IWDFUsbTargetPipe * pPipe, - HRESULT hrCompletion - ) -{ - UNREFERENCED_PARAMETER(pPipe); - - m_InterruptReadProblem = hrCompletion; - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Failure completed with %!HRESULT!", - hrCompletion - ); - - ServiceSwitchChangeQueue(m_SwitchState, - hrCompletion, - NULL); - - return TRUE; -} - -VOID -CMyDevice::OnReaderCompletion( - IWDFUsbTargetPipe * pPipe, - IWDFMemory * pMemory, - SIZE_T NumBytesTransferred, - PVOID Context - ) -{ - WUDF_TEST_DRIVER_ASSERT(pPipe == (IWDFUsbTargetPipe *)Context); - - // - // Make sure that there is data in the read packet. Depending on the device - // specification, it is possible for it to return a 0 length read in - // certain conditions. - // - - if (NumBytesTransferred == 0) { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Zero length read occured on the Interrupt Pipe's " - "Continuous Reader\n" - ); - return; - } - - WUDF_TEST_DRIVER_ASSERT(NumBytesTransferred == sizeof(m_SwitchState)); - - // - // Get the switch state - // - - PVOID pBuff = pMemory->GetDataBuffer(NULL); - - CopyMemory(&m_SwitchState, pBuff, sizeof(m_SwitchState)); - - - // - // Satisfy application request for switch change notification - // - - ServiceSwitchChangeQueue(m_SwitchState, - S_OK, - NULL); - - // - // Make sure that the request that got completed is the one that we reuse - // Don't Delete the request because it gets reused - // -} - - -HRESULT -CMyDevice::GetBusTypeGuid( - VOID - ) -/*++ - - Routine Description: - - This routine gets the device instance ID then invokes SetupDi to - retrieve the bus type guid for the device. The bus type guid is - stored in object. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - ULONG instanceIdCch = 0; - PWSTR instanceId = NULL; - - HDEVINFO deviceInfoSet = NULL; - SP_DEVINFO_DATA deviceInfo = {sizeof(SP_DEVINFO_DATA)}; - - HRESULT hr; - - // - // Retrieve the device instance ID. - // - - hr = m_FxDevice->RetrieveDeviceInstanceId(NULL, &instanceIdCch); - - if (FAILED(hr)) - { - goto Exit; - } - - instanceId = new WCHAR[instanceIdCch]; - - if (instanceId == NULL) - { - hr = E_OUTOFMEMORY; - goto Exit; - } - - hr = m_FxDevice->RetrieveDeviceInstanceId(instanceId, &instanceIdCch); - - if (FAILED(hr)) - { - goto Exit2; - } - - // - // Call SetupDI to open the device info. - // - - deviceInfoSet = SetupDiCreateDeviceInfoList(NULL, NULL); - - if (deviceInfoSet == INVALID_HANDLE_VALUE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit2; - } - - if (SetupDiOpenDeviceInfo(deviceInfoSet, - instanceId, - NULL, - 0, - &deviceInfo) == FALSE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit3; - } - - if (SetupDiGetDeviceRegistryProperty(deviceInfoSet, - &deviceInfo, - SPDRP_BUSTYPEGUID, - NULL, - (PBYTE) &m_BusTypeGuid, - sizeof(m_BusTypeGuid), - NULL) == FALSE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit3; - } - -Exit3: - SetupDiDestroyDeviceInfoList(deviceInfoSet); - -Exit2: - - delete[] instanceId; - -Exit: - - return hr; -} - -HRESULT -CMyDevice::PlaybackFile( - _In_ PFILE_PLAYBACK PlayInfo, - _In_ IWDFIoRequest *FxRequest - ) -/*++ - - Routine Description: - - This method impersonates the caller, opens the file and prints each - character to the seven segement display. - - Arguments: - - PlayInfo - the playback info from the request. - - FxRequest - the request (used for impersonation) - - Return Value: - - Status - ---*/ - -{ - PLAYBACK_IMPERSONATION_CONTEXT context = {PlayInfo, NULL, S_OK}; - IWDFIoRequest2* fxRequest2; - - HRESULT hr; - - // Convert FxRequest to FxRequest2. No error can occur here. - FxRequest->QueryInterface(IID_PPV_ARGS(&fxRequest2)); - _Analysis_assume_(fxRequest2 != NULL); - - // - // Impersonate and open the playback file. - // - - hr = FxRequest->Impersonate( - SecurityImpersonation, - this->QueryIImpersonateCallback(), - &context - ); - if (FAILED(hr)) - { - goto exit; - } - - // - // Release the reference that was added in QueryIImpersonateCallback() - // - this->Release(); - - hr = context.Hr; - - if (FAILED(hr)) - { - goto exit; - } - - // - // The impersonation callback succeeded - tell code analysis that the - // file handle is non-null - // - - _Analysis_assume_(context.FileHandle != NULL); - - // - // Read from the file one character at a time until we hit - // EOF or the request is cancelled. - // - - do - { - UCHAR c; - ULONG bytesRead; - - // - // Check for cancellation. - // - - if (fxRequest2->IsCanceled()) - { - hr = HRESULT_FROM_WIN32(ERROR_CANCELLED); - } - else - { - BOOL result; - - // - // Read a character from the file and see if we can - // encode it on the display. - // - - result = ReadFile(context.FileHandle, - &c, - sizeof(c), - &bytesRead, - NULL); - - if (result) - { - SEVEN_SEGMENT segment; - BAR_GRAPH_STATE barGraph; - - if (bytesRead > 0) - { - #pragma prefast(suppress:__WARNING_USING_UNINIT_VAR,"Above this->Release() method does not actually free 'this'") - if(EncodeSegmentValue(c, &segment) == true) - { - barGraph.BarsAsUChar = c; - - SetSevenSegmentDisplay(&segment); - SetBarGraphDisplay(&barGraph); - } - - Sleep(PlayInfo->Delay); - } - else - { - hr = S_OK; - break; - } - } - else - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - - } while(SUCCEEDED(hr)); - - CloseHandle(context.FileHandle); - -exit: - - fxRequest2->Release(); - return hr; -} - -VOID -CMyDevice::OnImpersonate( - _In_ PVOID Context - ) -/*++ - - Routine Description: - - This routine handles the impersonation for the PLAY FILE I/O control. - - Arguments: - - Context - pointer to the impersonation context - - Return Value: - - None - ---*/ -{ - PPLAYBACK_IMPERSONATION_CONTEXT context; - - context = (PPLAYBACK_IMPERSONATION_CONTEXT) Context; - - context->FileHandle = CreateFile(context->PlaybackInfo->Path, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (context->FileHandle == INVALID_HANDLE_VALUE) - { - DWORD error = GetLastError(); - context->Hr = HRESULT_FROM_WIN32(error); - } - else - { - context->Hr = S_OK; - } - - return; -} - -#define SS_LEFT (SS_TOP_LEFT | SS_BOTTOM_LEFT) -#define SS_RIGHT (SS_TOP_RIGHT | SS_BOTTOM_RIGHT) - -bool -CMyDevice::EncodeSegmentValue( - _In_ UCHAR Character, - _Out_ SEVEN_SEGMENT *SevenSegment - ) -{ - UCHAR letterMap[] = { - (SS_TOP | SS_BOTTOM_LEFT | SS_RIGHT | SS_CENTER | SS_BOTTOM), // a - (SS_LEFT | SS_CENTER | SS_BOTTOM | SS_BOTTOM_RIGHT), // b - (SS_CENTER | SS_BOTTOM_LEFT | SS_BOTTOM), // c - (SS_BOTTOM_LEFT | SS_CENTER | SS_BOTTOM | SS_RIGHT), // d - (SS_LEFT | SS_TOP | SS_CENTER | SS_BOTTOM), // e - (SS_LEFT | SS_TOP | SS_CENTER), // f - (SS_TOP | SS_TOP_LEFT | SS_CENTER | SS_BOTTOM | SS_RIGHT), // g - (SS_LEFT | SS_RIGHT | SS_CENTER), // h - (SS_BOTTOM_LEFT), // i - (SS_BOTTOM | SS_RIGHT), // j - (SS_LEFT | SS_CENTER | SS_BOTTOM), // k - (SS_LEFT | SS_BOTTOM), // l - (SS_LEFT | SS_TOP | SS_RIGHT), // m - (SS_BOTTOM_LEFT | SS_CENTER | SS_BOTTOM_RIGHT), // n - (SS_BOTTOM_LEFT | SS_BOTTOM_RIGHT | SS_CENTER | SS_BOTTOM), // o - (SS_LEFT | SS_TOP | SS_CENTER | SS_TOP_RIGHT), // p - (SS_TOP_LEFT | SS_TOP | SS_CENTER | SS_RIGHT), // q - (SS_BOTTOM_LEFT | SS_CENTER), // r - (SS_TOP_LEFT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_RIGHT), // s - (SS_TOP | SS_RIGHT), // t - (SS_LEFT | SS_RIGHT | SS_BOTTOM), // u - (SS_BOTTOM_LEFT | SS_BOTTOM | SS_BOTTOM_RIGHT), // v - (SS_LEFT | SS_BOTTOM | SS_BOTTOM_RIGHT), // w - (SS_LEFT | SS_CENTER | SS_RIGHT), // x - (SS_TOP_LEFT | SS_CENTER | SS_RIGHT), // y - (SS_TOP_RIGHT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_LEFT), // z - }; - - UCHAR numberMap[] = { - (SS_LEFT | SS_TOP | SS_BOTTOM | SS_RIGHT | SS_DOT), // 0 - (SS_RIGHT | SS_DOT), // 1 - (SS_TOP | - SS_TOP_RIGHT | SS_CENTER | SS_BOTTOM_LEFT | - SS_BOTTOM | SS_DOT), // 2 - (SS_TOP | SS_CENTER | SS_BOTTOM | SS_RIGHT | SS_DOT), // 3 - (SS_TOP_LEFT | SS_CENTER | SS_RIGHT | SS_DOT), // 4 - (SS_TOP_LEFT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_RIGHT | SS_DOT), // 5 - (SS_TOP | SS_CENTER | SS_BOTTOM | - SS_LEFT | SS_BOTTOM_RIGHT | SS_DOT), // 6 - (SS_TOP | SS_RIGHT | SS_DOT), // 7 - (SS_TOP | SS_BOTTOM | SS_CENTER | - SS_LEFT | SS_RIGHT | SS_DOT), // 8 - (SS_TOP_LEFT | SS_TOP | SS_CENTER | SS_RIGHT | SS_DOT), // 9 - }; - - if ((Character >= 'a') && (Character <= 'z')) - { - SevenSegment->Segments = letterMap[Character - 'a']; - return true; - } - else if ((Character >= 'A') && (Character <= 'Z')) - { - SevenSegment->Segments = letterMap[Character - 'A']; - return true; - } - else if ((Character >= '0') && (Character <= '9')) - { - SevenSegment->Segments = numberMap[Character - '0']; - return true; - } - else - { - SevenSegment->Segments = 0; - return false; - } -} - diff --git a/usb/umdf_filter_umdf/umdf_driver/Device.h b/usb/umdf_filter_umdf/umdf_driver/Device.h deleted file mode 100644 index 641a04ded..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/Device.h +++ /dev/null @@ -1,604 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF OSR Fx2 sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -#define ENDPOINT_TIMEOUT 10000 -#define NUM_OSRUSB_ENDPOINTS 3 - -// -// Define the vendor commands supported by our device -// -#define USBFX2LK_READ_7SEGMENT_DISPLAY 0xD4 -#define USBFX2LK_READ_SWITCHES 0xD6 -#define USBFX2LK_READ_BARGRAPH_DISPLAY 0xD7 -#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 -#define USBFX2LK_IS_HIGH_SPEED 0xD9 -#define USBFX2LK_REENUMERATE 0xDA -#define USBFX2LK_SET_7SEGMENT_DISPLAY 0xDB - -typedef struct { - UCHAR Segments; -} SEVEN_SEGMENT, *PSEVEN_SEGMENT; - -// -// Context for the impersonation callback. -// - -typedef struct -{ - PFILE_PLAYBACK PlaybackInfo; - - HANDLE FileHandle; - - HRESULT Hr; -} PLAYBACK_IMPERSONATION_CONTEXT, *PPLAYBACK_IMPERSONATION_CONTEXT; - -// -// Class for the driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackHardware, - public IPnpCallback, - public IPnpCallbackSelfManagedIo, - public IUsbTargetPipeContinuousReaderCallbackReadersFailed, - public IUsbTargetPipeContinuousReaderCallbackReadComplete, - public IImpersonateCallback -{ -// -// Private data members. -// -private: - // - // Weak reference to framework device - // Use IWDFDevice2 so we can set power policy settings - // - IWDFDevice2 *m_FxDevice; - - // - // Weak reference to the control queue - // - PCMyReadWriteQueue m_ReadWriteQueue; - - // - // Weak reference to the control queue - // - PCMyControlQueue m_ControlQueue; - - // - // The bus type for this device (used here for - // illustrative purposes only) - // - - GUID m_BusTypeGuid; - - // - // USB Device I/O Target - // - IWDFUsbTargetDevice * m_pIUsbTargetDevice; - - // - // USB Interface - // - IWDFUsbInterface * m_pIUsbInterface; - - // - // USB Input pipe for Reads - // - IWDFUsbTargetPipe * m_pIUsbInputPipe; - - // - // USB Output pipe for writes - // - IWDFUsbTargetPipe * m_pIUsbOutputPipe; - - // - // USB interrupt pipe - // - IWDFUsbTargetPipe * m_pIUsbInterruptPipe; - - // - // Use I/O target state management interfaces if you are going to - // support a continuous reader. - // - - // - // USB interrupt pipe state management - // - IWDFIoTargetStateManagement * m_pIoTargetInterruptPipeStateMgmt; - - // - // Device Speed (Low, Full, High) - // - UCHAR m_Speed; - - // - // Current switch state - // - SWITCH_STATE m_SwitchState; - - // - // Request to be used for pending reads from interrupt pipe - // (to get switch state change notifications) - // - - IWDFIoRequest * m_RequestForPendingRead; - - // - // If reads stopped because of a transient problem, the error status - // is stored here. - // - - HRESULT m_InterruptReadProblem; - - // - // Switch state buffer - this might hold the transient value - // m_SwitchState holds stable value of the switch state - // - SWITCH_STATE m_SwitchStateBuffer; - - // - // A manual queue to hold requests for changes in the I/O switch state. - // - - IWDFIoQueue * m_SwitchChangeQueue; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_ControlQueue(NULL), - m_ReadWriteQueue(NULL), - m_SwitchChangeQueue(NULL), - m_pIUsbTargetDevice(NULL), - m_pIUsbInterface(NULL), - m_pIUsbInputPipe(NULL), - m_pIUsbOutputPipe(NULL), - m_pIUsbInterruptPipe(NULL), - m_Speed(0), - m_InterruptReadProblem(S_OK), - m_RequestForPendingRead(NULL), - m_pIoTargetInterruptPipeStateMgmt(NULL) - { - ZeroMemory(&m_BusTypeGuid, sizeof(m_BusTypeGuid)); - } - - ~CMyDevice( - ); - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - // - // Helper methods - // - - HRESULT - GetBusTypeGuid( - VOID - ); - - HRESULT - CreateUsbIoTargets( - VOID - ); - - - HRESULT - ConfigureUsbPipes( - ); - - HRESULT - SetPowerManagement( - VOID - ); - - HRESULT - IndicateDeviceReady( - VOID - ); - - // - // Helper functions - // - - HRESULT - SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ); - - static - WDF_IO_TARGET_STATE - GetTargetState( - IWDFIoTarget * pTarget - ); - - VOID - ServiceSwitchChangeQueue( - _In_ SWITCH_STATE NewState, - _In_ HRESULT CompletionStatus, - _In_opt_ IWDFFile *SpecificFile - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - - IPnpCallback * - QueryIPnpCallback( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IPnpCallbackHardware * - QueryIPnpCallbackHardware( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IPnpCallbackSelfManagedIo * - QueryIPnpCallbackSelfManagedIo( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - - IUsbTargetPipeContinuousReaderCallbackReadersFailed * - QueryContinousReaderFailureCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IUsbTargetPipeContinuousReaderCallbackReadComplete * - QueryContinousReaderCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IImpersonateCallback * - QueryIImpersonateCallback( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - GetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - - HRESULT - SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - - HRESULT - GetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ); - - HRESULT - SetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ); - - HRESULT - ReadSwitchState( - _In_ PSWITCH_STATE SwitchState - ); - - bool - EncodeSegmentValue( - _In_ UCHAR Character, - _Out_ SEVEN_SEGMENT *SevenSegment - ); - - HRESULT - PlaybackFile( - _In_ PFILE_PLAYBACK PlaybackInfo, - _In_ IWDFIoRequest *FxRequest - ); - - // - //returns a weak reference to the target USB device - //DO NOT release it - // - IWDFUsbTargetDevice * - GetUsbTargetDevice( - ) - { - return m_pIUsbTargetDevice; - } - - // - //returns a weak reference to input pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetInputPipe( - ) - { - return m_pIUsbInputPipe; - } - - // - //returns a weak reference to output pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetOutputPipe( - ) - { - return m_pIUsbOutputPipe; - } - - IWDFIoQueue * - GetSwitchChangeQueue( - VOID - ) - { - return m_SwitchChangeQueue; - } - - PSWITCH_STATE - GetCurrentSwitchState( - VOID - ) - { - return &m_SwitchState; - } - - - HRESULT - ConfigContReaderForInterruptEndPoint( - VOID - ); -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IPnpCallbackHardware - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnPrepareHardware( - _In_ IWDFDevice *FxDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnReleaseHardware( - _In_ IWDFDevice *FxDevice - ); - - - // - // IPnpCallback - // - virtual - HRESULT - STDMETHODCALLTYPE - OnD0Entry( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnD0Exit( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ); - - virtual - void - STDMETHODCALLTYPE - OnSurpriseRemoval( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnQueryRemove( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnQueryStop( - _In_ IWDFDevice* pWdfDevice - ); - - // - // IPnpCallbackSelfManagedIo - // - virtual - VOID - STDMETHODCALLTYPE - OnSelfManagedIoCleanup( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - VOID - STDMETHODCALLTYPE - OnSelfManagedIoFlush( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoInit( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoRestart( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoStop( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoSuspend( - _In_ IWDFDevice* pWdfDevice - ); - - // - // IUsbTargetPipeContinuousReaderCallbackReadersFailed - // - virtual - BOOL - STDMETHODCALLTYPE - OnReaderFailure( - IWDFUsbTargetPipe * pPipe, - HRESULT hrCompletion - ); - - // - // IUsbTargetPipeContinuousReaderCallbackReadComplete - // - virtual - VOID - STDMETHODCALLTYPE - OnReaderCompletion( - IWDFUsbTargetPipe * pPipe, - IWDFMemory * pMemory, - SIZE_T NumBytesTransferred, - PVOID Context - ); - - // IImpersonateCallback - virtual - VOID - STDMETHODCALLTYPE - OnImpersonate( - _In_ PVOID Context - ); -}; - diff --git a/usb/umdf_filter_umdf/umdf_driver/Driver.cpp b/usb/umdf_filter_umdf/umdf_driver/Driver.cpp deleted file mode 100644 index d66352429..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 driver's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/umdf_filter_umdf/umdf_driver/Driver.h b/usb/umdf_filter_umdf/umdf_driver/Driver.h deleted file mode 100644 index d9cafb4e5..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF OSR Fx2 sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the OSR Fx2 sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.ctl b/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.rc b/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.cpp b/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.cpp deleted file mode 100644 index 461448292..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "ReadWriteQueue.tmh" - -VOID -CMyReadWriteQueue::OnCompletion( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ) -{ - UNREFERENCED_PARAMETER(pIoTarget); - UNREFERENCED_PARAMETER(pContext); - - pWdfRequest->CompleteWithInformation( - pParams->GetCompletionStatus(), - pParams->GetInformation() - ); -} - -void -CMyReadWriteQueue::ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ) -{ - // - //First set the completion callback - // - - IRequestCallbackRequestCompletion * pCompletionCallback = NULL; - HRESULT hrQI = this->QueryInterface(IID_PPV_ARGS(&pCompletionCallback)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI) && (NULL != pCompletionCallback)); - - pRequest->SetCompletionCallback( - pCompletionCallback, - NULL - ); - - pCompletionCallback->Release(); - pCompletionCallback = NULL; - - // - //Send down the request - // - - HRESULT hrSend = S_OK; - hrSend = pRequest->Send(pIoTarget, - 0, //flags - 0); //timeout - - if (FAILED(hrSend)) - { - pRequest->CompleteWithInformation(hrSend, 0); - } - - return; -} - - -CMyReadWriteQueue::CMyReadWriteQueue( - _In_ PCMyDevice Device - ) : - CMyQueue(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyReadWriteQueue::~CMyReadWriteQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyReadWriteQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) - { - hr = S_OK; - *Object = QueryIQueueCallbackWrite(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackRead))) - { - hr = S_OK; - *Object = QueryIQueueCallbackRead(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - hr = S_OK; - *Object = QueryIRequestCallbackRequestCompletion(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackIoStop))) - { - hr = S_OK; - *Object = QueryIQueueCallbackIoStop(); - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyReadWriteQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyReadWriteQueue queue; - HRESULT hr = S_OK; - - queue = new CMyReadWriteQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyReadWriteQueue::Initialize( - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - hr = __super::Initialize(WdfIoQueueDispatchParallel, - true, - true); - - // - // return the status. - // - - return hr; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - - Write dispatch routine - IQueueCallbackWrite - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Lenth of bytes in the write buffer - - Allocate and copy data to local buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToWrite - ); - - HRESULT hr = S_OK; - IWDFMemory * pInputMemory = NULL; - IWDFUsbTargetPipe * pOutputPipe = m_Device->GetOutputPipe(); - - pWdfRequest->GetInputMemory(&pInputMemory); - - hr = pOutputPipe->FormatRequestForWrite( - pWdfRequest, - NULL, //pFile - pInputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, pOutputPipe); - } - - SAFE_RELEASE(pInputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToRead - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToRead - Lenth of bytes in the read buffer - - Copy available data into the read buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToRead - ); - - HRESULT hr = S_OK; - IWDFMemory * pOutputMemory = NULL; - - pWdfRequest->GetOutputMemory(&pOutputMemory); - - hr = m_Device->GetInputPipe()->FormatRequestForRead( - pWdfRequest, - NULL, //pFile - pOutputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, m_Device->GetInputPipe()); - } - - SAFE_RELEASE(pOutputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnIoStop( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ) -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - - // - // The driver owns the request and no locking constraint is safe for - // the queue callbacks - // - if (ActionFlags == WdfRequestStopActionSuspend ) - { - IWDFIoRequest2 * request2 = NULL; - HRESULT hr; - - hr = pWdfRequest->QueryInterface(IID_PPV_ARGS(&request2)); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Failed to QI for IWDFIoRequest2: %!hresult!", - hr); - return; - } - - request2->StopAcknowledge(FALSE); //don't requeue - SAFE_RELEASE(request2); - } - else if(ActionFlags == WdfRequestStopActionPurge) - { - // - // Cancel the sent request since we are asked to purge the request - // - - pWdfRequest->CancelSentRequest(); - } - - return; -} - diff --git a/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.h b/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.h deleted file mode 100644 index 4f1a98c13..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/ReadWriteQueue.h +++ /dev/null @@ -1,163 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -#define MAX_TRANSFER_SIZE(x) 64*1024*1024 - -// -// Queue Callback Object. -// - -class CMyReadWriteQueue : - public IQueueCallbackRead, - public IQueueCallbackWrite, - public IRequestCallbackRequestCompletion, - public IQueueCallbackIoStop, - public CMyQueue -{ -protected: - HRESULT - Initialize( - ); - - void - ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ); - -public: - - CMyReadWriteQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyReadWriteQueue(); - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return CMyQueue::Configure(); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackRead * - QueryIQueueCallbackRead( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackIoStop* - QueryIQueueCallbackIoStop( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - - // - // Wdf Callbacks - // - - // - // IQueueCallbackWrite - // - STDMETHOD_ (void, OnWrite)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // - // IQueueCallbackRead - // - STDMETHOD_ (void, OnRead)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); - - // - //IRequestCallbackRequestCompletion - // - - STDMETHOD_ (void, OnCompletion)( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ); - - // - //IQueueCallbackIoStop - // - - STDMETHOD_ (void, OnIoStop)( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ); - -}; diff --git a/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj b/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj deleted file mode 100644 index d92581766..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj +++ /dev/null @@ -1,281 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98} - $(MSBuildProjectName) - 1 - 1 - false - true - Debug - Win32 - {87BFB278-0771-439F-893D-89376B83F7F0} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj.Filters b/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj.Filters deleted file mode 100644 index 372badf09..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/WUDFOsrUsbFx2.vcxproj.Filters +++ /dev/null @@ -1,52 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {F8E1CCD2-AADC-44B5-B631-5C6E6D74CFCD} - - - h;hpp;hxx;hm;inl;inc;xsd - {0E050956-9FA9-495C-9F9F-D663EFA3A344} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {49CD21A6-260A-471B-B532-9E9E23F6195F} - - - inf;inv;inx;mof;mc; - {A942026F-83A0-4223-881A-29732777F22C} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/umdf_driver/comsup.cpp b/usb/umdf_filter_umdf/umdf_driver/comsup.cpp deleted file mode 100644 index 2f14f5886..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/comsup.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -_Use_decl_annotations_ -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/umdf_filter_umdf/umdf_driver/comsup.h b/usb/umdf_filter_umdf/umdf_driver/comsup.h deleted file mode 100644 index 167b21ff3..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/comsup.h +++ /dev/null @@ -1,216 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_driver/dllsup.cpp b/usb/umdf_filter_umdf/umdf_driver/dllsup.cpp deleted file mode 100644 index 7fda91e4d..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the driver uses - L"Microsoft\\UMDF\\OsrUsb" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for this sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - OSR Fx2 driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/umdf_filter_umdf/umdf_driver/exports.def b/usb/umdf_filter_umdf/umdf_driver/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/umdf_filter_umdf/umdf_driver/internal.h b/usb/umdf_filter_umdf/umdf_driver/internal.h deleted file mode 100644 index 2d57793db..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/internal.h +++ /dev/null @@ -1,170 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF OSR Fx2 - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Include SetupDi functions. -// - -#include "setupapi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Include the safestring functions. -// - -#include "strsafe.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; -typedef class CMyReadWriteQueue *PCMyReadWriteQueue; - -typedef class CCancelCallback *PCCancelCallback; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" -#include "ControlQueue.h" -#include "ReadWriteQueue.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} - -#define IDLE_TIMEOUT_IN_MSEC 10*1000 diff --git a/usb/umdf_filter_umdf/umdf_driver/queue.cpp b/usb/umdf_filter_umdf/umdf_driver/queue.cpp deleted file mode 100644 index c56b38bbc..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/queue.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.tmh" - -CMyQueue::CMyQueue( - _In_ PCMyDevice Device - ) : - m_FxQueue(NULL), - m_Device(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - hr = CUnknown::QueryInterface(InterfaceId, Object); - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ) -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the I/O Queue object. - // - - { - IUnknown *callback = QueryIUnknown(); - - hr = m_Device->GetFxDevice()->CreateIoQueue( - callback, - Default, - DispatchType, - PowerManaged, - FALSE, - &fxQueue - ); - callback->Release(); - } - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // Release the creation reference on the queue. This object will be - // destroyed before the queue so we don't need to have a reference out - // on it. - // - - fxQueue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::Configure( - VOID - ) -{ - return S_OK; -} diff --git a/usb/umdf_filter_umdf/umdf_driver/queue.h b/usb/umdf_filter_umdf/umdf_driver/queue.h deleted file mode 100644 index 5659224bb..000000000 --- a/usb/umdf_filter_umdf/umdf_driver/queue.h +++ /dev/null @@ -1,93 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyQueue : - public CUnknown -{ -protected: - // - // Unreferenced pointer to the partner Fx device. - // - - IWDFIoQueue *m_FxQueue; - - // - // Unreferenced pointer to the parent device. - // - - PCMyDevice m_Device; - - HRESULT - Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ); - -protected: - - CMyQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyQueue(); - - HRESULT - Configure( - VOID - ); - -public: - - IWDFIoQueue * - GetFxQueue( - VOID - ) - { - return m_FxQueue; - } - - - PCMyDevice - GetDevice( - VOID - ) - { - return m_Device; - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_filter/OsrUsbFilter.rc b/usb/umdf_filter_umdf/umdf_filter/OsrUsbFilter.rc deleted file mode 100644 index cec032d97..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/OsrUsbFilter.rc +++ /dev/null @@ -1,17 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbFilter.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OsrUsbFilter User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "OsrUsbFilter" -#define VER_ORIGINALFILENAME_STR "OsrUsbFilter.dll" - -#include "common.ver" diff --git a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj b/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj deleted file mode 100644 index 38798dfef..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj +++ /dev/null @@ -1,293 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127} - $(MSBuildProjectName) - 1 - 1 - false - true - Debug - Win32 - {45297D7C-3015-4F09-B0E7-469440EB9458} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - WUDFOsrUsbFilter - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - 0x0A00 - 0x0A000000 - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalIncludeDirectories);..\..\..\inc - true - Level4 - - - - - %(AdditionalIncludeDirectories);..\..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters b/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters deleted file mode 100644 index 7a4a8f8d7..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilter.vcxproj.Filters +++ /dev/null @@ -1,46 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {3CE4C3CE-9C1D-4790-B2EF-784C3412310A} - - - h;hpp;hxx;hm;inl;inc;xsd - {4A9BD78B-5831-48AA-8C22-28BEBBC8A7AB} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {ACD57755-0E18-4D24-A740-0D944929A053} - - - inf;inv;inx;mof;mc; - {2084F476-D6F1-485F-B9A6-581DD86D24F1} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilterOnUmFx2Driver.inx b/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilterOnUmFx2Driver.inx deleted file mode 100644 index b8ff8b0f7..000000000 Binary files a/usb/umdf_filter_umdf/umdf_filter/WUDFOsrUsbFilterOnUmFx2Driver.inx and /dev/null differ diff --git a/usb/umdf_filter_umdf/umdf_filter/comsup.cpp b/usb/umdf_filter_umdf/umdf_filter/comsup.cpp deleted file mode 100644 index 76a4b940b..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/comsup.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// This is the number of characters in a GUID string including the trailing -// NULL. -// - -#define GUID_STRING_CCH (sizeof("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}")) - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -_Use_decl_annotations_ -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/umdf_filter_umdf/umdf_filter/comsup.h b/usb/umdf_filter_umdf/umdf_filter/comsup.h deleted file mode 100644 index 890b576a5..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/comsup.h +++ /dev/null @@ -1,216 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_filter/device.cpp b/usb/umdf_filter_umdf/umdf_filter/device.cpp deleted file mode 100644 index 126637ce0..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/device.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR USB Sample Filter driver's - device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "device.tmh" - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR USB Sample Filter driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice; - HRESULT hr; - - // - // Configure things like the locking model before we go to create our - // partner device. - // - - // - // We don't need device level locking since we do not keep any state - // across the requests - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // Mark ourselves as a filter - // - - FxDeviceInit->SetFilter(); - - - // - // We are a filter; we don't want to be the power policy owner - // - - FxDeviceInit->SetPowerPolicyOwnership(FALSE); - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - PCMyQueue defaultQueue; - - HRESULT hr; - - hr = CMyQueue::CreateInstance(m_FxDevice, &defaultQueue); - - if (FAILED(hr)) - { - return hr; - } - - hr = defaultQueue->Configure(); - - defaultQueue->Release(); - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the OSR USB Sample Filter driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If OSR USB Sample Filter is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - return CUnknown::QueryInterface(InterfaceId, Object); -} diff --git a/usb/umdf_filter_umdf/umdf_filter/device.h b/usb/umdf_filter_umdf/umdf_filter/device.h deleted file mode 100644 index f7a50b1d0..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/device.h +++ /dev/null @@ -1,114 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF OSR USB Sample Filter - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the iotrace driver. -// - -class CMyDevice : public CUnknown -{ - -// -// Private data members. -// -private: - - IWDFDevice *m_FxDevice; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) - { - m_FxDevice = NULL; - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_filter/dllsup.cpp b/usb/umdf_filter_umdf/umdf_filter/dllsup.cpp deleted file mode 100644 index d71d5fe83..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/dllsup.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the OSR USB Sample Filter - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the OSR USB Sample Filter sample. If - you choose to use a different primary include file, you should ensure - they are defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -// -// Global variable to hold the module handle for this DLL. Initialized during -// DllMain and never cleared. This is used when registering and unregistering -// the driver's COM information. -// - -HINSTANCE g_ModuleHandle = NULL; - -BOOL -WINAPI -DllMain( - HINSTANCE /* ModuleHandle */, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the OSR USB Sample - Filter driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} - diff --git a/usb/umdf_filter_umdf/umdf_filter/driver.cpp b/usb/umdf_filter_umdf/umdf_filter/driver.cpp deleted file mode 100644 index c5910c05e..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/driver.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR USB Sample Filter - driver's core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/umdf_filter_umdf/umdf_filter/driver.h b/usb/umdf_filter_umdf/umdf_filter/driver.h deleted file mode 100644 index 08f36a712..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/driver.h +++ /dev/null @@ -1,145 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF OSR USB Sample Filter - driver's callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the OSR USB Sample Filter driver. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver* /*FxWdfDriver*/ - ) - { - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver * /*FxWdfDriver*/ - ) - { - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); -}; diff --git a/usb/umdf_filter_umdf/umdf_filter/exports.def b/usb/umdf_filter_umdf/umdf_filter/exports.def deleted file mode 100644 index 0fc428179..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; Skeleton.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/umdf_filter_umdf/umdf_filter/internal.h b/usb/umdf_filter_umdf/umdf_filter/internal.h deleted file mode 100644 index 516f6d7fa..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/internal.h +++ /dev/null @@ -1,111 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF OSR USB Sample Filter - driver. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -// -// Define the tracing flags. -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - MyDriverTraceControl, (73cdcaa5,ce52,43f2,aa2d,5f5a84e22213), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsbFilter" -#define MYDRIVER_COM_DESCRIPTION L"UMDF OSR USB Sample Filter Driver" -#define MYDRIVER_CLASS_ID {0x422d8dbc, 0x520d, 0x4d7e, {0x8f, 0x53, 0x92, 0x0e, 0x5c, 0x86, 0x7e, 0x6c}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_SAMPLE_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/umdf_filter_umdf/umdf_filter/queue.cpp b/usb/umdf_filter_umdf/umdf_filter/queue.cpp deleted file mode 100644 index 5642ec744..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/queue.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Queue.cpp - -Abstract: - - This module contains the implementation of the OSR USB Filter Sample driver's - queue callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.h" - -#include "queue.tmh" - -HRESULT -CMyQueue::CreateInstance( - _In_ IWDFDevice * FxDevice, - _Out_ CMyQueue **Queue - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR USB Filter Sample driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - CMyQueue *queue; - - HRESULT hr = S_OK; - - // - // Allocate a new instance of the device class. - // - - queue = new CMyQueue(); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(FxDevice); - } - - if (SUCCEEDED(hr)) - { - queue->AddRef(); - *Queue = queue; - } - - if (NULL != queue) - { - queue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - - if(IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDefaultIoHandler))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDefaultIoHandler(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) - { - hr = S_OK; - *Object = QueryIQueueCallbackWrite(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - hr = S_OK; - *Object = QueryIRequestCallbackRequestCompletion(); - - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyQueue::Initialize( - _In_ IWDFDevice *FxDevice - ) -/*++ - - Routine Description: - - This method initializes the device callback object. Any operations which - need to be performed before the caller can use the callback object, but - which couldn't be done in the constructor becuase they could fail would - be placed here. - - Arguments: - - FxDevice - the device which this Queue is for. - - Return Value: - - status. - ---*/ -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the framework queue - // - - IUnknown *unknown = QueryIUnknown(); - hr = FxDevice->CreateIoQueue( - unknown, - TRUE, // bDefaultQueue - WdfIoQueueDispatchParallel, - FALSE, // bPowerManaged - TRUE, // bAllowZeroLengthRequests - &fxQueue - ); - if (FAILED(hr)) - { - Trace( - TRACE_LEVEL_ERROR, - "%!FUNC!: Could not create default I/O queue, %!hresult!", - hr - ); - } - - unknown->Release(); - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // m_FxQueue is kept as a Weak reference to framework Queue object to avoid - // circular reference. This object's lifetime is contained within - // framework Queue object's lifetime - // - - fxQueue->Release(); - } - - if (SUCCEEDED(hr)) - { - FxDevice->GetDefaultIoTarget(&m_FxIoTarget); - } - - return hr; -} - -void -CMyQueue::InvertBits( - _Inout_ IWDFMemory* FxMemory, - _In_ SIZE_T NumBytes - ) -/*++ - - Routine Description: - - This helper method inverts bits in the buffer of an FxMemory object - - Arguments: - - FxMemory - Framework memory object whose buffer's bits are to be inverted - - NumBytes - Number of bytes for which bits are to be inverted - - Return Value: - - None - ---*/ -{ - PBYTE Buffer = (PBYTE) - FxMemory->GetDataBuffer(NULL); - - for (SIZE_T i = 0; i < NumBytes; i++) - { - memset(Buffer + i, ~(Buffer[i]), sizeof(*Buffer)); - } -} - -void -CMyQueue::OnWrite( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest, - _In_ SIZE_T NumOfBytesToWrite - ) -/*++ - - Routine Description: - - This method is called by Framework Queue object to deliver the Write request - This method inverts the bits in write buffer and forwards the request down the device stack - In case of any failure prior to ForwardRequest, it completets the request with failure - - Arguments: - - pWdfQueue - Framework Queue which is delivering the request - - pWdfRequest - Framework Request - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - IWDFMemory * FxInputMemory = NULL; - - FxRequest->GetInputMemory(&FxInputMemory); - - // - // Invert bits of the buffer to be written to device - // - - InvertBits(FxInputMemory, NumOfBytesToWrite); - - // - // Forward request down the stack - // When the device below completes the request we will get notified in OnComplete - // and then we will complete the request - // - - ForwardRequest(FxRequest); - - FxInputMemory->Release(); -} - -// -// IQueueCallbackDefaultIoHandler method -// - -void -CMyQueue::OnDefaultIoHandler( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest - ) -/*++ - - Routine Description: - - This method is called by Framework Queue object to deliver all the I/O - Requests for which we do not have a specific handler - (In our case anything other than Write) - - Arguments: - - pWdfQueue - Framework Queue which is delivering the request - - pWdfRequest - Framework Request - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - // - // We just forward the request down the stack - // When the device below completes the request we will get notified in OnComplete - // and then we will complete the request - // - - ForwardRequest(FxRequest); -} - -void -CMyQueue::ForwardRequest( - _In_ IWDFIoRequest* FxRequest - ) -/*++ - - Routine Description: - - This helper method forwards the request down the stack - - Arguments: - - pWdfRequest - Request to be forwarded - - Return Value: - - None - - Remarks: - - The request gets forwarded to the next device in the stack which can be: - 1. Next device in user-mode stack - 2. Top device in kernel-mode stack (Redirector's Down Device) - - In this routine we: - 1. Set a completion callback - 2. Copy request parameters to next stack location - 3. Asynchronously send the request without any timeout - - When the lower request gets completed we will be notified via the - completion callback, where we will complete our request - - In case of failure this routine completes the request - ---*/ -{ - // - //First set the completion callback - // - - IRequestCallbackRequestCompletion *completionCallback = - QueryIRequestCallbackRequestCompletion(); - - FxRequest->SetCompletionCallback( - completionCallback, - NULL //pContext - ); - - completionCallback->Release(); - - // - //Copy current i/o stack locations parameters to the next stack location - // - - FxRequest->FormatUsingCurrentType( - ); - - // - //Send down the request - // - HRESULT hrSend = S_OK; - - hrSend = FxRequest->Send( - m_FxIoTarget, - 0, //No flag - 0 //No timeout - ); - - if (FAILED(hrSend)) - { - // - //If send failed we need to complete the request with failure - // - FxRequest->CompleteWithInformation(hrSend, 0); - } - - return; -} - -void -CMyQueue::HandleReadRequestCompletion( - IWDFIoRequest* FxRequest, - IWDFIoRequestCompletionParams* CompletionParams - ) -/*++ - - Routine Description: - - This helper method is called by OnCompletion method to complete Read request - We invert the bits in the read buffer - This is so that the client reads back the data it wrote since - we inverted bits during write to device - - Arguments: - - FxRequest - Request object of our layer - - CompletionParams - Parameters with which the lower Request got completed - - Return Value: - - None - - Remarks: - - This method always completes the request since no one else would get a chance to - complete the request - In case of failure it completes the request with failure - ---*/ -{ - HRESULT hrCompletion = CompletionParams->GetCompletionStatus(); - ULONG_PTR BytesRead = CompletionParams->GetInformation(); - - // - // Check - // 1. whether the lower device succeeded the Request (otherwise we will just complete - // the Request with failure - // 2. If data read is of non-zero length, for us to bother to invert its bits - // - - if (SUCCEEDED(hrCompletion) && - (0 != BytesRead) - ) - { - IWDFMemory *FxOutputMemory; - - FxRequest->GetOutputMemory(&FxOutputMemory ); - - InvertBits(FxOutputMemory, BytesRead); - - FxOutputMemory->Release(); - } - - // - // Complete the request - // - - FxRequest->CompleteWithInformation( - hrCompletion, - BytesRead - ); -} - - -void -CMyQueue::OnCompletion( - IWDFIoRequest* FxRequest, - IWDFIoTarget* FxIoTarget, - IWDFRequestCompletionParams* CompletionParams, - PVOID Context - ) -/*++ - - Routine Description: - - This method is called by Framework I/O Target object when - the lower device completets the Request - - Arguments: - - pWdfRequest - Request object of our layer - - pIoTarget - I/O Target object invoking this callback - - pParams - Parameters with which the lower Request got completed - - Return Value: - - None - ---*/ -{ - UNREFERENCED_PARAMETER(FxIoTarget); - UNREFERENCED_PARAMETER(Context); - - // - // If it is a read request, we invert the bits read since we inverted them during write - // so that application would read the same data as it wrote - // - - if (WdfRequestRead == FxRequest->GetType()) - { - IWDFIoRequestCompletionParams * IoCompletionParams = NULL; - HRESULT hrQI = CompletionParams->QueryInterface(IID_PPV_ARGS(&IoCompletionParams)); - WUDF_SAMPLE_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - HandleReadRequestCompletion( - FxRequest, - IoCompletionParams - ); - - SAFE_RELEASE(IoCompletionParams); - } - else - { - - // - // Otherwise we just complete our Request object with the same parameters - // with which the lower Request got completed - // - - FxRequest->CompleteWithInformation( - CompletionParams->GetCompletionStatus(), - CompletionParams->GetInformation() - ); - } -} - diff --git a/usb/umdf_filter_umdf/umdf_filter/queue.h b/usb/umdf_filter_umdf/umdf_filter/queue.h deleted file mode 100644 index 216264e93..000000000 --- a/usb/umdf_filter_umdf/umdf_filter/queue.h +++ /dev/null @@ -1,253 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Queue.h - -Abstract: - - This module contains the type definitions for the OSR USB Filter Sample - driver's queue callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Class for the queue callbacks. -// It implements -// IQueueCallbackDeviceIoControl -// IRequestCallbackRequestCompletion -// Queue callbacks -// -// This class also implements IRequestCallbackRequestCompletion callback -// to get the request completion notification when request is sent down the -// stack. This callback can be implemented on a separate object as well. -// This callback is implemented here only for conenience. -// -class CMyQueue : - public CUnknown, - public IQueueCallbackWrite, - public IQueueCallbackDefaultIoHandler, - public IRequestCallbackRequestCompletion -{ - -// -// Private data members. -// -private: - - // - // Weak reference to framework Queue object which this object implements callbacks for - // This is kept as a weak reference to avoid circular reference - // This object's lifetime is contained within framework Queue object's lifetime - // - - IWDFIoQueue *m_FxQueue; - - // - // I/O Target to which we forward requests. Represents next device in the - // device stack - // - - IWDFIoTarget *m_FxIoTarget; - -// -// Private methods. -// - -private: - - CMyQueue() : - m_FxQueue(NULL), - m_FxIoTarget(NULL) - { - } - - virtual ~CMyQueue() - { - if (NULL != m_FxIoTarget) - { - m_FxIoTarget->Release(); - } - } - - // - // QueryInterface helpers - // - - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackDefaultIoHandler * - QueryIQueueCallbackDefaultIoHandler( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // Initialize - // - - HRESULT - Initialize( - _In_ IWDFDevice *FxDevice - ); - - // - // Helper method to forward request down the stack - // - - void - ForwardRequest( - _In_ IWDFIoRequest *pWdfRequest - ); - - // - // Helper method to inverts bits in the buffer of a framework Memory object - // - - void - InvertBits( - _Inout_ IWDFMemory* FxMemory, - _In_ SIZE_T NumBytes - ); - - // - // Helper method to handle Read request completion - // - - void - HandleReadRequestCompletion( - IWDFIoRequest* FxRequest, - IWDFIoRequestCompletionParams* CompletionParams - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this class - // - - static - HRESULT - CreateInstance( - _In_ IWDFDevice *FxDevice, - _Out_ CMyQueue **Queue - ); - - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // IQueueCallbackWrite method - // - - virtual - void - STDMETHODCALLTYPE - OnWrite( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - - // - // IQueueCallbackDefaultIoHandler method - // - - virtual - void - STDMETHODCALLTYPE - OnDefaultIoHandler( - _In_ IWDFIoQueue* FxQueue, - _In_ IWDFIoRequest* FxRequest - ); - - // - //IRequestCallbackRequestCompletion - // - - virtual - void - STDMETHODCALLTYPE - OnCompletion( - IWDFIoRequest* FxRequest, - IWDFIoTarget* FxIoTarget, - IWDFRequestCompletionParams* CompletionParams, - PVOID Context - ); -}; - diff --git a/usb/umdf_filter_umdf/umdf_filter_umdf.sln b/usb/umdf_filter_umdf/umdf_filter_umdf.sln deleted file mode 100644 index 32dc6d8bd..000000000 --- a/usb/umdf_filter_umdf/umdf_filter_umdf.sln +++ /dev/null @@ -1,59 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Package", "Package", "{23CDA216-49BA-49D6-98E9-6692D1E6D363}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Umdf_filter", "Umdf_filter", "{EF4F817D-931F-4D72-B5A5-0E0FB30F1CE0}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Umdf_driver", "Umdf_driver", "{B3DCEF35-5C54-4506-981B-31B0611116E3}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "package", "Package\package.VcxProj", "{A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFilter", "umdf_filter\WUDFOsrUsbFilter.vcxproj", "{502F5F25-02A2-4047-8DD1-EB3DF0CC7127}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2", "umdf_driver\WUDFOsrUsbFx2.vcxproj", "{6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Debug|Win32.ActiveCfg = Debug|Win32 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Debug|Win32.Build.0 = Debug|Win32 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Release|Win32.ActiveCfg = Release|Win32 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Release|Win32.Build.0 = Release|Win32 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Debug|x64.ActiveCfg = Debug|x64 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Debug|x64.Build.0 = Debug|x64 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Release|x64.ActiveCfg = Release|x64 - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7}.Release|x64.Build.0 = Release|x64 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Debug|Win32.ActiveCfg = Debug|Win32 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Debug|Win32.Build.0 = Debug|Win32 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Release|Win32.ActiveCfg = Release|Win32 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Release|Win32.Build.0 = Release|Win32 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Debug|x64.ActiveCfg = Debug|x64 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Debug|x64.Build.0 = Debug|x64 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Release|x64.ActiveCfg = Release|x64 - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127}.Release|x64.Build.0 = Release|x64 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Debug|Win32.ActiveCfg = Debug|Win32 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Debug|Win32.Build.0 = Debug|Win32 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Release|Win32.ActiveCfg = Release|Win32 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Release|Win32.Build.0 = Release|Win32 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Debug|x64.ActiveCfg = Debug|x64 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Debug|x64.Build.0 = Debug|x64 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Release|x64.ActiveCfg = Release|x64 - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {A217E49A-2A5E-4E51-BA9E-D87D62F6E2F7} = {23CDA216-49BA-49D6-98E9-6692D1E6D363} - {502F5F25-02A2-4047-8DD1-EB3DF0CC7127} = {EF4F817D-931F-4D72-B5A5-0E0FB30F1CE0} - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98} = {B3DCEF35-5C54-4506-981B-31B0611116E3} - EndGlobalSection -EndGlobal diff --git a/usb/umdf_fx2/README.md b/usb/umdf_fx2/README.md deleted file mode 100644 index f95374f2c..000000000 --- a/usb/umdf_fx2/README.md +++ /dev/null @@ -1,373 +0,0 @@ ---- -page_type: sample -description: "A UMDF driver for the OSR USB-FX2 device that includes a test application, sample device metadata, and supports impersonation and idle power down." -languages: -- cpp -products: -- windows -- windows-wdk ---- - -# Sample UMDF Function Driver for OSR USB-FX2 (UMDF Version 1) - -The umdf\_fx2 sample is a User-Mode Driver Framework (UMDF) driver for the OSR USB-FX2 device. It includes a test app and sample device metadata, and supports impersonation and idle power down. - -The sample can also be used with the CustomDeviceAccess SDK sample. The sample demonstrates how to perform bulk and interrupt data transfers to an USB device. For more information, see the specification for the [OSR USB FX-2 Learning Kit](https://www.osronline.com/hardware/OSRFX2_32.pdf). The driver and sample device metadata also work with the [Custom driver access](https://go.microsoft.com/fwlink/p/?linkid=2114373) sample. - -The osrusbfx2 sample is divided into three samples: - -- **WDF Sample Driver Learning Lab for OSR USB-FX2**: This sample is a series of iterative drivers that demonstrate how to write a "Hello World" driver and adds additional features in each step. - -- **kmdf\_fx2**: This sample is the final version of kernel-mode **wdf\_osrfx2** driver. The sample demonstrates KMDF methods. - -- **umdf\_fx2**: This sample is the final version of the user-mode driver **wdf\_osrfx2**. The sample demonstrates UMDF methods. - -## Build the sample - -The default Solution build configuration is Debug and Win32. - -1. Open the driver project or solution in Visual Studio 2015 (find *filtername*.sln or *filtername*.vcxproj). - -1. Right-click the solution in the **Solutions Explorer** and select **Configuration Manager**. - -1. From the **Configuration Manager**, select the **Active Solution Configuration** and the **Active Solution Platform** (for example, Win32) that correspond to the type of build you are interested in. - -1. From the **Build** menu, click **Build Solution** (Ctrl+Shift+B). - -## Overview - -- The device is based on the development board supplied with the Cypress EZ-USB FX2 Development Kit (CY3681). - -- It contains 1 interface and 3 endpoints (Interrupt IN, Bulk Out, Bulk IN). - -- Firmware supports vendor commands to query or set LED Bar graph display and 7-segment LED display, and to query toggle switch states. - -- Interrupt Endpoint: - - - Sends an 8-bit value that represents the state of the switches. - - - Sent on startup, resume from suspend, and whenever the switch pack setting changes. - - - Firmware does not de-bounce the switch pack. - - - One switch change can result in multiple bytes being sent. - - - Bits are in the reverse order of the labels on the pack (for example, bit 0x80 is labeled 1 on the pack). - -- Bulk Endpoints are configured for loopback: - - - The device moves data from IN endpoint to OUT endpoint. - - - The device does not change the values of the data it receives nor does it internally create any data. - - - Endpoints are always double buffered. - - - Maximum packet size depends on speed (64 full speed, 512 high speed). - -## Testing the driver - -You can use the [Custom driver access](https://go.microsoft.com/fwlink/p/?linkid=2114373) sample to test the umdf\_fx2 sample. - -This sample also includes a test application, osrusbfx2.exe, that you can use to test the device. This console application enumerates the interface registered by the driver and opens the device to send read, write, or IOCTL requests based on the command line options. - -Usage for Read/Write test: - -- -r [*n*], where *n* is number of bytes to read. - -- -w [*n*], where *n* is number of bytes to write. - -- -c [*n*], where *n* is number of iterations (default = 1). - -- -v, shows verbose read data. - -- -p, plays with Bar Display, Dip Switch, 7-Segment Display. - -- -a, performs asynchronous I/O operation. - -- -u, dumps USB configuration and pipe information. - -- -f \<*filename*\> [*interval-seconds*], where *interval-seconds* is a delay in milliseconds, to send a text file to the seven-segment display (UMDF only) - -### Playing with the 7 segment display, toggle switches, and bar graph display - -Use the command `osrusbfx2.exe -p` with options 1 through 9 to set and clear bar graph display, set and get 7 segment state, and read the toggle switch states. The following shows the function options: - -```cmd -1. Light Bar -2. Clear Bar -3. Light entire Bar graph -4. Clear entire Bar graph -5. Get bar graph state -6. Get Switch state -7. Get Switch Interrupt Message -8. Get 7 segment state -9. Set 7 segment state -10. Reset the device -11. Re-enumerate the device - -0. Exit - -Selection: -``` - -### Reset and re-enumerate the device - -Use the command `osrusbfx2.exe -p` with options 10 and 11 to either reset the device or re-enumerate the device. - -### Read and write to bulk endpoints - -The following commands send read and write requests to the device's bulk endpoint. - -- `osrusbfx2.exe -r 64` - - The preceding command reads 64 bytes to the bulk IN endpoint. - -- `osrusbfx2.exe -w 64` - - The preceding command writes 64 bytes to the bulk OUT endpoint. - -- `osrusbfx2.exe -r 64 -w 64 -c 100 -v` - - The preceding command first writes 64 bytes of data to bulk OUT endpoint (Pipe 1), then reads 64 bytes from bulk IN endpoint (Pipe 2), and then compares the read buffer with write buffer to see if they match. If the buffer contents match, it repeats this operation 100 times. - -- `osrusbfx2.exe -a` - - The preceding command reads and writes to the device asynchronously in an infinite loop. - -The bulk endpoints are double buffered. Depending on the operational speed (full or high), the buffer size is either 64 bytes or 512 bytes, respectively. A request to read data does not complete if the buffers are empty. If the buffers are full, a request to write data does not complete until the buffers are emptied. When you are doing a synchronous read, make sure the endpoint buffer has data (for example, when you send 512 bytes write request to the device operating in full speed mode). Because the endpoints are double buffered, the total buffer capacity is 256 bytes. The first 256 bytes fills the buffer and the write request waits in the USB stack until the buffers are emptied. If you run another instance of the application to read 512 bytes of data, both write and read requests complete successfully. - -### Displaying descriptors - -The following command displays all the descriptors and endpoint information. - -`osrusbfx2.exe -u` - -If the device is operating in high speed mode, you get the following information: - -```cmd -=================== - -USB_CONFIGURATION_DESCRIPTOR - -bLength = 0x9, decimal 9 - -bDescriptorType = 0x2 ( USB_CONFIGURATION_DESCRIPTOR_TYPE ) - -wTotalLength = 0x27, decimal 39 - -bNumInterfaces = 0x1, decimal 1 - -bConfigurationValue = 0x1, decimal 1 - -iConfiguration = 0x4, decimal 4 - -bmAttributes = 0xa0 ( USB_CONFIG_BUS_POWERED ) - -MaxPower = 0x32, decimal 50 - ------------------------------ - -USB_INTERFACE_DESCRIPTOR #0 - -bLength = 0x9 - -bDescriptorType = 0x4 ( USB_INTERFACE_DESCRIPTOR_TYPE ) - -bInterfaceNumber = 0x0 - -bAlternateSetting = 0x0 - -bNumEndpoints = 0x3 - -bInterfaceClass = 0xff - -bInterfaceSubClass = 0x0 - -bInterfaceProtocol = 0x0 - -bInterface = 0x0 - ------------------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe00 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x81 ( INPUT ) - -bmAttributes= 0x3 ( USB_ENDPOINT_TYPE_INTERRUPT ) - -wMaxPacketSize= 0x49, decimal 73 - -bInterval = 0x1, decimal 1 - ------------------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe01 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x6 ( OUTPUT ) - -bmAttributes= 0x2 ( USB_ENDPOINT_TYPE_BULK ) - -wMaxPacketSize= 0x200, - -decimal 512 bInterval = 0x0, - -decimal 0 - ------------------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe02 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x88 ( INPUT ) - -bmAttributes= 0x2 ( USB_ENDPOINT_TYPE_BULK ) - -wMaxPacketSize= 0x200, decimal 512 - -bInterval = 0x0, decimal 0 -``` - -If the device is operating in low speed mode, you will get the following information: - -```cmd -=================== - -USB_CONFIGURATION_DESCRIPTOR - -bLength = 0x9, decimal 9 - -bDescriptorType = 0x2 ( USB_CONFIGURATION_DESCRIPTOR_TYPE ) - -wTotalLength = 0x27, decimal 39 - -bNumInterfaces = 0x1, decimal 1 - -bConfigurationValue = 0x1, decimal 1 - -iConfiguration = 0x3, decimal 3 - -bmAttributes = 0xa0 ( USB_CONFIG_BUS_POWERED ) - -MaxPower = 0x32, decimal 50 - ------------------------------ - -USB_INTERFACE_DESCRIPTOR #0 - -bLength = 0x9 - -bDescriptorType = 0x4 ( USB_INTERFACE_DESCRIPTOR_TYPE ) - -bInterfaceNumber = 0x0 bAlternateSetting = 0x0 - -bNumEndpoints = 0x3 - -bInterfaceClass = 0xff - -bInterfaceSubClass = 0x0 - -bInterfaceProtocol = 0x0 - -bInterface = 0x0 - ------------------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe00 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x81 ( INPUT ) - -bmAttributes= 0x3 ( USB_ENDPOINT_TYPE_INTERRUPT ) - -wMaxPacketSize= 0x49, decimal 73 - -bInterval = 0x1, decimal 1 - -------- ----------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe01 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x6 ( OUTPUT ) - -bmAttributes= 0x2 ( USB_ENDPOINT_TYPE_BULK ) - -wMaxPacketSize= 0x40, decimal 64 - -bInterval = 0x0, decimal 0 - ------------------------------- - -USB_ENDPOINT_DESCRIPTOR for Pipe02 - -bLength = 0x7 - -bDescriptorType = 0x5 ( USB_ENDPOINT_DESCRIPTOR_TYPE ) - -bEndpointAddress= 0x88 ( INPUT ) - -bmAttributes= 0x2 ( USB_ENDPOINT_TYPE_BULK ) - -wMaxPacketSize= 0x40, decimal 64 - -bInterval = 0x0, decimal 0 -``` - -## Sample Contents - -### usb\\umdf\_fx2\\driver - -This directory contains driver code that demonstrates the following functionality: - -- Loads the driver and responds to PnP and Power events. You can install, uninstall, disable, enable, suspend, and resume the system. - -- Registers a PnP device interface so that application can open a handle to the device. - -- Implements **IPnpCallbackHardware** interface and initializes USB I/O targets in **IPnpCallbackHardware::OnPrepareHardware** method. - -- Creates a sequential queue for handling IOCTL requests. - -- Adds code to handle the IOCTL to set bar graph display. - -- Creates a parallel queue for handling read and write requests. - -- Retrieves memory from read and write requests, format the requests, and sends them to a USB target. - -- Supports additional IOCTLs to get and set the 7-segment display, get bar graph display, and get config descriptor. - -- Sets power policy for the device. - -- Adds code to indicate that the device is ready by lighting up the period on 7-segment display. - -- Calls **SetupDi** functions to determine the "BusTypeGUID" of the device, and uses impersonation to access resources that only the caller has access to. - -- Shows how to implement idle and wake functionality to make the driver the power policy owner (PPO). The sample achieves this using power-managed queues and UMDF DDIs, AssignS0IdleSettings, and AssignSxWakeSettings. - -- Demonstrates implementation of a continuous reader. - -- Demonstrates the use of impersonation. - -### usb\\umdf\_fx2\\exe - -This directory contains a test application that can be used to drive the UMDF driver and FX2 device. This is a modified version of the test application for the KMDF Fx2 driver. - -### usb\\umdf\_fx2\\deviceMetadata - -This directory contains the device metadata package for the sample. You must copy the device metadata to the system before installing the device. For information on how to update and deploy device metadata, see [Custom driver access sample](https://go.microsoft.com/fwlink/p/?linkid=2114373). diff --git a/usb/umdf_fx2/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms b/usb/umdf_fx2/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms deleted file mode 100644 index 5f8e82ee8..000000000 Binary files a/usb/umdf_fx2/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms and /dev/null differ diff --git a/usb/umdf_fx2/driver/ControlQueue.cpp b/usb/umdf_fx2/driver/ControlQueue.cpp deleted file mode 100644 index f4058941f..000000000 --- a/usb/umdf_fx2/driver/ControlQueue.cpp +++ /dev/null @@ -1,564 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "winioctl.h" - -#include "ControlQueue.tmh" - -CMyControlQueue::CMyControlQueue( - _In_ PCMyDevice Device - ) : CMyQueue(Device) -{ - -} - -HRESULT -STDMETHODCALLTYPE -CMyControlQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDeviceIoControl(); - - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyControlQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyControlQueue queue = NULL; - HRESULT hr = S_OK; - - queue = new CMyControlQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyControlQueue::Initialize( - VOID - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - // - // The framework (UMDF) will not deliver a - // request to the driver that arrives on a power-managed queue, unless - // the device is in a powered-up state. If you receive a request on a - // power-managed queue after the device has idled out, - // the framework will not be able to power-up and present the request - // to the driver unless it is the power policy owner (PPO). - // Since this driver is the PPO it can use power managed queues - // - - hr = __super::Initialize(WdfIoQueueDispatchSequential, - false, - true /* use power managed queue */); - - // - // return the status. - // - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyControlQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *FxQueue, - _In_ IWDFIoRequest *FxRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Aruments: - - FxQueue - Framework Queue instance - FxRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Lenth of input buffer - OutputBufferSizeInBytes - Lenth of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - - IWDFMemory *memory = NULL; - PVOID buffer; - - SIZE_T bigBufferCb; - - ULONG information = 0; - - bool completeRequest = true; - - HRESULT hr = S_OK; - - switch (ControlCode) - { - case IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR: - { - // - // Get the output buffer. - // - - FxRequest->GetOutputMemory(&memory ); - - // - // request the descriptor. - // - - ULONG bufferCb; - - // - // Get the buffer address then release the memory object. - // The memory object remains valid until the request is - // completed. - // - - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - if (bigBufferCb > ULONG_MAX) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - break; - } - else - { - bufferCb = (ULONG) bigBufferCb; - } - - hr = m_Device->GetUsbTargetDevice()->RetrieveDescriptor( - USB_CONFIGURATION_DESCRIPTOR_TYPE, - 0, - 0, - &bufferCb, - (PUCHAR) buffer - ); - - if (SUCCEEDED(hr)) - { - information = bufferCb; - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the result of the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->GetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - // - // If that worked then record how many bytes of data we're - // returning. - // - - if (SUCCEEDED(hr)) - { - information = sizeof(BAR_GRAPH_STATE); - } - - break; - } - - case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the result of the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(SEVEN_SEGMENT)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - hr = m_Device->GetSevenSegmentDisplay((PSEVEN_SEGMENT) buffer); - } - - // - // If that worked then record how many bytes of data we're - // returning. - // - - if (SUCCEEDED(hr)) - { - information = sizeof(SEVEN_SEGMENT); - } - - break; - } - - case IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(SEVEN_SEGMENT)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory ); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetSevenSegmentDisplay((PSEVEN_SEGMENT) buffer); - } - break; - } - - case IOCTL_OSRUSBFX2_READ_SWITCHES: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (OutputBufferSizeInBytes < sizeof(SWITCH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetOutputMemory(&memory ); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->ReadSwitchState((PSWITCH_STATE) buffer); - } - - if (SUCCEEDED(hr)) - { - information = sizeof(SWITCH_STATE); - } - - break; - } - - case IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE: - { - // - // Make sure the buffer is big enough to hold the switch - // state. - // - - if (OutputBufferSizeInBytes < sizeof(SWITCH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - // - // Forward the request to the switch state change queue. - // - - hr = FxRequest->ForwardToIoQueue( - m_Device->GetSwitchChangeQueue() - ); - - if (SUCCEEDED(hr)) - { - completeRequest = false; - } - } - - break; - } - - case IOCTL_OSRUSBFX2_RESET_DEVICE: - case IOCTL_OSRUSBFX2_REENUMERATE_DEVICE: - { - // - // WinUSB does not allow us to reset or re-enumerate the device. - // Return not-supported for the error in both of these cases. - // - - hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - break; - } - - case IOCTL_OSRUSBFX2_PLAY_FILE: - { - // - // This IOCTL demonstrates how to use impersonation to access - // resources using the credentials provided by the client. Note - // that for impersonation to work it has to be enabled in the device - // INF and the client must allow impersonation when they open the - // device. - // - // This IOCTL opens a file using the path provided by the client - // and then plays the characters in that file out to the seven segment - // display in a worker thread. - // - - PFILE_PLAYBACK playback; - SIZE_T playbackCb; - size_t realPlaybackCb; - - FxRequest->GetInputMemory(&memory); - - if (memory == NULL) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Get the playback structure from the input buffer. - // - - playback = (PFILE_PLAYBACK) memory->GetDataBuffer(&playbackCb); - - memory->Release(); - - // - // Make sure the length is at least as big as the fixed portion - // of the input structure. - // - - if (playbackCb < (FIELD_OFFSET(FILE_PLAYBACK, Path))) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Make sure the file name is at least one character long. - // - - playbackCb -= FIELD_OFFSET(FILE_PLAYBACK, Path); - - if (playbackCb < sizeof(WCHAR)) - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); - break; - } - - // - // Verify that the string provided is valid. - // - - hr = StringCbLength(playback->Path, - min(playbackCb, (STRSAFE_MAX_CCH * sizeof(WCHAR))), - &realPlaybackCb); - - if (FAILED(hr)) - { - break; - } - - hr = m_Device->PlaybackFile(playback, FxRequest); - - break; - } - - - - default: - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION); - break; - } - } - - if (completeRequest) - { - FxRequest->CompleteWithInformation(hr, information); - } - - return; -} diff --git a/usb/umdf_fx2/driver/ControlQueue.h b/usb/umdf_fx2/driver/ControlQueue.h deleted file mode 100644 index 251521e1b..000000000 --- a/usb/umdf_fx2/driver/ControlQueue.h +++ /dev/null @@ -1,101 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.h - -Abstract: - - This file defines the queue callback object for handling device I/O - control requests. This is a serialized queue. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyControlQueue : public IQueueCallbackDeviceIoControl, - public CMyQueue -{ - HRESULT - Initialize( - VOID - ); - -public: - - CMyControlQueue( - _In_ PCMyDevice Device - ); - - virtual - ~CMyControlQueue( - VOID - ) - { - return; - } - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // - // IQueueCallbackDeviceIoControl - // - STDMETHOD_ (void, OnDeviceIoControl)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); -}; - diff --git a/usb/umdf_fx2/driver/Device.cpp b/usb/umdf_fx2/driver/Device.cpp deleted file mode 100644 index 101b3b796..000000000 --- a/usb/umdf_fx2/driver/Device.cpp +++ /dev/null @@ -1,2091 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 driver's - device callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" -#include - -#include "device.tmh" -#define CONCURRENT_READS 2 - -CMyDevice::~CMyDevice( - ) -{ - SAFE_RELEASE(m_pIoTargetInterruptPipeStateMgmt); -} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the OSR Fx2 driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice2 *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: If you're writing a filter driver then indicate that here. - // And then don't claim power policy ownership below - // - // FxDeviceInit->SetFilter(); - // - - // - // Set the Fx2 driver as the power policy owner. - // - - FxDeviceInit->SetPowerPolicyOwnership(TRUE); - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - IWDFDevice* device1; - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &device1); - - // - // Convert the interface to version 2 - // - - if (SUCCEEDED(hr)) { - device1->QueryInterface(IID_PPV_ARGS(&fxDevice)); - _Analysis_assume_(fxDevice != NULL); - device1->Release(); - } - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - // - // Get the bus type GUID for the device and confirm that we're attached to - // USB. - // - // NOTE: Since this device only supports USB we'd normally trust our INF - // to ensure this. - // - // But if the device also supported 1394 then we could - // use this to determine which type of bus we were attached to. - // - - hr = GetBusTypeGuid(); - - if (FAILED(hr)) - { - return hr; - } - - // - // Create the read-write queue. - // - - hr = CMyReadWriteQueue::CreateInstance(this, &m_ReadWriteQueue); - - if (FAILED(hr)) - { - return hr; - } - - // - // We use default queue for read/write - // - - hr = m_ReadWriteQueue->Configure(); - - m_ReadWriteQueue->Release(); - - // - // Create the control queue and configure forwarding for IOCTL requests. - // - - if (SUCCEEDED(hr)) - { - hr = CMyControlQueue::CreateInstance(this, &m_ControlQueue); - - if (SUCCEEDED(hr)) - { - hr = m_ControlQueue->Configure(); - if (SUCCEEDED(hr)) - { - m_FxDevice->ConfigureRequestDispatching( - m_ControlQueue->GetFxQueue(), - WdfRequestDeviceIoControl, - true - ); - } - m_ControlQueue->Release(); - } - } - - // - // Create a manual I/O queue to hold requests for notification when - // the switch state changes. - // - - hr = m_FxDevice->CreateIoQueue(NULL, - FALSE, - WdfIoQueueDispatchManual, - FALSE, - FALSE, - &m_SwitchChangeQueue); - - - // - // Release creation reference as object tree will keep a reference - // - - m_SwitchChangeQueue->Release(); - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_OSRUSBFX2, - NULL); - } - - // - // Mark the interface as restricted to allow access to applications bound - // using device metadata. Failures here are not fatal so we log them but - // ignore them otherwise. - // - if (SUCCEEDED(hr)) - { - WDF_PROPERTY_STORE_ROOT RootSpecifier; - IWDFUnifiedPropertyStoreFactory * pUnifiedPropertyStoreFactory = NULL; - IWDFUnifiedPropertyStore * pUnifiedPropertyStore = NULL; - DEVPROP_BOOLEAN isRestricted = DEVPROP_TRUE; - HRESULT hrSetProp; - - hrSetProp = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pUnifiedPropertyStoreFactory)); - - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrSetProp)); - - RootSpecifier.LengthCb = sizeof(RootSpecifier); - RootSpecifier.RootClass = WdfPropertyStoreRootClassDeviceInterfaceKey; - RootSpecifier.Qualifier.DeviceInterfaceKey.InterfaceGUID = &GUID_DEVINTERFACE_OSRUSBFX2; - RootSpecifier.Qualifier.DeviceInterfaceKey.ReferenceString = NULL; - - hrSetProp = pUnifiedPropertyStoreFactory->RetrieveUnifiedDevicePropertyStore(&RootSpecifier, - &pUnifiedPropertyStore); - - if (SUCCEEDED(hrSetProp)) - { - hrSetProp = pUnifiedPropertyStore->SetPropertyData(&DEVPKEY_DeviceInterface_Restricted, - 0, // Lcid - 0, // Flags - DEVPROP_TYPE_BOOLEAN, - sizeof(isRestricted), - &isRestricted); - } - - if (FAILED(hrSetProp)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Could not set restricted property %!HRESULT!", - hrSetProp - ); - } - - SAFE_RELEASE(pUnifiedPropertyStoreFactory); - SAFE_RELEASE(pUnifiedPropertyStore); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackHardware))) - { - *Object = QueryIPnpCallbackHardware(); - hr = S_OK; - } - else if (IsEqualIID(InterfaceId, __uuidof(IPnpCallback))) - { - *Object = QueryIPnpCallback(); - hr = S_OK; - } - else if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackSelfManagedIo))) - { - *Object = QueryIPnpCallbackSelfManagedIo(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IUsbTargetPipeContinuousReaderCallbackReadersFailed))) - { - *Object = QueryContinousReaderFailureCompletion(); - hr = S_OK; - } - else if(IsEqualIID(InterfaceId, __uuidof(IUsbTargetPipeContinuousReaderCallbackReadComplete))) - { - *Object = QueryContinousReaderCompletion(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnPrepareHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked to ready the driver - to talk to hardware. It opens the handle to the - device and talks to it using the WINUSB interface. - It invokes WINUSB to discver the interfaces and stores - the information related to bulk endpoints. - -Arguments: - - FxDevice : Pointer to the WDF device interface - -Return Value: - - HRESULT - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - // - // Get the device name. - // Get the length to allocate first - // - - hr = m_FxDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!HRESULT!", - hr - ); - } - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Device name %S", - deviceName - ); - } - - // - // Create USB I/O Targets and configure them - // - - if (SUCCEEDED(hr)) - { - hr = CreateUsbIoTargets(); - } - - if (SUCCEEDED(hr)) - { - ULONG length = sizeof(m_Speed); - - hr = m_pIUsbTargetDevice->RetrieveDeviceInformation(DEVICE_SPEED, - &length, - &m_Speed); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb device speed information %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Speed - %x\n", - m_Speed - ); - } - - if (SUCCEEDED(hr)) - { - hr = ConfigureUsbPipes(); - } - - // Setup power-management settings on the device. - // - - if (SUCCEEDED(hr)) - { - hr = SetPowerManagement(); - } - - // - // - // Clear the seven segement display to indicate that we're done with - // prepare hardware. - // - - if (SUCCEEDED(hr)) - { - hr = IndicateDeviceReady(); - } - - if (SUCCEEDED(hr)) - { - hr = ConfigContReaderForInterruptEndPoint(); - } - - delete[] deviceName; - - return hr; -} - -HRESULT -CMyDevice::OnReleaseHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. - -Arguments: - - FxDevice - Pointer to the Device object. - -Return Value: - - HRESULT - Always succeeds. - ---*/ -{ - // - // Delete USB Target Device WDF Object, this will in turn - // delete all the children - interface and the pipe objects - // - // This makes sure that - // 1. We drain the the pending read which does not come from an I/O queue - // 2. We remove USB target objects from object tree (and thereby free them) - // before any potential subsequent OnPrepareHardware creates new ones - // - // m_pIUsbTargetDevice could be NULL if OnPrepareHardware failed so we need - // to guard against that - // - - if (m_pIUsbTargetDevice) - { - m_pIUsbTargetDevice->DeleteWdfObject(); - } - - return S_OK; -} - -HRESULT -CMyDevice::CreateUsbIoTargets( - ) -/*++ - -Routine Description: - - This routine creates Usb device, interface and pipe objects - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr; - UCHAR NumEndPoints = 0; - IWDFUsbTargetFactory * pIUsbTargetFactory = NULL; - IWDFUsbTargetDevice * pIUsbTargetDevice = NULL; - IWDFUsbInterface * pIUsbInterface = NULL; - IWDFUsbTargetPipe * pIUsbPipe = NULL; - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pIUsbTargetFactory)); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb target factory %!HRESULT!", - hr - ); - } - - if (SUCCEEDED(hr)) - { - hr = pIUsbTargetFactory->CreateUsbTargetDevice( - &pIUsbTargetDevice); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to create USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbTargetDevice = pIUsbTargetDevice; - - // - // Release the creation reference as object tree will maintain a reference - // - - pIUsbTargetDevice->Release(); - } - } - - if (SUCCEEDED(hr)) - { - UCHAR NumInterfaces = pIUsbTargetDevice->GetNumInterfaces(); - - WUDF_TEST_DRIVER_ASSERT(1 == NumInterfaces); - - hr = pIUsbTargetDevice->RetrieveUsbInterface(0, &pIUsbInterface); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB interface from USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbInterface = pIUsbInterface; - - pIUsbInterface->Release(); //release creation reference - } - } - - if (SUCCEEDED(hr)) - { - NumEndPoints = pIUsbInterface->GetNumEndPoints(); - - if (NumEndPoints != NUM_OSRUSB_ENDPOINTS) { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Has %d endpoints, expected %d, returning %!HRESULT! ", - NumEndPoints, - NUM_OSRUSB_ENDPOINTS, - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - for (UCHAR PipeIndex = 0; PipeIndex < NumEndPoints; PipeIndex++) - { - hr = pIUsbInterface->RetrieveUsbPipeObject(PipeIndex, - &pIUsbPipe); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB Pipe for PipeIndex %d, %!HRESULT!", - PipeIndex, - hr - ); - } - else - { - if ( pIUsbPipe->IsInEndPoint() ) - { - if ( UsbdPipeTypeInterrupt == pIUsbPipe->GetType() ) - { - m_pIUsbInterruptPipe = pIUsbPipe; - - WUDF_TEST_DRIVER_ASSERT (m_pIoTargetInterruptPipeStateMgmt == NULL); - - hr = m_pIUsbInterruptPipe->QueryInterface(__uuidof( - IWDFIoTargetStateManagement), - reinterpret_cast(&m_pIoTargetInterruptPipeStateMgmt) - ); - if (FAILED(hr)) - { - m_pIoTargetInterruptPipeStateMgmt = NULL; - } - } - else if ( UsbdPipeTypeBulk == pIUsbPipe->GetType() ) - { - m_pIUsbInputPipe = pIUsbPipe; - } - else - { - pIUsbPipe->DeleteWdfObject(); - } - } - else if ( pIUsbPipe->IsOutEndPoint() && (UsbdPipeTypeBulk == pIUsbPipe->GetType()) ) - { - m_pIUsbOutputPipe = pIUsbPipe; - } - else - { - pIUsbPipe->DeleteWdfObject(); - } - - SAFE_RELEASE(pIUsbPipe); //release creation reference - } - } - - if (NULL == m_pIUsbInputPipe || NULL == m_pIUsbOutputPipe) - { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Input or output pipe not found, returning %!HRESULT!", - hr - ); - } - } - - SAFE_RELEASE(pIUsbTargetFactory); - - return hr; -} - -HRESULT -CMyDevice::ConfigureUsbPipes( - ) -/*++ - -Routine Description: - - This routine retrieves the IDs for the bulk end points of the USB device. - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr = S_OK; - LONG timeout; - - // - // Set timeout policies for input/output pipes - // - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbInputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for input pipe %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbOutputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for output pipe %!HRESULT!", - hr - ); - } - } - - return hr; -} - -HRESULT -CMyDevice::IndicateDeviceReady( - VOID - ) -/*++ - - Routine Description: - - This method lights the period on the device's seven-segment display to - indicate that the driver's PrepareHardware method has completed. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - SEVEN_SEGMENT display = {0}; - - HRESULT hr; - - // - // First read the contents of the seven segment display. - // - - hr = GetSevenSegmentDisplay(&display); - - if (SUCCEEDED(hr)) - { - display.Segments |= 0x08; - - hr = SetSevenSegmentDisplay(&display); - } - - return hr; -} - -HRESULT -CMyDevice::GetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the contents of the buffer - the controller OR's in every - // light that's set. - // - - BarGraphState->BarsAsUChar = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesTransferred - ); - - - return hr; -} - -HRESULT -CMyDevice::GetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the output buffer - the device will or in the bits for - // the lights that are set. - // - - SevenSegment->Segments = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_7SEGMENT_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SevenSegment, - sizeof(SEVEN_SEGMENT), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_7SEGMENT_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SevenSegment, - sizeof(SEVEN_SEGMENT), - &bytesTransferred - ); - - return hr; -} - -HRESULT -CMyDevice::ReadSwitchState( - _In_ PSWITCH_STATE SwitchState - ) -/*++ - - Routine Description: - - This method synchronously retrieves the bar graph display information - from the OSR USB-FX2 device. It uses the buffers in the FxRequest - to hold the data it retrieves. - - Arguments: - - FxRequest - the request for the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesReturned; - - HRESULT hr = S_OK; - - // - // Zero the output buffer - the device will or in the bits for - // the lights that are set. - // - - SwitchState->SwitchesAsUChar = 0; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestDeviceToHost, - BmRequestToDevice, - USBFX2LK_READ_SWITCHES, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) SwitchState, - sizeof(SWITCH_STATE), - &bytesReturned - ); - - return hr; -} - -HRESULT -CMyDevice::SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ) -{ - HRESULT hr = S_OK; - HRESULT hrRequest = S_OK; - IWDFIoRequest *pWdfRequest = NULL; - IWDFDriver * FxDriver = NULL; - IWDFMemory * FxMemory = NULL; - IWDFRequestCompletionParams * FxComplParams = NULL; - IWDFUsbRequestCompletionParams * FxUsbComplParams = NULL; - - *LengthTransferred = 0; - - hr = m_FxDevice->CreateRequest( NULL, //pCallbackInterface - NULL, //pParentObject - &pWdfRequest); - hrRequest = hr; - - if (SUCCEEDED(hr)) - { - m_FxDevice->GetDriver(&FxDriver); - - hr = FxDriver->CreatePreallocatedWdfMemory( Buffer, - BufferLength, - NULL, //pCallbackInterface - pWdfRequest, //pParetObject - &FxMemory ); - } - - if (SUCCEEDED(hr)) - { - hr = m_pIUsbTargetDevice->FormatRequestForControlTransfer( pWdfRequest, - SetupPacket, - FxMemory, - NULL); //TransferOffset - } - - if (SUCCEEDED(hr)) - { - hr = pWdfRequest->Send( m_pIUsbTargetDevice, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - 0); //Timeout - } - - if (SUCCEEDED(hr)) - { - pWdfRequest->GetCompletionParams(&FxComplParams); - - hr = FxComplParams->GetCompletionStatus(); - } - - if (SUCCEEDED(hr)) - { - HRESULT hrQI = FxComplParams->QueryInterface(IID_PPV_ARGS(&FxUsbComplParams)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - WUDF_TEST_DRIVER_ASSERT( WdfUsbRequestTypeDeviceControlTransfer == - FxUsbComplParams->GetCompletedUsbRequestType() ); - - FxUsbComplParams->GetDeviceControlTransferParameters( NULL, - LengthTransferred, - NULL, - NULL ); - } - - SAFE_RELEASE(FxUsbComplParams); - SAFE_RELEASE(FxComplParams); - SAFE_RELEASE(FxMemory); - - if (SUCCEEDED(hrRequest)) - { - pWdfRequest->DeleteWdfObject(); - } - SAFE_RELEASE(pWdfRequest); - - SAFE_RELEASE(FxDriver); - - return hr; -} - -WDF_IO_TARGET_STATE -CMyDevice::GetTargetState( - IWDFIoTarget * pTarget - ) -{ - IWDFIoTargetStateManagement * pStateMgmt = NULL; - WDF_IO_TARGET_STATE state; - - HRESULT hrQI = pTarget->QueryInterface(IID_PPV_ARGS(&pStateMgmt)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pStateMgmt)); - - state = pStateMgmt->GetState(); - - SAFE_RELEASE(pStateMgmt); - - return state; -} - -VOID -CMyDevice::ServiceSwitchChangeQueue( - _In_ SWITCH_STATE NewState, - _In_ HRESULT CompletionStatus, - _In_opt_ IWDFFile *SpecificFile - ) -/*++ - - Routine Description: - - This method processes switch-state change notification requests as - part of reading the OSR device's interrupt pipe. As each read completes - this pulls all pending I/O off the switch change queue and completes - each request with the current switch state. - - Arguments: - - NewState - the state of the switches - - CompletionStatus - all pending operations are completed with this status. - - SpecificFile - if provided only requests for this file object will get - completed. - - Return Value: - - None - ---*/ -{ - IWDFIoRequest *fxRequest; - - HRESULT enumHr = S_OK; - - do - { - HRESULT hr; - - // - // Get the next request. - // - - if (NULL != SpecificFile) - { - enumHr = m_SwitchChangeQueue->RetrieveNextRequestByFileObject( - SpecificFile, - &fxRequest - ); - } - else - { - enumHr = m_SwitchChangeQueue->RetrieveNextRequest(&fxRequest); - } - - // - // if we got one then complete it. - // - - if (SUCCEEDED(enumHr)) - { - if (SUCCEEDED(CompletionStatus)) - { - IWDFMemory *fxMemory; - - // - // First copy the result to the request buffer. - // - - fxRequest->GetOutputMemory(&fxMemory ); - - hr = fxMemory->CopyFromBuffer(0, - &NewState, - sizeof(SWITCH_STATE)); - fxMemory->Release(); - } - else - { - hr = CompletionStatus; - } - - // - // Complete the request with the status of the copy (or the completion - // status if that was an error). - // - - if (SUCCEEDED(hr)) - { - fxRequest->CompleteWithInformation(hr, sizeof(SWITCH_STATE)); - } - else - { - fxRequest->Complete(hr); - } - - fxRequest->Release(); - } - } - while (SUCCEEDED(enumHr)); -} - -HRESULT -CMyDevice::SetPowerManagement( - VOID - ) -/*++ - - Routine Description: - - This method enables the idle and wake functionality - using UMDF. UMDF has been set as the power policy - owner (PPO) for the device stack and we are using power - managed queues. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - HRESULT hr; - - // - // Enable USB selective suspend on the device. - // - - hr = m_FxDevice->AssignS0IdleSettings( IdleUsbSelectiveSuspend, - PowerDeviceMaximum, - IDLE_TIMEOUT_IN_MSEC, - IdleAllowUserControl, - WdfUseDefault); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to assign S0 idle settings for the device %!HRESULT!", - hr - ); - } - - // - // Enable Sx wake settings - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->AssignSxWakeSettings( PowerDeviceMaximum, - WakeAllowUserControl, - WdfUseDefault); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set Sx Wake Settings for the device %!HRESULT!", - hr - ); - } - - } - - - return hr; -} - -HRESULT -CMyDevice::OnD0Entry( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - UNREFERENCED_PARAMETER(previousState); - - // - // Start/Stop the I/O target if you support a continuous reader. - // The rest of the I/O is fed through power managed queues. The queue - // itself will stop feeding I/O to targets (and will wait for any pending - // I/O to complete before going into low power state), hence targets - // don�t need to be stopped/started. The continuous reader I/O is outside - // of power managed queues so we need to Stop the I/O target on D0Exit and - // start it on D0Entry. Please note that bulk pipe target doesn't need to - // be stopped/started because I/O submitted to this pipe comes from power - // managed I/O queue, which delivers I/O only in power on state. - // - - m_pIoTargetInterruptPipeStateMgmt->Start(); - - return S_OK; -} - -HRESULT -CMyDevice::OnD0Exit( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - UNREFERENCED_PARAMETER(previousState); - - // - // Stop the I/O target always succeedes. - // - m_pIoTargetInterruptPipeStateMgmt->Stop(WdfIoTargetCancelSentIo); - return S_OK; -} - -void -CMyDevice::OnSurpriseRemoval( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return; -} - -HRESULT -CMyDevice::OnQueryRemove( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnQueryStop( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -// -// Self Managed Io Callbacks -// - -VOID -CMyDevice::OnSelfManagedIoCleanup( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return; -} - -VOID -CMyDevice::OnSelfManagedIoFlush( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - - // - // Complete every switch change operation with an error. - // - ServiceSwitchChangeQueue(m_SwitchState, - HRESULT_FROM_WIN32(ERROR_DEVICE_REMOVED), - NULL); - - return; -} - -HRESULT -CMyDevice::OnSelfManagedIoInit( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoRestart( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoStop( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - -HRESULT -CMyDevice::OnSelfManagedIoSuspend( - _In_ IWDFDevice* pWdfDevice - ) -{ - UNREFERENCED_PARAMETER(pWdfDevice); - return S_OK; -} - - - -HRESULT -CMyDevice::ConfigContReaderForInterruptEndPoint( - VOID - ) -/*++ - -Routine Description: - - This routine configures a continuous reader on the - interrupt endpoint. It's called from the PrepareHarware event. - -Arguments: - - -Return Value: - - HRESULT value - ---*/ -{ - HRESULT hr, hrQI; - IUsbTargetPipeContinuousReaderCallbackReadComplete *pOnCompletionCallback = NULL; - IUsbTargetPipeContinuousReaderCallbackReadersFailed *pOnFailureCallback= NULL; - IWDFUsbTargetPipe2 * pIUsbInterruptPipe2; - - hrQI = this->QueryInterface(IID_PPV_ARGS(&pOnCompletionCallback)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pOnCompletionCallback)); - - hrQI = this->QueryInterface(IID_PPV_ARGS(&pOnFailureCallback)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pOnFailureCallback)); - - hrQI = m_pIUsbInterruptPipe->QueryInterface(IID_PPV_ARGS(&pIUsbInterruptPipe2)); - WUDF_TEST_DRIVER_ASSERT((SUCCEEDED(hrQI) && pIUsbInterruptPipe2)); - - // - // Reader requests are not posted to the target automatically. - // Driver must explictly call WdfIoTargetStart to kick start the - // reader. In this sample, it's done in D0Entry. - // By defaut, framework queues two requests to the target - // endpoint. Driver can configure up to 10 requests with the - // parameter CONCURRENT_READS - // - hr = pIUsbInterruptPipe2->ConfigureContinuousReader( sizeof(m_SwitchStateBuffer), - 0,//header - 0,//trailer - CONCURRENT_READS, - NULL, - pOnCompletionCallback, - m_pIUsbInterruptPipe, - pOnFailureCallback - ); - - if (FAILED(hr)) { - TraceEvents(TRACE_LEVEL_ERROR, TEST_TRACE_DEVICE, - "OsrFxConfigContReaderForInterruptEndPoint failed %!HRESULT!", - hr); - } - - SAFE_RELEASE(pOnCompletionCallback); - SAFE_RELEASE(pOnFailureCallback); - SAFE_RELEASE(pIUsbInterruptPipe2); - - return hr; -} - - -BOOL -CMyDevice::OnReaderFailure( - IWDFUsbTargetPipe * pPipe, - HRESULT hrCompletion - ) -{ - UNREFERENCED_PARAMETER(pPipe); - - m_InterruptReadProblem = hrCompletion; - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Failure completed with %!HRESULT!", - hrCompletion - ); - - ServiceSwitchChangeQueue(m_SwitchState, - hrCompletion, - NULL); - - return TRUE; -} - -VOID -CMyDevice::OnReaderCompletion( - IWDFUsbTargetPipe * pPipe, - IWDFMemory * pMemory, - SIZE_T NumBytesTransferred, - PVOID Context - ) -{ - WUDF_TEST_DRIVER_ASSERT(pPipe == (IWDFUsbTargetPipe *)Context); - - // - // Make sure that there is data in the read packet. Depending on the device - // specification, it is possible for it to return a 0 length read in - // certain conditions. - // - - if (NumBytesTransferred == 0) { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Zero length read occured on the Interrupt Pipe's " - "Continuous Reader\n" - ); - return; - } - - WUDF_TEST_DRIVER_ASSERT(NumBytesTransferred == sizeof(m_SwitchState)); - - // - // Get the switch state - // - - PVOID pBuff = pMemory->GetDataBuffer(NULL); - - CopyMemory(&m_SwitchState, pBuff, sizeof(m_SwitchState)); - - - // - // Satisfy application request for switch change notification - // - - ServiceSwitchChangeQueue(m_SwitchState, - S_OK, - NULL); - - // - // Make sure that the request that got completed is the one that we reuse - // Don't Delete the request because it gets reused - // -} - - -HRESULT -CMyDevice::GetBusTypeGuid( - VOID - ) -/*++ - - Routine Description: - - This routine gets the device instance ID then invokes SetupDi to - retrieve the bus type guid for the device. The bus type guid is - stored in object. - - Arguments: - - None - - Return Value: - - Status - ---*/ -{ - ULONG instanceIdCch = 0; - PWSTR instanceId = NULL; - - HDEVINFO deviceInfoSet = NULL; - SP_DEVINFO_DATA deviceInfo = {sizeof(SP_DEVINFO_DATA)}; - - HRESULT hr; - - // - // Retrieve the device instance ID. - // - - hr = m_FxDevice->RetrieveDeviceInstanceId(NULL, &instanceIdCch); - - if (FAILED(hr)) - { - goto Exit; - } - - instanceId = new WCHAR[instanceIdCch]; - - if (instanceId == NULL) - { - hr = E_OUTOFMEMORY; - goto Exit; - } - - hr = m_FxDevice->RetrieveDeviceInstanceId(instanceId, &instanceIdCch); - - if (FAILED(hr)) - { - goto Exit2; - } - - // - // Call SetupDI to open the device info. - // - - deviceInfoSet = SetupDiCreateDeviceInfoList(NULL, NULL); - - if (deviceInfoSet == INVALID_HANDLE_VALUE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit2; - } - - if (SetupDiOpenDeviceInfo(deviceInfoSet, - instanceId, - NULL, - 0, - &deviceInfo) == FALSE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit3; - } - - if (SetupDiGetDeviceRegistryProperty(deviceInfoSet, - &deviceInfo, - SPDRP_BUSTYPEGUID, - NULL, - (PBYTE) &m_BusTypeGuid, - sizeof(m_BusTypeGuid), - NULL) == FALSE) - { - hr = HRESULT_FROM_WIN32(GetLastError()); - goto Exit3; - } - -Exit3: - SetupDiDestroyDeviceInfoList(deviceInfoSet); - -Exit2: - - delete[] instanceId; - -Exit: - - return hr; -} - -HRESULT -CMyDevice::PlaybackFile( - _In_ PFILE_PLAYBACK PlayInfo, - _In_ IWDFIoRequest *FxRequest - ) -/*++ - - Routine Description: - - This method impersonates the caller, opens the file and prints each - character to the seven segement display. - - Arguments: - - PlayInfo - the playback info from the request. - - FxRequest - the request (used for impersonation) - - Return Value: - - Status - ---*/ - -{ - PLAYBACK_IMPERSONATION_CONTEXT context = {PlayInfo, NULL, S_OK}; - IWDFIoRequest2* fxRequest2; - - HRESULT hr; - - // Convert FxRequest to FxRequest2. No error can occur here. - FxRequest->QueryInterface(IID_PPV_ARGS(&fxRequest2)); - _Analysis_assume_(fxRequest2 != NULL); - - // - // Impersonate and open the playback file. - // - - hr = FxRequest->Impersonate( - SecurityImpersonation, - this->QueryIImpersonateCallback(), - &context - ); - if (FAILED(hr)) - { - goto exit; - } - - // - // Release the reference that was added in QueryIImpersonateCallback() - // - this->Release(); - - hr = context.Hr; - - if (FAILED(hr)) - { - goto exit; - } - - // - // The impersonation callback succeeded - tell code analysis that the - // file handle is non-null - // - - _Analysis_assume_(context.FileHandle != NULL); - - // - // Read from the file one character at a time until we hit - // EOF or the request is cancelled. - // - - do - { - UCHAR c; - ULONG bytesRead; - - // - // Check for cancellation. - // - - if (fxRequest2->IsCanceled()) - { - hr = HRESULT_FROM_WIN32(ERROR_CANCELLED); - } - else - { - BOOL result; - - // - // Read a character from the file and see if we can - // encode it on the display. - // - - result = ReadFile(context.FileHandle, - &c, - sizeof(c), - &bytesRead, - NULL); - - if (result) - { - SEVEN_SEGMENT segment; - BAR_GRAPH_STATE barGraph; - - if (bytesRead > 0) - { - #pragma prefast(suppress:__WARNING_USING_UNINIT_VAR,"Above this->Release() method does not actually free 'this'") - if(EncodeSegmentValue(c, &segment) == true) - { - barGraph.BarsAsUChar = c; - - SetSevenSegmentDisplay(&segment); - SetBarGraphDisplay(&barGraph); - } - - Sleep(PlayInfo->Delay); - } - else - { - hr = S_OK; - break; - } - } - else - { - hr = HRESULT_FROM_WIN32(GetLastError()); - } - } - - } while(SUCCEEDED(hr)); - - CloseHandle(context.FileHandle); - -exit: - - fxRequest2->Release(); - return hr; -} - -VOID -CMyDevice::OnImpersonate( - _In_ PVOID Context - ) -/*++ - - Routine Description: - - This routine handles the impersonation for the PLAY FILE I/O control. - - Arguments: - - Context - pointer to the impersonation context - - Return Value: - - None - ---*/ -{ - PPLAYBACK_IMPERSONATION_CONTEXT context; - - context = (PPLAYBACK_IMPERSONATION_CONTEXT) Context; - - context->FileHandle = CreateFile(context->PlaybackInfo->Path, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (context->FileHandle == INVALID_HANDLE_VALUE) - { - DWORD error = GetLastError(); - context->Hr = HRESULT_FROM_WIN32(error); - } - else - { - context->Hr = S_OK; - } - - return; -} - -#define SS_LEFT (SS_TOP_LEFT | SS_BOTTOM_LEFT) -#define SS_RIGHT (SS_TOP_RIGHT | SS_BOTTOM_RIGHT) - -bool -CMyDevice::EncodeSegmentValue( - _In_ UCHAR Character, - _Out_ SEVEN_SEGMENT *SevenSegment - ) -{ - UCHAR letterMap[] = { - (SS_TOP | SS_BOTTOM_LEFT | SS_RIGHT | SS_CENTER | SS_BOTTOM), // a - (SS_LEFT | SS_CENTER | SS_BOTTOM | SS_BOTTOM_RIGHT), // b - (SS_CENTER | SS_BOTTOM_LEFT | SS_BOTTOM), // c - (SS_BOTTOM_LEFT | SS_CENTER | SS_BOTTOM | SS_RIGHT), // d - (SS_LEFT | SS_TOP | SS_CENTER | SS_BOTTOM), // e - (SS_LEFT | SS_TOP | SS_CENTER), // f - (SS_TOP | SS_TOP_LEFT | SS_CENTER | SS_BOTTOM | SS_RIGHT), // g - (SS_LEFT | SS_RIGHT | SS_CENTER), // h - (SS_BOTTOM_LEFT), // i - (SS_BOTTOM | SS_RIGHT), // j - (SS_LEFT | SS_CENTER | SS_BOTTOM), // k - (SS_LEFT | SS_BOTTOM), // l - (SS_LEFT | SS_TOP | SS_RIGHT), // m - (SS_BOTTOM_LEFT | SS_CENTER | SS_BOTTOM_RIGHT), // n - (SS_BOTTOM_LEFT | SS_BOTTOM_RIGHT | SS_CENTER | SS_BOTTOM), // o - (SS_LEFT | SS_TOP | SS_CENTER | SS_TOP_RIGHT), // p - (SS_TOP_LEFT | SS_TOP | SS_CENTER | SS_RIGHT), // q - (SS_BOTTOM_LEFT | SS_CENTER), // r - (SS_TOP_LEFT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_RIGHT), // s - (SS_TOP | SS_RIGHT), // t - (SS_LEFT | SS_RIGHT | SS_BOTTOM), // u - (SS_BOTTOM_LEFT | SS_BOTTOM | SS_BOTTOM_RIGHT), // v - (SS_LEFT | SS_BOTTOM | SS_BOTTOM_RIGHT), // w - (SS_LEFT | SS_CENTER | SS_RIGHT), // x - (SS_TOP_LEFT | SS_CENTER | SS_RIGHT), // y - (SS_TOP_RIGHT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_LEFT), // z - }; - - UCHAR numberMap[] = { - (SS_LEFT | SS_TOP | SS_BOTTOM | SS_RIGHT | SS_DOT), // 0 - (SS_RIGHT | SS_DOT), // 1 - (SS_TOP | - SS_TOP_RIGHT | SS_CENTER | SS_BOTTOM_LEFT | - SS_BOTTOM | SS_DOT), // 2 - (SS_TOP | SS_CENTER | SS_BOTTOM | SS_RIGHT | SS_DOT), // 3 - (SS_TOP_LEFT | SS_CENTER | SS_RIGHT | SS_DOT), // 4 - (SS_TOP_LEFT | - SS_TOP | SS_CENTER | SS_BOTTOM | - SS_BOTTOM_RIGHT | SS_DOT), // 5 - (SS_TOP | SS_CENTER | SS_BOTTOM | - SS_LEFT | SS_BOTTOM_RIGHT | SS_DOT), // 6 - (SS_TOP | SS_RIGHT | SS_DOT), // 7 - (SS_TOP | SS_BOTTOM | SS_CENTER | - SS_LEFT | SS_RIGHT | SS_DOT), // 8 - (SS_TOP_LEFT | SS_TOP | SS_CENTER | SS_RIGHT | SS_DOT), // 9 - }; - - if ((Character >= 'a') && (Character <= 'z')) - { - SevenSegment->Segments = letterMap[Character - 'a']; - return true; - } - else if ((Character >= 'A') && (Character <= 'Z')) - { - SevenSegment->Segments = letterMap[Character - 'A']; - return true; - } - else if ((Character >= '0') && (Character <= '9')) - { - SevenSegment->Segments = numberMap[Character - '0']; - return true; - } - else - { - SevenSegment->Segments = 0; - return false; - } -} - diff --git a/usb/umdf_fx2/driver/Device.h b/usb/umdf_fx2/driver/Device.h deleted file mode 100644 index 641a04ded..000000000 --- a/usb/umdf_fx2/driver/Device.h +++ /dev/null @@ -1,604 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF OSR Fx2 sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -#define ENDPOINT_TIMEOUT 10000 -#define NUM_OSRUSB_ENDPOINTS 3 - -// -// Define the vendor commands supported by our device -// -#define USBFX2LK_READ_7SEGMENT_DISPLAY 0xD4 -#define USBFX2LK_READ_SWITCHES 0xD6 -#define USBFX2LK_READ_BARGRAPH_DISPLAY 0xD7 -#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 -#define USBFX2LK_IS_HIGH_SPEED 0xD9 -#define USBFX2LK_REENUMERATE 0xDA -#define USBFX2LK_SET_7SEGMENT_DISPLAY 0xDB - -typedef struct { - UCHAR Segments; -} SEVEN_SEGMENT, *PSEVEN_SEGMENT; - -// -// Context for the impersonation callback. -// - -typedef struct -{ - PFILE_PLAYBACK PlaybackInfo; - - HANDLE FileHandle; - - HRESULT Hr; -} PLAYBACK_IMPERSONATION_CONTEXT, *PPLAYBACK_IMPERSONATION_CONTEXT; - -// -// Class for the driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackHardware, - public IPnpCallback, - public IPnpCallbackSelfManagedIo, - public IUsbTargetPipeContinuousReaderCallbackReadersFailed, - public IUsbTargetPipeContinuousReaderCallbackReadComplete, - public IImpersonateCallback -{ -// -// Private data members. -// -private: - // - // Weak reference to framework device - // Use IWDFDevice2 so we can set power policy settings - // - IWDFDevice2 *m_FxDevice; - - // - // Weak reference to the control queue - // - PCMyReadWriteQueue m_ReadWriteQueue; - - // - // Weak reference to the control queue - // - PCMyControlQueue m_ControlQueue; - - // - // The bus type for this device (used here for - // illustrative purposes only) - // - - GUID m_BusTypeGuid; - - // - // USB Device I/O Target - // - IWDFUsbTargetDevice * m_pIUsbTargetDevice; - - // - // USB Interface - // - IWDFUsbInterface * m_pIUsbInterface; - - // - // USB Input pipe for Reads - // - IWDFUsbTargetPipe * m_pIUsbInputPipe; - - // - // USB Output pipe for writes - // - IWDFUsbTargetPipe * m_pIUsbOutputPipe; - - // - // USB interrupt pipe - // - IWDFUsbTargetPipe * m_pIUsbInterruptPipe; - - // - // Use I/O target state management interfaces if you are going to - // support a continuous reader. - // - - // - // USB interrupt pipe state management - // - IWDFIoTargetStateManagement * m_pIoTargetInterruptPipeStateMgmt; - - // - // Device Speed (Low, Full, High) - // - UCHAR m_Speed; - - // - // Current switch state - // - SWITCH_STATE m_SwitchState; - - // - // Request to be used for pending reads from interrupt pipe - // (to get switch state change notifications) - // - - IWDFIoRequest * m_RequestForPendingRead; - - // - // If reads stopped because of a transient problem, the error status - // is stored here. - // - - HRESULT m_InterruptReadProblem; - - // - // Switch state buffer - this might hold the transient value - // m_SwitchState holds stable value of the switch state - // - SWITCH_STATE m_SwitchStateBuffer; - - // - // A manual queue to hold requests for changes in the I/O switch state. - // - - IWDFIoQueue * m_SwitchChangeQueue; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_ControlQueue(NULL), - m_ReadWriteQueue(NULL), - m_SwitchChangeQueue(NULL), - m_pIUsbTargetDevice(NULL), - m_pIUsbInterface(NULL), - m_pIUsbInputPipe(NULL), - m_pIUsbOutputPipe(NULL), - m_pIUsbInterruptPipe(NULL), - m_Speed(0), - m_InterruptReadProblem(S_OK), - m_RequestForPendingRead(NULL), - m_pIoTargetInterruptPipeStateMgmt(NULL) - { - ZeroMemory(&m_BusTypeGuid, sizeof(m_BusTypeGuid)); - } - - ~CMyDevice( - ); - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - // - // Helper methods - // - - HRESULT - GetBusTypeGuid( - VOID - ); - - HRESULT - CreateUsbIoTargets( - VOID - ); - - - HRESULT - ConfigureUsbPipes( - ); - - HRESULT - SetPowerManagement( - VOID - ); - - HRESULT - IndicateDeviceReady( - VOID - ); - - // - // Helper functions - // - - HRESULT - SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ); - - static - WDF_IO_TARGET_STATE - GetTargetState( - IWDFIoTarget * pTarget - ); - - VOID - ServiceSwitchChangeQueue( - _In_ SWITCH_STATE NewState, - _In_ HRESULT CompletionStatus, - _In_opt_ IWDFFile *SpecificFile - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - - IPnpCallback * - QueryIPnpCallback( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IPnpCallbackHardware * - QueryIPnpCallbackHardware( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IPnpCallbackSelfManagedIo * - QueryIPnpCallbackSelfManagedIo( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - - IUsbTargetPipeContinuousReaderCallbackReadersFailed * - QueryContinousReaderFailureCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IUsbTargetPipeContinuousReaderCallbackReadComplete * - QueryContinousReaderCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IImpersonateCallback * - QueryIImpersonateCallback( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - GetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - - HRESULT - SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - - HRESULT - GetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ); - - HRESULT - SetSevenSegmentDisplay( - _In_ PSEVEN_SEGMENT SevenSegment - ); - - HRESULT - ReadSwitchState( - _In_ PSWITCH_STATE SwitchState - ); - - bool - EncodeSegmentValue( - _In_ UCHAR Character, - _Out_ SEVEN_SEGMENT *SevenSegment - ); - - HRESULT - PlaybackFile( - _In_ PFILE_PLAYBACK PlaybackInfo, - _In_ IWDFIoRequest *FxRequest - ); - - // - //returns a weak reference to the target USB device - //DO NOT release it - // - IWDFUsbTargetDevice * - GetUsbTargetDevice( - ) - { - return m_pIUsbTargetDevice; - } - - // - //returns a weak reference to input pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetInputPipe( - ) - { - return m_pIUsbInputPipe; - } - - // - //returns a weak reference to output pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetOutputPipe( - ) - { - return m_pIUsbOutputPipe; - } - - IWDFIoQueue * - GetSwitchChangeQueue( - VOID - ) - { - return m_SwitchChangeQueue; - } - - PSWITCH_STATE - GetCurrentSwitchState( - VOID - ) - { - return &m_SwitchState; - } - - - HRESULT - ConfigContReaderForInterruptEndPoint( - VOID - ); -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IPnpCallbackHardware - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnPrepareHardware( - _In_ IWDFDevice *FxDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnReleaseHardware( - _In_ IWDFDevice *FxDevice - ); - - - // - // IPnpCallback - // - virtual - HRESULT - STDMETHODCALLTYPE - OnD0Entry( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnD0Exit( - _In_ IWDFDevice* pWdfDevice, - _In_ WDF_POWER_DEVICE_STATE previousState - ); - - virtual - void - STDMETHODCALLTYPE - OnSurpriseRemoval( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnQueryRemove( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnQueryStop( - _In_ IWDFDevice* pWdfDevice - ); - - // - // IPnpCallbackSelfManagedIo - // - virtual - VOID - STDMETHODCALLTYPE - OnSelfManagedIoCleanup( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - VOID - STDMETHODCALLTYPE - OnSelfManagedIoFlush( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoInit( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoRestart( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoStop( - _In_ IWDFDevice* pWdfDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnSelfManagedIoSuspend( - _In_ IWDFDevice* pWdfDevice - ); - - // - // IUsbTargetPipeContinuousReaderCallbackReadersFailed - // - virtual - BOOL - STDMETHODCALLTYPE - OnReaderFailure( - IWDFUsbTargetPipe * pPipe, - HRESULT hrCompletion - ); - - // - // IUsbTargetPipeContinuousReaderCallbackReadComplete - // - virtual - VOID - STDMETHODCALLTYPE - OnReaderCompletion( - IWDFUsbTargetPipe * pPipe, - IWDFMemory * pMemory, - SIZE_T NumBytesTransferred, - PVOID Context - ); - - // IImpersonateCallback - virtual - VOID - STDMETHODCALLTYPE - OnImpersonate( - _In_ PVOID Context - ); -}; - diff --git a/usb/umdf_fx2/driver/Driver.cpp b/usb/umdf_fx2/driver/Driver.cpp deleted file mode 100644 index d66352429..000000000 --- a/usb/umdf_fx2/driver/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 driver's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/umdf_fx2/driver/Driver.h b/usb/umdf_fx2/driver/Driver.h deleted file mode 100644 index d9cafb4e5..000000000 --- a/usb/umdf_fx2/driver/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF OSR Fx2 sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the OSR Fx2 sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/umdf_fx2/driver/OsrUsbFx2.ctl b/usb/umdf_fx2/driver/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/umdf_fx2/driver/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/umdf_fx2/driver/OsrUsbFx2.rc b/usb/umdf_fx2/driver/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/umdf_fx2/driver/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/umdf_fx2/driver/ReadWriteQueue.cpp b/usb/umdf_fx2/driver/ReadWriteQueue.cpp deleted file mode 100644 index 461448292..000000000 --- a/usb/umdf_fx2/driver/ReadWriteQueue.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "ReadWriteQueue.tmh" - -VOID -CMyReadWriteQueue::OnCompletion( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ) -{ - UNREFERENCED_PARAMETER(pIoTarget); - UNREFERENCED_PARAMETER(pContext); - - pWdfRequest->CompleteWithInformation( - pParams->GetCompletionStatus(), - pParams->GetInformation() - ); -} - -void -CMyReadWriteQueue::ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ) -{ - // - //First set the completion callback - // - - IRequestCallbackRequestCompletion * pCompletionCallback = NULL; - HRESULT hrQI = this->QueryInterface(IID_PPV_ARGS(&pCompletionCallback)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI) && (NULL != pCompletionCallback)); - - pRequest->SetCompletionCallback( - pCompletionCallback, - NULL - ); - - pCompletionCallback->Release(); - pCompletionCallback = NULL; - - // - //Send down the request - // - - HRESULT hrSend = S_OK; - hrSend = pRequest->Send(pIoTarget, - 0, //flags - 0); //timeout - - if (FAILED(hrSend)) - { - pRequest->CompleteWithInformation(hrSend, 0); - } - - return; -} - - -CMyReadWriteQueue::CMyReadWriteQueue( - _In_ PCMyDevice Device - ) : - CMyQueue(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyReadWriteQueue::~CMyReadWriteQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyReadWriteQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) - { - hr = S_OK; - *Object = QueryIQueueCallbackWrite(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackRead))) - { - hr = S_OK; - *Object = QueryIQueueCallbackRead(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - hr = S_OK; - *Object = QueryIRequestCallbackRequestCompletion(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackIoStop))) - { - hr = S_OK; - *Object = QueryIQueueCallbackIoStop(); - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyReadWriteQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyReadWriteQueue queue; - HRESULT hr = S_OK; - - queue = new CMyReadWriteQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyReadWriteQueue::Initialize( - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - hr = __super::Initialize(WdfIoQueueDispatchParallel, - true, - true); - - // - // return the status. - // - - return hr; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - - Write dispatch routine - IQueueCallbackWrite - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Lenth of bytes in the write buffer - - Allocate and copy data to local buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToWrite - ); - - HRESULT hr = S_OK; - IWDFMemory * pInputMemory = NULL; - IWDFUsbTargetPipe * pOutputPipe = m_Device->GetOutputPipe(); - - pWdfRequest->GetInputMemory(&pInputMemory); - - hr = pOutputPipe->FormatRequestForWrite( - pWdfRequest, - NULL, //pFile - pInputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, pOutputPipe); - } - - SAFE_RELEASE(pInputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToRead - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToRead - Lenth of bytes in the read buffer - - Copy available data into the read buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToRead - ); - - HRESULT hr = S_OK; - IWDFMemory * pOutputMemory = NULL; - - pWdfRequest->GetOutputMemory(&pOutputMemory); - - hr = m_Device->GetInputPipe()->FormatRequestForRead( - pWdfRequest, - NULL, //pFile - pOutputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, m_Device->GetInputPipe()); - } - - SAFE_RELEASE(pOutputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnIoStop( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ) -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - - // - // The driver owns the request and no locking constraint is safe for - // the queue callbacks - // - if (ActionFlags == WdfRequestStopActionSuspend ) - { - IWDFIoRequest2 * request2 = NULL; - HRESULT hr; - - hr = pWdfRequest->QueryInterface(IID_PPV_ARGS(&request2)); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Failed to QI for IWDFIoRequest2: %!hresult!", - hr); - return; - } - - request2->StopAcknowledge(FALSE); //don't requeue - SAFE_RELEASE(request2); - } - else if(ActionFlags == WdfRequestStopActionPurge) - { - // - // Cancel the sent request since we are asked to purge the request - // - - pWdfRequest->CancelSentRequest(); - } - - return; -} - diff --git a/usb/umdf_fx2/driver/ReadWriteQueue.h b/usb/umdf_fx2/driver/ReadWriteQueue.h deleted file mode 100644 index 4f1a98c13..000000000 --- a/usb/umdf_fx2/driver/ReadWriteQueue.h +++ /dev/null @@ -1,163 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -#define MAX_TRANSFER_SIZE(x) 64*1024*1024 - -// -// Queue Callback Object. -// - -class CMyReadWriteQueue : - public IQueueCallbackRead, - public IQueueCallbackWrite, - public IRequestCallbackRequestCompletion, - public IQueueCallbackIoStop, - public CMyQueue -{ -protected: - HRESULT - Initialize( - ); - - void - ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ); - -public: - - CMyReadWriteQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyReadWriteQueue(); - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return CMyQueue::Configure(); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackRead * - QueryIQueueCallbackRead( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackIoStop* - QueryIQueueCallbackIoStop( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - - // - // Wdf Callbacks - // - - // - // IQueueCallbackWrite - // - STDMETHOD_ (void, OnWrite)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // - // IQueueCallbackRead - // - STDMETHOD_ (void, OnRead)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); - - // - //IRequestCallbackRequestCompletion - // - - STDMETHOD_ (void, OnCompletion)( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ); - - // - //IQueueCallbackIoStop - // - - STDMETHOD_ (void, OnIoStop)( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ); - -}; diff --git a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.inx b/usb/umdf_fx2/driver/WUDFOsrUsbFx2.inx deleted file mode 100644 index b9e322233..000000000 Binary files a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.inx and /dev/null differ diff --git a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj b/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj deleted file mode 100644 index 3a21cae84..000000000 --- a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj +++ /dev/null @@ -1,281 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {6E5D412E-EF25-4DA4-B64E-6EAE67AF8D98} - $(MSBuildProjectName) - 1 - 1 - false - true - Debug - Win32 - {87BFB278-0771-439F-893D-89376B83F7F0} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - - - %(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib;$(SDK_LIB_PATH)\setupapi.lib - exports.def - - - sha256 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj.Filters b/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj.Filters deleted file mode 100644 index 372badf09..000000000 --- a/usb/umdf_fx2/driver/WUDFOsrUsbFx2.vcxproj.Filters +++ /dev/null @@ -1,52 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {F8E1CCD2-AADC-44B5-B631-5C6E6D74CFCD} - - - h;hpp;hxx;hm;inl;inc;xsd - {0E050956-9FA9-495C-9F9F-D663EFA3A344} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {49CD21A6-260A-471B-B532-9E9E23F6195F} - - - inf;inv;inx;mof;mc; - {A942026F-83A0-4223-881A-29732777F22C} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_fx2/driver/comsup.cpp b/usb/umdf_fx2/driver/comsup.cpp deleted file mode 100644 index 2f14f5886..000000000 --- a/usb/umdf_fx2/driver/comsup.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -_Use_decl_annotations_ -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/umdf_fx2/driver/comsup.h b/usb/umdf_fx2/driver/comsup.h deleted file mode 100644 index 167b21ff3..000000000 --- a/usb/umdf_fx2/driver/comsup.h +++ /dev/null @@ -1,216 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/umdf_fx2/driver/dllsup.cpp b/usb/umdf_fx2/driver/dllsup.cpp deleted file mode 100644 index 7fda91e4d..000000000 --- a/usb/umdf_fx2/driver/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF OSR Fx2 - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the driver uses - L"Microsoft\\UMDF\\OsrUsb" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for this sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - OSR Fx2 driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/umdf_fx2/driver/exports.def b/usb/umdf_fx2/driver/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/umdf_fx2/driver/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/umdf_fx2/driver/internal.h b/usb/umdf_fx2/driver/internal.h deleted file mode 100644 index 2d57793db..000000000 --- a/usb/umdf_fx2/driver/internal.h +++ /dev/null @@ -1,170 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF OSR Fx2 - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Include SetupDi functions. -// - -#include "setupapi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Include the safestring functions. -// - -#include "strsafe.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; -typedef class CMyReadWriteQueue *PCMyReadWriteQueue; - -typedef class CCancelCallback *PCCancelCallback; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" -#include "ControlQueue.h" -#include "ReadWriteQueue.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} - -#define IDLE_TIMEOUT_IN_MSEC 10*1000 diff --git a/usb/umdf_fx2/driver/queue.cpp b/usb/umdf_fx2/driver/queue.cpp deleted file mode 100644 index c56b38bbc..000000000 --- a/usb/umdf_fx2/driver/queue.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.tmh" - -CMyQueue::CMyQueue( - _In_ PCMyDevice Device - ) : - m_FxQueue(NULL), - m_Device(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - hr = CUnknown::QueryInterface(InterfaceId, Object); - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ) -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the I/O Queue object. - // - - { - IUnknown *callback = QueryIUnknown(); - - hr = m_Device->GetFxDevice()->CreateIoQueue( - callback, - Default, - DispatchType, - PowerManaged, - FALSE, - &fxQueue - ); - callback->Release(); - } - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // Release the creation reference on the queue. This object will be - // destroyed before the queue so we don't need to have a reference out - // on it. - // - - fxQueue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::Configure( - VOID - ) -{ - return S_OK; -} diff --git a/usb/umdf_fx2/driver/queue.h b/usb/umdf_fx2/driver/queue.h deleted file mode 100644 index 5659224bb..000000000 --- a/usb/umdf_fx2/driver/queue.h +++ /dev/null @@ -1,93 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyQueue : - public CUnknown -{ -protected: - // - // Unreferenced pointer to the partner Fx device. - // - - IWDFIoQueue *m_FxQueue; - - // - // Unreferenced pointer to the parent device. - // - - PCMyDevice m_Device; - - HRESULT - Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ); - -protected: - - CMyQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyQueue(); - - HRESULT - Configure( - VOID - ); - -public: - - IWDFIoQueue * - GetFxQueue( - VOID - ) - { - return m_FxQueue; - } - - - PCMyDevice - GetDevice( - VOID - ) - { - return m_Device; - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj b/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj deleted file mode 100644 index 53ba424d3..000000000 --- a/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj +++ /dev/null @@ -1,223 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {B4244D54-7EBF-43D4-BB6D-C994C182C572} - $(MSBuildProjectName) - Debug - Win32 - {6A99CFCE-4C34-4F5D-B7D4-D810AE496B95} - - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - - $(IntDir) - - - - - - - - - - - - - - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj.Filters b/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj.Filters deleted file mode 100644 index a430f986c..000000000 --- a/usb/umdf_fx2/exe/WudfOsrUsbFx2Test.vcxproj.Filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {047255FC-568B-4968-9167-306B7BC95B6D} - - - h;hpp;hxx;hm;inl;inc;xsd - {4B1DCCF4-7F0A-4571-BA4F-DF378E24BD68} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {AC1DECB1-7996-4C71-8D32-0543B4C57AD4} - - - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/umdf_fx2/exe/dump.c b/usb/umdf_fx2/exe/dump.c deleted file mode 100644 index aef55116c..000000000 --- a/usb/umdf_fx2/exe/dump.c +++ /dev/null @@ -1,444 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - DUMP.C - -Abstract: - - Routines to dump the descriptors information in a human readable form. - -Environment: - - user mode only - ---*/ - -#include -#include -#include -#include "devioctl.h" - -#pragma warning(disable:4200) // -#pragma warning(disable:4201) // nameless struct/union -#pragma warning(disable:4214) // bit field types other than int - -#include -#include "usbdi.h" -#include "public.h" - -#pragma warning(default:4200) -#pragma warning(default:4201) -#pragma warning(default:4214) - -HANDLE -OpenDevice( - _In_ BOOL Synchronous - ); - - -char* -usbDescriptorTypeString(UCHAR bDescriptorType ) -/*++ -Routine Description: - - Called to get ascii string of USB descriptor - -Arguments: - - PUSB_ENDPOINT_DESCRIPTOR->bDescriptorType or - PUSB_DEVICE_DESCRIPTOR->bDescriptorType or - PUSB_INTERFACE_DESCRIPTOR->bDescriptorType or - PUSB_STRING_DESCRIPTOR->bDescriptorType or - PUSB_POWER_DESCRIPTOR->bDescriptorType or - PUSB_CONFIGURATION_DESCRIPTOR->bDescriptorType - -Return Value: - - ptr to string - ---*/ -{ - - switch(bDescriptorType) { - - case USB_DEVICE_DESCRIPTOR_TYPE: - return "USB_DEVICE_DESCRIPTOR_TYPE"; - - case USB_CONFIGURATION_DESCRIPTOR_TYPE: - return "USB_CONFIGURATION_DESCRIPTOR_TYPE"; - - - case USB_STRING_DESCRIPTOR_TYPE: - return "USB_STRING_DESCRIPTOR_TYPE"; - - - case USB_INTERFACE_DESCRIPTOR_TYPE: - return "USB_INTERFACE_DESCRIPTOR_TYPE"; - - - case USB_ENDPOINT_DESCRIPTOR_TYPE: - return "USB_ENDPOINT_DESCRIPTOR_TYPE"; - - -#ifdef USB_POWER_DESCRIPTOR_TYPE // this is the older definintion which is actually obsolete - // workaround for temporary bug in 98ddk, older USB100.h file - case USB_POWER_DESCRIPTOR_TYPE: - return "USB_POWER_DESCRIPTOR_TYPE"; -#endif - -#ifdef USB_RESERVED_DESCRIPTOR_TYPE // this is the current version of USB100.h as in NT5DDK - - case USB_RESERVED_DESCRIPTOR_TYPE: - return "USB_RESERVED_DESCRIPTOR_TYPE"; - - case USB_CONFIG_POWER_DESCRIPTOR_TYPE: - return "USB_CONFIG_POWER_DESCRIPTOR_TYPE"; - - case USB_INTERFACE_POWER_DESCRIPTOR_TYPE: - return "USB_INTERFACE_POWER_DESCRIPTOR_TYPE"; -#endif // for current nt5ddk version of USB100.h - - default: - return "??? UNKNOWN!!"; - } -} - - -char * -usbEndPointTypeString(UCHAR bmAttributes) -/*++ -Routine Description: - - Called to get ascii string of endpt descriptor type - -Arguments: - - PUSB_ENDPOINT_DESCRIPTOR->bmAttributes - -Return Value: - - ptr to string - ---*/ -{ - UINT typ = bmAttributes & USB_ENDPOINT_TYPE_MASK; - - - switch( typ) { - case USB_ENDPOINT_TYPE_INTERRUPT: - return "USB_ENDPOINT_TYPE_INTERRUPT"; - - case USB_ENDPOINT_TYPE_BULK: - return "USB_ENDPOINT_TYPE_BULK"; - - case USB_ENDPOINT_TYPE_ISOCHRONOUS: - return "USB_ENDPOINT_TYPE_ISOCHRONOUS"; - - case USB_ENDPOINT_TYPE_CONTROL: - return "USB_ENDPOINT_TYPE_CONTROL"; - - default: - return "??? UNKNOWN!!"; - } -} - - -char * -usbConfigAttributesString(UCHAR bmAttributes) -/*++ -Routine Description: - - Called to get ascii string of USB_CONFIGURATION_DESCRIPTOR attributes - -Arguments: - - PUSB_CONFIGURATION_DESCRIPTOR->bmAttributes - -Return Value: - - ptr to string - ---*/ -{ - UINT typ = bmAttributes & USB_CONFIG_POWERED_MASK; - - - switch( typ) { - - case USB_CONFIG_BUS_POWERED: - return "USB_CONFIG_BUS_POWERED"; - - case USB_CONFIG_SELF_POWERED: - return "USB_CONFIG_SELF_POWERED"; - - case USB_CONFIG_REMOTE_WAKEUP: - return "USB_CONFIG_REMOTE_WAKEUP"; - - - default: - return "??? UNKNOWN!!"; - } -} - - -void -print_USB_CONFIGURATION_DESCRIPTOR(PUSB_CONFIGURATION_DESCRIPTOR cd) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB config descriptor - -Arguments: - - ptr to USB configuration descriptor - -Return Value: - - none - ---*/ -{ - printf("\n===================\nUSB_CONFIGURATION_DESCRIPTOR\n"); - - printf( - "bLength = 0x%x, decimal %u\n", cd->bLength, cd->bLength - ); - - printf( - "bDescriptorType = 0x%x ( %s )\n", cd->bDescriptorType, - usbDescriptorTypeString( cd->bDescriptorType ) - ); - - printf( - "wTotalLength = 0x%x, decimal %u\n", cd->wTotalLength, cd->wTotalLength - ); - - printf( - "bNumInterfaces = 0x%x, decimal %u\n", cd->bNumInterfaces, cd->bNumInterfaces - ); - - printf( - "bConfigurationValue = 0x%x, decimal %u\n", - cd->bConfigurationValue, cd->bConfigurationValue - ); - - printf( - "iConfiguration = 0x%x, decimal %u\n", cd->iConfiguration, cd->iConfiguration - ); - - printf( - "bmAttributes = 0x%x ( %s )\n", cd->bmAttributes, - usbConfigAttributesString( cd->bmAttributes ) - ); - - printf( - "MaxPower = 0x%x, decimal %u\n", cd->MaxPower, cd->MaxPower - ); -} - - -void -print_USB_INTERFACE_DESCRIPTOR(PUSB_INTERFACE_DESCRIPTOR id, UINT ix) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB interface descriptor - -Arguments: - - ptr to USB interface descriptor - -Return Value: - - none - ---*/ -{ - printf("\n-----------------------------\nUSB_INTERFACE_DESCRIPTOR #%u\n", ix); - - - printf( - "bLength = 0x%x\n", id->bLength - ); - - - printf( - "bDescriptorType = 0x%x ( %s )\n", id->bDescriptorType, - usbDescriptorTypeString( id->bDescriptorType ) - ); - - - printf( - "bInterfaceNumber = 0x%x\n", id->bInterfaceNumber - ); - printf( - "bAlternateSetting = 0x%x\n", id->bAlternateSetting - ); - printf( - "bNumEndpoints = 0x%x\n", id->bNumEndpoints - ); - printf( - "bInterfaceClass = 0x%x\n", id->bInterfaceClass - ); - printf( - "bInterfaceSubClass = 0x%x\n", id->bInterfaceSubClass - ); - printf( - "bInterfaceProtocol = 0x%x\n", id->bInterfaceProtocol - ); - printf( - "bInterface = 0x%x\n", id->iInterface - ); -} - - -void -print_USB_ENDPOINT_DESCRIPTOR(PUSB_ENDPOINT_DESCRIPTOR ed, int i) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB endpoint descriptor - -Arguments: - - ptr to USB endpoint descriptor, - index of this endpt in interface desc - -Return Value: - - none - ---*/ -{ - printf( - "------------------------------\nUSB_ENDPOINT_DESCRIPTOR for Pipe%02d\n", i - ); - - printf( - "bLength = 0x%x\n", ed->bLength - ); - - printf( - "bDescriptorType = 0x%x ( %s )\n", ed->bDescriptorType, - usbDescriptorTypeString( ed->bDescriptorType ) - ); - - if ( USB_ENDPOINT_DIRECTION_IN( ed->bEndpointAddress ) ) { - printf( - "bEndpointAddress= 0x%x ( INPUT )\n", ed->bEndpointAddress - ); - } else { - printf( - "bEndpointAddress= 0x%x ( OUTPUT )\n", ed->bEndpointAddress - ); - } - - printf( - "bmAttributes= 0x%x ( %s )\n", ed->bmAttributes, - usbEndPointTypeString ( ed->bmAttributes ) - ); - - printf( - "wMaxPacketSize= 0x%x, decimal %u\n", ed->wMaxPacketSize, - ed->wMaxPacketSize - ); - - printf( - "bInterval = 0x%x, decimal %u\n", ed->bInterval, ed->bInterval - ); -} - - -BOOL -DumpUsbConfig() -/*++ -Routine Description: - - Called to do formatted ascii dump to console of USB - configuration, interface, and endpoint descriptors. - -Arguments: - - none - -Return Value: - - TRUE or FALSE - ---*/ -{ - HANDLE hDev; - UINT success; - int siz, nBytes; - char buf[256] = {0}; - - hDev = OpenDevice(TRUE); - if(hDev == INVALID_HANDLE_VALUE) - { - return FALSE; - } - - siz = sizeof(buf); - - success = DeviceIoControl(hDev, - IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR, - NULL, - 0, - buf, - siz, - (PULONG) &nBytes, - NULL); - - if(success == FALSE) { - printf("Ioct - GetConfigDesc failed %u\n", GetLastError()); - } else { - - ULONG i; - UINT j, n; - char *pch; - PUSB_CONFIGURATION_DESCRIPTOR cd; - PUSB_INTERFACE_DESCRIPTOR id; - PUSB_ENDPOINT_DESCRIPTOR ed; - - pch = buf; - n = 0; - - cd = (PUSB_CONFIGURATION_DESCRIPTOR) pch; - - print_USB_CONFIGURATION_DESCRIPTOR( cd ); - - pch += cd->bLength; - - do { - id = (PUSB_INTERFACE_DESCRIPTOR) pch; - - print_USB_INTERFACE_DESCRIPTOR(id, n++); - - pch += id->bLength; - for (j=0; jbNumEndpoints; j++) { - - ed = (PUSB_ENDPOINT_DESCRIPTOR) pch; - - print_USB_ENDPOINT_DESCRIPTOR(ed,j); - - pch += ed->bLength; - } - i = (ULONG)(pch - buf); - - } while (iwTotalLength); - } - - CloseHandle(hDev); - - return success; - -} - diff --git a/usb/umdf_fx2/exe/testapp.c b/usb/umdf_fx2/exe/testapp.c deleted file mode 100644 index 4e9684e39..000000000 --- a/usb/umdf_fx2/exe/testapp.c +++ /dev/null @@ -1,1368 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - TESTAPP.C - -Abstract: - - Console test app for osrusbfx2 driver. - -Environment: - - user mode only - ---*/ - -#include -_Analysis_mode_(_Analysis_code_type_user_code_); - -#include -#include -#include -#include - -#include "devioctl.h" -#include "strsafe.h" - -#pragma warning(push) -#pragma warning(disable:4200) // -#pragma warning(disable:4201) // nameless struct/union -#pragma warning(disable:4214) // bit field types other than int - -#include -#include -#include "usbdi.h" -#include "public.h" - -#pragma warning(pop) - -#define WHILE(a) \ -while(__pragma(warning(disable:4127)) a __pragma(warning(disable:4127))) - -#define countof(x) (sizeof(x) / sizeof(x[0])) - -#define MAX_DEVPATH_LENGTH 256 -#define NUM_ASYNCH_IO 100 -#define BUFFER_SIZE 1024 -#define READER_TYPE 1 -#define WRITER_TYPE 2 - -BOOL G_fDumpUsbConfig = FALSE; // flags set in response to console command line switches -BOOL G_fDumpReadData = FALSE; -BOOL G_fRead = FALSE; -BOOL G_fWrite = FALSE; -BOOL G_fPlayWithDevice = FALSE; -BOOL G_fPerformAsyncIo = FALSE; -ULONG G_IterationCount = 1; //count of iterations of the test we are to perform -int G_WriteLen = 512; // #bytes to write -int G_ReadLen = 512; // #bytes to read -PCWSTR G_SendFileName = NULL; -ULONG G_SendFileInterval = 1; - -BOOL -DumpUsbConfig( // defined in dump.c - ); - -typedef enum _INPUT_FUNCTION { - LIGHT_ONE_BAR = 1, - CLEAR_ONE_BAR, - LIGHT_ALL_BARS, - CLEAR_ALL_BARS, - GET_BAR_GRAPH_LIGHT_STATE, - GET_SWITCH_STATE, - GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE, - GET_7_SEGEMENT_STATE, - SET_7_SEGEMENT_STATE, - RESET_DEVICE, - REENUMERATE_DEVICE, -} INPUT_FUNCTION; - -_Success_ (return != FALSE) -BOOL -GetDevicePath( - IN LPGUID InterfaceGuid, - _Out_writes_(BufLen) PWSTR DevicePath, - _In_ size_t BufLen - ) -{ - HDEVINFO HardwareDeviceInfo; - SP_DEVICE_INTERFACE_DATA DeviceInterfaceData; - PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL; - ULONG Length, RequiredLength = 0; - BOOL bResult; - HRESULT hr; - - HardwareDeviceInfo = SetupDiGetClassDevs( - InterfaceGuid, - NULL, - NULL, - (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); - - if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) { - wprintf(L"SetupDiGetClassDevs failed!\n"); - return FALSE; - } - - DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - - bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo, - 0, - InterfaceGuid, - 0, - &DeviceInterfaceData); - - if (bResult == FALSE) { - - LPVOID lpMsgBuf; - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR) &lpMsgBuf, - 0, - NULL - )) { - - printf("SetupDiEnumDeviceInterfaces failed: %s", (LPSTR)lpMsgBuf); - LocalFree(lpMsgBuf); - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - return FALSE; - } - - SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - NULL, - 0, - &RequiredLength, - NULL - ); - - DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) - LocalAlloc(LMEM_FIXED, RequiredLength); - - if (DeviceInterfaceDetailData == NULL) { - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - wprintf(L"Failed to allocate memory.\n"); - return FALSE; - } - - DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); - - Length = RequiredLength; - - bResult = SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - DeviceInterfaceDetailData, - Length, - &RequiredLength, - NULL); - - if (bResult == FALSE) { - - LPVOID lpMsgBuf; - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR) &lpMsgBuf, - 0, - NULL)) { - - printf("Error in SetupDiGetDeviceInterfaceDetail: %s\n", (LPSTR)lpMsgBuf); - LocalFree(lpMsgBuf); - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - return FALSE; - } - - hr = StringCchCopy(DevicePath, - BufLen, - DeviceInterfaceDetailData->DevicePath); - if (FAILED(hr)) { - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - return FALSE; - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - - return TRUE; - -} - - -_Check_return_ -_Ret_notnull_ -_Success_(return != INVALID_HANDLE_VALUE) -HANDLE -OpenDevice( - _In_ BOOL Synchronous - ) - -/*++ -Routine Description: - - Called by main() to open an instance of our device after obtaining its name - -Arguments: - - Synchronous - TRUE, if Device is to be opened for synchronous access. - FALSE, otherwise. - -Return Value: - - Device handle on success else INVALID_HANDLE_VALUE - ---*/ - -{ - HANDLE hDev; - WCHAR completeDeviceName[MAX_DEVPATH_LENGTH]; - - if ( !GetDevicePath( - (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, - completeDeviceName, - countof(completeDeviceName)) ) - { - return INVALID_HANDLE_VALUE; - } - - wprintf(L"DeviceName = (%s)\n", completeDeviceName); - - hDev = CreateFile(completeDeviceName, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, // default security - OPEN_EXISTING, - ((Synchronous ? FILE_ATTRIBUTE_NORMAL : FILE_FLAG_OVERLAPPED) | SECURITY_IMPERSONATION), - NULL); - - if (hDev == INVALID_HANDLE_VALUE) { - wprintf(L"Failed to open the device, error - %d", GetLastError()); - } else { - wprintf(L"Opened the device successfully.\n"); - } - - return hDev; -} - - - -VOID -Usage() - -/*++ -Routine Description: - - Called by main() to dump usage info to the console when - the app is called with no parms or with an invalid parm - -Arguments: - - None - -Return Value: - - None - ---*/ - -{ - wprintf(L"Usage for osrusbfx2 testapp:\n"); - wprintf(L"-r where n is number of bytes to read\n"); - wprintf(L"-w where n is number of bytes to write\n"); - wprintf(L"-c where n is number of iterations (default = 1)\n"); - wprintf(L"-v -- dumps read data\n"); - wprintf(L"-p to control bar LEDs, seven segment, and dip switch\n"); - wprintf(L"-a to perform asynchronous I/O\n"); - wprintf(L"-u to dump USB configuration and pipe info \n"); - wprintf(L"-f [interval-seconds] to send a text file to the seven-segment display (UMDF only)\n"); - - return; -} - - -void -Parse( - _In_ int argc, - _In_reads_(argc) LPWSTR *argv - ) - -/*++ -Routine Description: - - Called by main() to parse command line parms - -Arguments: - - argc and argv that was passed to main() - -Return Value: - - Sets global flags as per user function request - ---*/ - -{ - int i; - PWSTR endchar; - - if ( argc < 2 ) // give usage if invoked with no parms - Usage(); - - for (i=0; i= argc) { - Usage(); - exit(1); - } - else { - G_ReadLen = wcstoul(&argv[i+1][0], &endchar, 10); - G_fRead = TRUE; - } - i++; - break; - case L'w': - case L'W': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_WriteLen = wcstoul(&argv[i+1][0], &endchar, 10); - G_fWrite = TRUE; - } - i++; - break; - case L'c': - case L'C': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_IterationCount = wcstoul(&argv[i+1][0], &endchar, 10); - } - i++; - break; - case L'f': - case L'F': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_SendFileName = argv[i+1]; - } - - i++; - - if (i+1 < argc) { - G_SendFileInterval = wcstoul(&argv[i+1][0], &endchar, 10); - } - i++; - - break; - case L'u': - case L'U': - G_fDumpUsbConfig = TRUE; - break; - case L'p': - case L'P': - G_fPlayWithDevice = TRUE; - break; - case L'a': - case L'A': - G_fPerformAsyncIo = TRUE; - break; - case L'v': - case L'V': - G_fDumpReadData = TRUE; - break; - default: - Usage(); - } - } - } -} - -BOOL -Compare_Buffs( - _In_reads_bytes_(length) PVOID *buff1, - _In_reads_bytes_(length) PVOID *buff2, - _In_ int length - ) -/*++ -Routine Description: - - Called to verify read and write buffers match for loopback test - -Arguments: - - buffers to compare and length - -Return Value: - - TRUE if buffers match, else FALSE - ---*/ -{ - int ok = 1; - - if (memcmp(buff1, buff2, length )) { - // Edi, and Esi point to the mismatching char and ecx indicates the - // remaining length. - ok = 0; - } - - return ok; -} - -#define NPERLN 8 - -VOID -Dump( - UCHAR *b, - int len -) - -/*++ -Routine Description: - - Called to do formatted ascii dump to console of the io buffer - -Arguments: - - buffer and length - -Return Value: - - none - ---*/ - -{ - ULONG i; - ULONG longLen = (ULONG)len / sizeof( ULONG ); - PULONG pBuf = (PULONG) b; - - // dump an ordinal ULONG for each sizeof(ULONG)'th byte - wprintf(L"\n****** BEGIN DUMP LEN decimal %d, 0x%x\n", len,len); - for (i=0; i 8){ - wprintf(L"Invalid bar number!\n"); - goto Error; - } - - bar--; // normalize to 0 to 7 - - barGraphState.BarsAsUChar = 1 << (UCHAR)bar; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case CLEAR_ONE_BAR: - - - wprintf(L"Which Bar (input number 1 thru 8)?\n"); - if (scanf_s ("%d", &bar) <= 0) { - - wprintf(L"Error reading input!\n"); - goto Error; - - } - - if(bar == 0 || bar > 8){ - wprintf(L"Invalid bar number!\n"); - goto Error; - } - - bar--; - - // - // Read the current state - // - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &barGraphState, // Ptr to OutBuffer - sizeof(BAR_GRAPH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - if (barGraphState.BarsAsUChar & (1 << bar)) { - - wprintf(L"Bar is set...Clearing it\n"); - barGraphState.BarsAsUChar &= ~(1 << bar); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - - } - - } else { - - wprintf(L"Bar not set.\n"); - - } - - break; - - case LIGHT_ALL_BARS: - - barGraphState.BarsAsUChar = 0xFF; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case CLEAR_ALL_BARS: - - barGraphState.BarsAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - - case GET_BAR_GRAPH_LIGHT_STATE: - - barGraphState.BarsAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &barGraphState, // Ptr to OutBuffer - sizeof(BAR_GRAPH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Bar Graph: \n"); - wprintf(L" Bar8 is %s\n", barGraphState.Bar8 ? L"ON" : L"OFF"); - wprintf(L" Bar7 is %s\n", barGraphState.Bar7 ? L"ON" : L"OFF"); - wprintf(L" Bar6 is %s\n", barGraphState.Bar6 ? L"ON" : L"OFF"); - wprintf(L" Bar5 is %s\n", barGraphState.Bar5 ? L"ON" : L"OFF"); - wprintf(L" Bar4 is %s\n", barGraphState.Bar4 ? L"ON" : L"OFF"); - wprintf(L" Bar3 is %s\n", barGraphState.Bar3 ? L"ON" : L"OFF"); - wprintf(L" Bar2 is %s\n", barGraphState.Bar2 ? L"ON" : L"OFF"); - wprintf(L" Bar1 is %s\n", barGraphState.Bar1 ? L"ON" : L"OFF"); - - break; - - case GET_SWITCH_STATE: - - switchState.SwitchesAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_READ_SWITCHES, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &switchState, // Ptr to OutBuffer - sizeof(SWITCH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Switches: \n"); - wprintf(L" Switch8 is %s\n", switchState.Switch8 ? L"ON" : L"OFF"); - wprintf(L" Switch7 is %s\n", switchState.Switch7 ? L"ON" : L"OFF"); - wprintf(L" Switch6 is %s\n", switchState.Switch6 ? L"ON" : L"OFF"); - wprintf(L" Switch5 is %s\n", switchState.Switch5 ? L"ON" : L"OFF"); - wprintf(L" Switch4 is %s\n", switchState.Switch4 ? L"ON" : L"OFF"); - wprintf(L" Switch3 is %s\n", switchState.Switch3 ? L"ON" : L"OFF"); - wprintf(L" Switch2 is %s\n", switchState.Switch2 ? L"ON" : L"OFF"); - wprintf(L" Switch1 is %s\n", switchState.Switch1 ? L"ON" : L"OFF"); - - break; - - case GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE: - - switchState.SwitchesAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &switchState, // Ptr to OutBuffer - sizeof(switchState), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Switches: %d\n",index); - wprintf(L" Switch8 is %s\n", switchState.Switch8 ? L"ON" : L"OFF"); - wprintf(L" Switch7 is %s\n", switchState.Switch7 ? L"ON" : L"OFF"); - wprintf(L" Switch6 is %s\n", switchState.Switch6 ? L"ON" : L"OFF"); - wprintf(L" Switch5 is %s\n", switchState.Switch5 ? L"ON" : L"OFF"); - wprintf(L" Switch4 is %s\n", switchState.Switch4 ? L"ON" : L"OFF"); - wprintf(L" Switch3 is %s\n", switchState.Switch3 ? L"ON" : L"OFF"); - wprintf(L" Switch2 is %s\n", switchState.Switch2 ? L"ON" : L"OFF"); - wprintf(L" Switch1 is %s\n", switchState.Switch1 ? L"ON" : L"OFF"); - - break; - - case GET_7_SEGEMENT_STATE: - - sevenSegment = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &sevenSegment, // Ptr to OutBuffer - sizeof(UCHAR), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"7 Segment mask: 0x%x\n", sevenSegment); - break; - - case SET_7_SEGEMENT_STATE: - - for (i = 0; i < 8; i++) { - - sevenSegment = 1 << i; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY, - &sevenSegment, // Ptr to InBuffer - sizeof(UCHAR), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"This is %d\n", i); - Sleep(500); - - } - - wprintf(L"7 Segment mask: 0x%x\n", sevenSegment); - break; - - case RESET_DEVICE: - - wprintf(L"Reset the device\n"); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_RESET_DEVICE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - NULL)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case REENUMERATE_DEVICE: - - wprintf(L"Re-enumerate the device\n"); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_REENUMERATE_DEVICE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - NULL)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - // - // Close the handle to the device and exit out so that - // the driver can unload when the device is surprise-removed - // and reenumerated. - // - default: - - result = TRUE; - goto Error; - - } - - } // end of while loop - -Error: - - CloseHandle(deviceHandle); - return result; - -} - -BOOL -SendFileToDevice( - _In_ PCWSTR FileName - ) -{ - HANDLE deviceHandle; - - struct - { - USHORT delay; - WCHAR buffer[MAX_PATH + 1]; - } playback; - - ULONG bufferCch; - - DWORD code; - BOOL result = FALSE; - - // - // Open a handle to the device. - // - - deviceHandle = OpenDevice(FALSE); - - if (deviceHandle == INVALID_HANDLE_VALUE) { - - wprintf(L"Unable to find any OSR FX2 devices!\n"); - - return FALSE; - - } - - // - // Convert the file name from relative to absolute. - // - - bufferCch = GetFullPathName(FileName, - countof(playback.buffer), - playback.buffer, - NULL); - - if (bufferCch == 0) - { - wprintf(L"Error getting full path name for %s - %d\n", - FileName, - GetLastError()); - goto Error; - } - - if ((G_SendFileInterval * 1000) >= ((USHORT) 0xffff)) - { - wprintf(L"Error - delay is too large. Remember that it's in terms of seconds.\n"); - goto Error; - } - - playback.delay = (USHORT) (G_SendFileInterval * 1000); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_PLAY_FILE, - &playback, - sizeof(playback), - NULL, - 0, - &bufferCch, - 0)) { - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - result = TRUE; - -Error: - - CloseHandle(deviceHandle); - return result; -} - -ULONG -AsyncIo( - PVOID ThreadParameter - ) -{ - HANDLE hDevice = INVALID_HANDLE_VALUE; - HANDLE hCompletionPort = NULL; - OVERLAPPED *pOvList = NULL; - PUCHAR buf = NULL; - ULONG_PTR i; - ULONG ioType = (ULONG)(ULONG_PTR)ThreadParameter; - ULONG error; - - hDevice = OpenDevice(FALSE); - - if (hDevice == INVALID_HANDLE_VALUE) { - wprintf(L"Cannot open device %d\n", GetLastError()); - goto Error; - } - - hCompletionPort = CreateIoCompletionPort(hDevice, NULL, 1, 0); - - if (hCompletionPort == NULL) { - wprintf(L"Cannot open completion port %d \n",GetLastError()); - goto Error; - } - - pOvList = (OVERLAPPED *)malloc(NUM_ASYNCH_IO * sizeof(OVERLAPPED)); - - if (pOvList == NULL) { - wprintf(L"Cannot allocate overlapped array \n"); - goto Error; - } - - buf = (PUCHAR)malloc(NUM_ASYNCH_IO * BUFFER_SIZE); - - if (buf == NULL) { - wprintf(L"Cannot allocate buffer \n"); - goto Error; - } - - ZeroMemory(pOvList, NUM_ASYNCH_IO * sizeof(OVERLAPPED)); - ZeroMemory(buf, NUM_ASYNCH_IO * BUFFER_SIZE); - - // - // Issue asynch I/O - // - - for (i = 0; i < NUM_ASYNCH_IO; i++) { - if (ioType == READER_TYPE) { - if ( ReadFile( hDevice, - buf + (i* BUFFER_SIZE), - BUFFER_SIZE, - NULL, - &pOvList[i]) == 0) { - - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L" %Iu th read failed %d \n",i, GetLastError()); - goto Error; - } - } - - } else { - if ( WriteFile( hDevice, - buf + (i* BUFFER_SIZE), - BUFFER_SIZE, - NULL, - &pOvList[i]) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L" %Iu th write failed %d \n",i, GetLastError()); - goto Error; - } - } - } - } - - // - // Wait for the I/Os to complete. If one completes then reissue the I/O - // - - WHILE (1) { - OVERLAPPED *completedOv; - ULONG_PTR key; - ULONG numberOfBytesTransferred; - - if ( GetQueuedCompletionStatus(hCompletionPort, &numberOfBytesTransferred, - &key, &completedOv, INFINITE) == 0) { - wprintf(L"GetQueuedCompletionStatus failed %d\n", GetLastError()); - goto Error; - } - - // - // Read successfully completed. Issue another one. - // - - if (ioType == READER_TYPE) { - - i = completedOv - pOvList; - - wprintf(L"Number of bytes read by request number %Iu is %d\n", - i, numberOfBytesTransferred); - - if ( ReadFile( hDevice, - buf + (i * BUFFER_SIZE), - BUFFER_SIZE, - NULL, - completedOv) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L"%Iu th Read failed %d \n", i, GetLastError()); - goto Error; - } - } - } else { - - i = completedOv - pOvList; - - wprintf(L"Number of bytes written by request number %Iu is %d\n", - i, numberOfBytesTransferred); - - if ( WriteFile( hDevice, - buf + (i * BUFFER_SIZE), - BUFFER_SIZE, - NULL, - completedOv) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L"%Iu th write failed %d \n", i, GetLastError()); - goto Error; - } - } - } - } - -Error: - if (hDevice != INVALID_HANDLE_VALUE) { - CloseHandle(hDevice); - } - - if (hCompletionPort) { - CloseHandle(hCompletionPort); - } - - if (pOvList) { - free(pOvList); - } - if (buf) { - free(buf); - } - - return 1; - -} - - -int -_cdecl -wmain( - _In_ int argc, - _In_reads_(argc) LPWSTR *argv - ) -/*++ -Routine Description: - - Entry point to rwbulk.exe - Parses cmdline, performs user-requested tests - -Arguments: - - argc, argv standard console 'c' app arguments - -Return Value: - - Zero - ---*/ - -{ - PWSTR * pinBuf = NULL; - PWSTR * poutBuf = NULL; - int nBytesRead; - int nBytesWrite; - int ok; - int retValue = 0; - UINT success; - HANDLE hRead = INVALID_HANDLE_VALUE; - HANDLE hWrite = INVALID_HANDLE_VALUE; - ULONG fail = 0L; - ULONG i; - - - Parse(argc, argv ); - - // - // dump USB configuation and pipe info - // - if (G_fDumpUsbConfig) { - DumpUsbConfig(); - } - - if (G_fPlayWithDevice) { - PlayWithDevice(); - goto exit; - } - - if (G_SendFileName != NULL) - { - SendFileToDevice(G_SendFileName); - goto exit; - } - - if (G_fPerformAsyncIo) { - HANDLE th1; - - // - // Create a reader thread - // - th1 = CreateThread( NULL, // Default Security Attrib. - 0, // Initial Stack Size, - AsyncIo, // Thread Func - (LPVOID)READER_TYPE, - 0, // Creation Flags - NULL ); // Don't need the Thread Id. - - if (th1 == NULL) { - wprintf(L"Couldn't create reader thread - error %d\n", GetLastError()); - retValue = 1; - goto exit; - } - - // - // Use this thread for peforming write. - // - AsyncIo((PVOID)WRITER_TYPE); - - goto exit; - } - - // - // doing a read, write, or both test - // - if ((G_fRead) || (G_fWrite)) { - - if (G_fRead) { - if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping - while( G_ReadLen % sizeof( ULONG ) ) { - G_ReadLen++; - } - } - - // - // open the output file - // - hRead = OpenDevice(TRUE); - if(hRead == INVALID_HANDLE_VALUE) { - retValue = 1; - goto exit; - } - - pinBuf = malloc(G_ReadLen); - } - - if (G_fWrite) { - if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping - while( G_WriteLen % sizeof( ULONG ) ) { - G_WriteLen++; - } - } - - // - // open the output file - // - hWrite = OpenDevice(TRUE); - if(hWrite == INVALID_HANDLE_VALUE) { - retValue = 1; - goto exit; - } - - poutBuf = malloc(G_WriteLen); - if (poutBuf == NULL) { - retValue = 1; - goto exit; - } - } - - for (i = 0; i < G_IterationCount; i++) { - ULONG j; - - if (G_fWrite && poutBuf && hWrite != INVALID_HANDLE_VALUE) { - - PULONG pOut = (PULONG) poutBuf; - ULONG numLongs = G_WriteLen / sizeof( ULONG ); - - // - // put some data in the output buffer - // - for (j=0; j - -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT2_UNKNOWN -#define VER_FILEDESCRIPTION_STR "OSRUSBFX2 Bulk & Isoch Read and Write test App for UMDF" -#define VER_INTERNALNAME_STR "WudfOsrUsbFx2Test.exe" -#define VER_ORIGINALFILENAME_STR "WudfOsrUsbFx2Test.exe" - -#include - - diff --git a/usb/umdf_fx2/inc/WUDFOsrUsbPublic.h b/usb/umdf_fx2/inc/WUDFOsrUsbPublic.h deleted file mode 100644 index 6681fa146..000000000 --- a/usb/umdf_fx2/inc/WUDFOsrUsbPublic.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - WUDFOsrUsbPublic.h - -Abstract: - - This module contains the common declarations shared by driver - and user applications for the UMDF OSR device sample. - - Note that this driver does NOT use the same device interface GUID - as the KMDF OSR USB sample. - -Environment: - - user and kernel - ---*/ - -#pragma once - -// -// Define an Interface Guid so that app can find the device and talk to it. -// - -// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} -DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, - 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); - diff --git a/usb/umdf_fx2/inc/list.h b/usb/umdf_fx2/inc/list.h deleted file mode 100644 index 38d0b1e90..000000000 --- a/usb/umdf_fx2/inc/list.h +++ /dev/null @@ -1,77 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - list.h - -Abstract: - - This module contains doubly linked list macros - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -FORCEINLINE -VOID -InitializeListHead( - IN PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -VOID -InsertHeadList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -InsertTailList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} diff --git a/usb/umdf_fx2/inc/public.h b/usb/umdf_fx2/inc/public.h deleted file mode 100644 index 2c3f6805c..000000000 --- a/usb/umdf_fx2/inc/public.h +++ /dev/null @@ -1,217 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - public.h - -Abstract: - - Public definitions for the OSR_FX2 device operations. - -Environment: - - User & Kernel mode - ---*/ - -#ifndef _PUBLIC_H -#define _PUBLIC_H - -#include - -#include "WudfOsrUsbPublic.h" - - -// -// Define the structures that will be used by the IOCTL -// interface to the driver -// - -// -// BAR_GRAPH_STATE -// -// BAR_GRAPH_STATE is a bit field structure with each -// bit corresponding to one of the bar graph on the -// OSRFX2 Development Board -// -#include - -#pragma warning( push ) -#pragma warning( disable : 4201 ) // nameless struct/union -#pragma warning( disable : 4214 ) // bit-field type other than int - -typedef struct _BAR_GRAPH_STATE { - - union { - - struct { - // - // Individual bars starting from the - // top of the stack of bars - // - // NOTE: There are actually 10 bars, - // but the very top two do not light - // and are not counted here - // - UCHAR Bar1 : 1; - UCHAR Bar2 : 1; - UCHAR Bar3 : 1; - UCHAR Bar4 : 1; - UCHAR Bar5 : 1; - UCHAR Bar6 : 1; - UCHAR Bar7 : 1; - UCHAR Bar8 : 1; - }; - - // - // The state of all the bar graph as a single - // UCHAR - // - UCHAR BarsAsUChar; - - }; - -}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; - -// -// SWITCH_STATE -// -// SWITCH_STATE is a bit field structure with each -// bit corresponding to one of the switches on the -// OSRFX2 Development Board -// -typedef struct _SWITCH_STATE { - - union { - struct { - // - // Individual switches starting from the - // left of the set of switches - // - UCHAR Switch1 : 1; - UCHAR Switch2 : 1; - UCHAR Switch3 : 1; - UCHAR Switch4 : 1; - UCHAR Switch5 : 1; - UCHAR Switch6 : 1; - UCHAR Switch7 : 1; - UCHAR Switch8 : 1; - }; - - // - // The state of all the switches as a single - // UCHAR - // - UCHAR SwitchesAsUChar; - - }; - - -}SWITCH_STATE, *PSWITCH_STATE; - -// -// Seven segment display bit values. -// - -// -// Undefine conflicting MFC constant -// -#undef SS_CENTER -#undef SS_LEFT -#undef SS_RIGHT - -#define SS_TOP 0x01 -#define SS_TOP_LEFT 0x40 -#define SS_TOP_RIGHT 0x02 -#define SS_CENTER 0x20 -#define SS_BOTTOM_LEFT 0x10 -#define SS_BOTTOM_RIGHT 0x04 -#define SS_BOTTOM 0x80 -#define SS_DOT 0x08 - -// -// FILE_PLAYBACK -// -// FILE_PLAYBACK structure contains the parameters for the PLAY_FILE I/O Control. -// - -typedef struct _FILE_PLAYBACK -{ - // - // The delay between changes in the display, in milliseconds. - // - - USHORT Delay; - - // - // The data file path. - // - - WCHAR Path[1]; -} FILE_PLAYBACK, *PFILE_PLAYBACK; - -#include - -#define IOCTL_INDEX 0x800 -#define FILE_DEVICE_OSRUSBFX2 65500U - -#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 1, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 3, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 4, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 5, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - - -#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 6, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 7, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 8, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 9, \ - METHOD_OUT_DIRECT, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_PLAY_FILE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 10, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#pragma warning(pop) - -#endif - diff --git a/usb/umdf_fx2/inc/usb_hw.h b/usb/umdf_fx2/inc/usb_hw.h deleted file mode 100644 index d6e983f1a..000000000 --- a/usb/umdf_fx2/inc/usb_hw.h +++ /dev/null @@ -1,233 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Usb.h - -Abstract: - - Contains prototypes for interfacing with a USB connected device. These - are copied from the KMDF WDFUSB.H header file (but with the WDF specific - portions removed) - -Environment: - - kernel mode only - ---*/ - -#pragma once - -typedef enum _WINUSB_BMREQUEST_DIRECTION { - BmRequestHostToDevice = BMREQUEST_HOST_TO_DEVICE, - BmRequestDeviceToHost = BMREQUEST_DEVICE_TO_HOST, -} WINUSB_BMREQUEST_DIRECTION; - -typedef enum _WINUSB_BMREQUEST_TYPE { - BmRequestStandard = BMREQUEST_STANDARD, - BmRequestClass = BMREQUEST_CLASS, - BmRequestVendor = BMREQUEST_VENDOR, -} WINUSB_BMREQUEST_TYPE; - -typedef enum _WINUSB_BMREQUEST_RECIPIENT { - BmRequestToDevice = BMREQUEST_TO_DEVICE, - BmRequestToInterface = BMREQUEST_TO_INTERFACE, - BmRequestToEndpoint = BMREQUEST_TO_ENDPOINT, - BmRequestToOther = BMREQUEST_TO_OTHER, -} WINUSB_BMREQUEST_RECIPIENT; - -typedef enum _WINUSB_DEVICE_TRAITS { - WINUSB_DEVICE_TRAIT_SELF_POWERED = 0x00000001, - WINUSB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE = 0x00000002, - WINUSB_DEVICE_TRAIT_AT_HIGH_SPEED = 0x00000004, -} WINUSB_DEVICE_TRAITS; - -typedef enum _WdfUsbTargetDeviceSelectInterfaceType { - WdfUsbTargetDeviceSelectInterfaceTypeInterface = 0x10, - WdfUsbTargetDeviceSelectInterfaceTypeUrb = 0x11, -} WdfUsbTargetDeviceSelectInterfaceType; - - - -typedef union _WINUSB_CONTROL_SETUP_PACKET { - struct { - union { - #pragma warning(disable:4214) // bit field types other than int - struct { - // - // Valid values are BMREQUEST_TO_DEVICE, BMREQUEST_TO_INTERFACE, - // BMREQUEST_TO_ENDPOINT, BMREQUEST_TO_OTHER - // - BYTE Recipient:2; - - BYTE Reserved:3; - - // - // Valid values are BMREQUEST_STANDARD, BMREQUEST_CLASS, - // BMREQUEST_VENDOR - // - BYTE Type:2; - - // - // Valid values are BMREQUEST_HOST_TO_DEVICE, - // BMREQUEST_DEVICE_TO_HOST - // - BYTE Dir:1; - } Request; - #pragma warning(default:4214) // bit field types other than int - BYTE Byte; - } bm; - - BYTE bRequest; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wValue; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wIndex; - - USHORT wLength; - } Packet; - - struct { - BYTE Bytes[8]; - } Generic; - - WINUSB_SETUP_PACKET WinUsb; - -} WINUSB_CONTROL_SETUP_PACKET, *PWINUSB_CONTROL_SETUP_PACKET; - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_CLASS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestClass; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_VENDOR( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestVendor; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_FEATURE( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT FeatureSelector, - USHORT Index, - BOOLEAN SetFeature - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestHostToDevice; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - if (SetFeature) { - Packet->Packet.bRequest = USB_REQUEST_SET_FEATURE; - } - else { - Packet->Packet.bRequest = USB_REQUEST_CLEAR_FEATURE; - } - - Packet->Packet.wValue.Value = FeatureSelector; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_GET_STATUS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestDeviceToHost; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - Packet->Packet.bRequest = USB_REQUEST_GET_STATUS; - Packet->Packet.wIndex.Value = Index; - Packet->Packet.wValue.Value = 0; - - // Packet->Packet.wLength will be set by the formatting function -} - diff --git a/usb/umdf_fx2/umdf_fx2.sln b/usb/umdf_fx2/umdf_fx2.sln deleted file mode 100644 index c67f4db38..000000000 --- a/usb/umdf_fx2/umdf_fx2.sln +++ /dev/null @@ -1,46 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 -MinimumVisualStudioVersion = 12.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Driver", "Driver", "{0F58CCC8-C87F-436A-8155-C5A9C20AE3A0}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{F891F391-8DC0-4256-B1E3-993DE7A0DEFF}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2", "driver\WUDFOsrUsbFx2.vcxproj", "{E73991B4-029F-448E-9CA8-0827CBE1EF0E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WudfOsrUsbFx2Test", "exe\WudfOsrUsbFx2Test.vcxproj", "{F0965B23-D0A3-4587-85A3-FA4B20F2051D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Debug|Win32.ActiveCfg = Debug|Win32 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Debug|Win32.Build.0 = Debug|Win32 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Release|Win32.ActiveCfg = Release|Win32 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Release|Win32.Build.0 = Release|Win32 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Debug|x64.ActiveCfg = Debug|x64 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Debug|x64.Build.0 = Debug|x64 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Release|x64.ActiveCfg = Release|x64 - {E73991B4-029F-448E-9CA8-0827CBE1EF0E}.Release|x64.Build.0 = Release|x64 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Debug|Win32.ActiveCfg = Debug|Win32 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Debug|Win32.Build.0 = Debug|Win32 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Release|Win32.ActiveCfg = Release|Win32 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Release|Win32.Build.0 = Release|Win32 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Debug|x64.ActiveCfg = Debug|x64 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Debug|x64.Build.0 = Debug|x64 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Release|x64.ActiveCfg = Release|x64 - {F0965B23-D0A3-4587-85A3-FA4B20F2051D}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {E73991B4-029F-448E-9CA8-0827CBE1EF0E} = {0F58CCC8-C87F-436A-8155-C5A9C20AE3A0} - {F0965B23-D0A3-4587-85A3-FA4B20F2051D} = {F891F391-8DC0-4256-B1E3-993DE7A0DEFF} - EndGlobalSection -EndGlobal diff --git a/usb/usbsamp/exe/usbsamp.vcxproj b/usb/usbsamp/exe/usbsamp.vcxproj index 20fe67baf..8e9de3b19 100644 --- a/usb/usbsamp/exe/usbsamp.vcxproj +++ b/usb/usbsamp/exe/usbsamp.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/usb/usbsamp/sys/driver/usbsamp.inx b/usb/usbsamp/sys/driver/usbsamp.inx index 9f4cf03ab..57dc4bf36 100644 Binary files a/usb/usbsamp/sys/driver/usbsamp.inx and b/usb/usbsamp/sys/driver/usbsamp.inx differ diff --git a/usb/usbsamp/sys/driver/usbsamp.vcxproj b/usb/usbsamp/sys/driver/usbsamp.vcxproj index a4ab4576d..528d765b5 100644 --- a/usb/usbsamp/sys/driver/usbsamp.vcxproj +++ b/usb/usbsamp/sys/driver/usbsamp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/usbview/display.c b/usb/usbview/display.c index f0b4ce669..2cb2c54a1 100644 --- a/usb/usbview/display.c +++ b/usb/usbview/display.c @@ -1977,7 +1977,7 @@ DisplayConfigDesc ( AppendTextBuffer("*!*ERROR: bLength of %d for Device Qualifier incorrect, "\ "should be %d\r\n", commonDesc->bLength, - sizeof(USB_DEVICE_QUALIFIER_DESCRIPTOR)); + (UCHAR) sizeof(USB_DEVICE_QUALIFIER_DESCRIPTOR)); OOPS(); displayUnknown = TRUE; break; @@ -1997,7 +1997,7 @@ DisplayConfigDesc ( AppendTextBuffer("*!*ERROR: bLength of %d for Other Speed Configuration "\ "incorrect, should be %d\r\n", commonDesc->bLength, - sizeof(USB_CONFIGURATION_DESCRIPTOR)); + (UCHAR) sizeof(USB_CONFIGURATION_DESCRIPTOR)); OOPS(); displayUnknown = TRUE; } @@ -2019,7 +2019,7 @@ DisplayConfigDesc ( AppendTextBuffer("*!*ERROR: bLength of %d for Configuration incorrect, "\ "should be %d\r\n", commonDesc->bLength, - sizeof(USB_CONFIGURATION_DESCRIPTOR)); + (UCHAR) sizeof(USB_CONFIGURATION_DESCRIPTOR)); OOPS(); displayUnknown = TRUE; break; @@ -2042,8 +2042,8 @@ DisplayConfigDesc ( AppendTextBuffer("*!*ERROR: bLength of %d for Interface incorrect, "\ "should be %d or %d\r\n", commonDesc->bLength, - sizeof(USB_INTERFACE_DESCRIPTOR), - sizeof(USB_INTERFACE_DESCRIPTOR2)); + (UCHAR) sizeof(USB_INTERFACE_DESCRIPTOR), + (UCHAR) sizeof(USB_INTERFACE_DESCRIPTOR2)); OOPS(); displayUnknown = TRUE; break; @@ -2078,8 +2078,8 @@ DisplayConfigDesc ( AppendTextBuffer("*!*ERROR: bLength of %d for Endpoint incorrect, "\ "should be %d or %d\r\n", commonDesc->bLength, - sizeof(USB_ENDPOINT_DESCRIPTOR), - sizeof(USB_ENDPOINT_DESCRIPTOR2)); + (UCHAR) sizeof(USB_ENDPOINT_DESCRIPTOR), + (UCHAR) sizeof(USB_ENDPOINT_DESCRIPTOR2)); OOPS(); displayUnknown = TRUE; break; @@ -2506,7 +2506,7 @@ DisplayUsb20ExtensionCapabilityDescriptor ( AppendTextBuffer("bDevCapabilityType: 0x%02X\r\n", extCapDesc->bDevCapabilityType); AppendTextBuffer("bmAttributes: 0x%08X", - extCapDesc->bmAttributes); + extCapDesc->bmAttributes.AsUlong); if (extCapDesc->bmAttributes.AsUlong & USB_DEVICE_CAPABILITY_USB20_EXTENSION_BMATTRIBUTES_RESERVED_MASK) { if(gDoAnnotation) @@ -2955,7 +2955,7 @@ DisplayBillboardCapabilityDescriptor ( billboardCapDesc->bPreferredAlternateMode); AppendTextBuffer("VCONN Power: 0x%04X", - billboardCapDesc->VconnPower); + billboardCapDesc->VconnPower.AsUshort); if (billboardCapDesc->VconnPower.NoVconnPowerRequired) { diff --git a/usb/usbview/dispvid.c b/usb/usbview/dispvid.c index fa7765fb5..b3e3f9dfa 100644 --- a/usb/usbview/dispvid.c +++ b/usb/usbview/dispvid.c @@ -259,7 +259,7 @@ BOOL DisplayVCInputTerminal ( PVIDEO_INPUT_TERMINAL VidITDesc, PSTRING_DESCRIPTOR_NODE StringDescs, - DEVICE_POWER_STATE LatestDevicePowerState + DEVICE_POWER_STATE LatestDevicePowerState ); BOOL @@ -521,9 +521,9 @@ DisplayVideoDescriptor ( #endif #ifdef H264_SUPPORT - case MAX_TYPE_UNIT+1: + case MAX_TYPE_UNIT+1: // for H.264, the bDescriptorSubtype = 7, which is equal to MAX_TYPE_UNIT - // so now MAX_TYPE_UNIT needs to be set to 8 + // so now MAX_TYPE_UNIT needs to be set to 8 //(TODO: need to change nt\sdpublic\internal\drivers\inc\uvcdesc.h's define // of MAX_TYPE_UNIT from7 to 8, and ad the type for H.264 = 8) #else @@ -897,7 +897,7 @@ DisplayVCHeader ( } AppendTextBuffer("wTotalLength: 0x%04X", VCInterfaceDesc->wTotalLength); - // Verify the total interface size (size of this header and all descriptors + // Verify the total interface size (size of this header and all descriptors // following until and not including the first endpoint) uSize = GetVCInterfaceSize(VCInterfaceDesc); if (uSize != VCInterfaceDesc->wTotalLength) { @@ -906,21 +906,21 @@ DisplayVCHeader ( } else { AppendTextBuffer(" -> Validated\r\n"); } - AppendTextBuffer("dwClockFreq: 0x%08X", + AppendTextBuffer("dwClockFreq: 0x%08X", VCInterfaceDesc->dwClockFreq); - if (gDoAnnotation) + if (gDoAnnotation) { - AppendTextBuffer(" = (%d) Hz", VCInterfaceDesc->dwClockFreq); + AppendTextBuffer(" = (%d) Hz", VCInterfaceDesc->dwClockFreq); } - AppendTextBuffer("\r\nbInCollection: 0x%02X\r\n", + AppendTextBuffer("\r\nbInCollection: 0x%02X\r\n", VCInterfaceDesc->bInCollection); // baInterfaceNr is a variable length field // Size is in bInCollection - for (i = 1, pData = (PUCHAR) &VCInterfaceDesc->bInCollection; + for (i = 1, pData = (PUCHAR) &VCInterfaceDesc->bInCollection; i <= VCInterfaceDesc->bInCollection; i++, pData++) { - AppendTextBuffer("baInterfaceNr[%d]: 0x%02X\r\n", + AppendTextBuffer("baInterfaceNr[%d]: 0x%02X\r\n", i, *pData); } @@ -930,7 +930,7 @@ DisplayVCHeader ( //@@TestCase B2.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is less than required length in + //@@The declared length in the device descriptor is less than required length in //@@ the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", VCInterfaceDesc->bLength, uSize); @@ -962,8 +962,8 @@ DisplayVCHeader ( //@@Not yet implemented - Priority 1 //@@Descriptor Field - baInterfaceNr //@@We should test to verify each interface number is valid? - // for (i=0; ibInCollection; i++) - // {AppendTextBuffer("baInterfaceNr[%d]: 0x%02X\r\n", i+1, + // for (i=0; ibInCollection; i++) + // {AppendTextBuffer("baInterfaceNr[%d]: 0x%02X\r\n", i+1, // VCInterfaceDesc->baInterfaceNr[i]);} @@ -1016,25 +1016,25 @@ DisplayVCInputTerminal ( AppendTextBuffer("wTerminalType: 0x%04X", VidITDesc->wTerminalType); if(gDoAnnotation) { - pStr = GetStringFromList(slInputTermTypes, + pStr = GetStringFromList(slInputTermTypes, sizeof(slInputTermTypes) / sizeof(STRINGLIST), - VidITDesc->wTerminalType, + VidITDesc->wTerminalType, "Invalid Input Terminal Type"); - AppendTextBuffer(" = (%s)", pStr); + AppendTextBuffer(" = (%s)", pStr); } AppendTextBuffer("\r\n"); - + AppendTextBuffer("bAssocTerminal: 0x%02X\r\n", VidITDesc->bAssocTerminal); AppendTextBuffer("iTerminal: 0x%02X\r\n", VidITDesc->iTerminal); if (gDoAnnotation) { if (VidITDesc->iTerminal) { - // if executing this code, the configuration descriptor has been + // if executing this code, the configuration descriptor has been // obtained. If a device is suspended, then its configuration - // descriptor was not obtained and we do not want errors to be + // descriptor was not obtained and we do not want errors to be // displayed when string descriptors were not obtained. - DisplayStringDescriptor(VidITDesc->iTerminal, StringDescs, LatestDevicePowerState); + DisplayStringDescriptor(VidITDesc->iTerminal, StringDescs, LatestDevicePowerState); } } @@ -1043,7 +1043,7 @@ DisplayVCInputTerminal ( //@@TestCase B3.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is less than required length in + //@@The declared length in the device descriptor is less than required length in //@@ the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d is too small\r\n", VidITDesc->bLength); OOPS(); @@ -1131,11 +1131,11 @@ DisplayVCOutputTerminal ( AppendTextBuffer("wTerminalType: 0x%04X", VidOTDesc->wTerminalType); if(gDoAnnotation) { - pStr = GetStringFromList(slOutputTermTypes, + pStr = GetStringFromList(slOutputTermTypes, sizeof(slOutputTermTypes) / sizeof(STRINGLIST), - VidOTDesc->wTerminalType, + VidOTDesc->wTerminalType, "Invalid Output Terminal Type"); - AppendTextBuffer(" = (%s)", pStr); + AppendTextBuffer(" = (%s)", pStr); } AppendTextBuffer("\r\n"); AppendTextBuffer("bAssocTerminal: 0x%02X\r\n", VidOTDesc->bAssocTerminal); @@ -1145,9 +1145,9 @@ DisplayVCOutputTerminal ( { if (VidOTDesc->iTerminal) { - // if executing this code, the configuration descriptor has been + // if executing this code, the configuration descriptor has been // obtained. If a device is suspended, then its configuration - // descriptor was not obtained and we do not want errors to be + // descriptor was not obtained and we do not want errors to be // displayed when string descriptors were not obtained. DisplayStringDescriptor(VidOTDesc->iTerminal, StringDescs, LatestDevicePowerState); } @@ -1158,7 +1158,7 @@ DisplayVCOutputTerminal ( //@@TestCase B4.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is less than required length in + //@@The declared length in the device descriptor is less than required length in //@@ the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d is too small\r\n", VidOTDesc->bLength); OOPS(); @@ -1252,7 +1252,7 @@ DisplayVCMediaTransInputTerminal( bLength = SizeOfVideoInputMTT(MediaTransportInDesc); AppendTextBuffer("===>Additional Media Transport Input Terminal Data\r\n"); - AppendTextBuffer("bControlSize: 0x%02X\r\n", + AppendTextBuffer("bControlSize: 0x%02X\r\n", MediaTransportInDesc->bControlSize); // point to bControlSize @@ -1263,12 +1263,12 @@ DisplayVCMediaTransInputTerminal( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1277,9 +1277,9 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportControls, + GetStringFromList(slMediaTransportControls, sizeof(slMediaTransportControls) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportCtrl bmControl value")); cMask = cMask << 1; @@ -1294,12 +1294,12 @@ DisplayVCMediaTransInputTerminal( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1308,18 +1308,18 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes1, + GetStringFromList(slMediaTransportModes1, sizeof(slMediaTransportModes1) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; } - + // Is there a second control? if (1 < * pData) { - // map the second control + // map the second control for ( uBitIndex = 8, cMask = 1; uBitIndex < 16; uBitIndex++ ) { cCheckBit = cMask & *(pData + 2); @@ -1328,9 +1328,9 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes2, + GetStringFromList(slMediaTransportModes2, sizeof(slMediaTransportModes2) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1339,7 +1339,7 @@ DisplayVCMediaTransInputTerminal( // Is there a third control? if (2 < * pData) { - // map the third control + // map the third control for ( uBitIndex = 16, cMask = 1; uBitIndex < 24; uBitIndex++ ) { cCheckBit = cMask & *(pData + 3); @@ -1348,9 +1348,9 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes3, + GetStringFromList(slMediaTransportModes3, sizeof(slMediaTransportModes3) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1359,7 +1359,7 @@ DisplayVCMediaTransInputTerminal( // Is there a fourth control? if (3 < * pData) { - // map the fourth control + // map the fourth control for ( uBitIndex = 24, cMask = 1; uBitIndex < 32; uBitIndex++ ) { cCheckBit = cMask & *(pData + 4); @@ -1368,9 +1368,9 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes4, + GetStringFromList(slMediaTransportModes4, sizeof(slMediaTransportModes4) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1379,7 +1379,7 @@ DisplayVCMediaTransInputTerminal( // Is there a fifth control? if (4 < * pData) { - // map the fifth control + // map the fifth control for ( uBitIndex = 32, cMask = 1; uBitIndex < 40; uBitIndex++ ) { cCheckBit = cMask & *(pData + 5); @@ -1388,9 +1388,9 @@ DisplayVCMediaTransInputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes5, + GetStringFromList(slMediaTransportModes5, sizeof(slMediaTransportModes5) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1398,13 +1398,13 @@ DisplayVCMediaTransInputTerminal( } } - // The size of a Media Transport Descriptor is + // The size of a Media Transport Descriptor is // the size of the Descriptor plus // (bControlSize - 1) plus // IF bmControls & 1 THEN 1 (bTransportModeSize) plus // bTransportModeSize - // -// p = sizeof(VIDEO_INPUT_MTT) + + // +// p = sizeof(VIDEO_INPUT_MTT) + // (MediaTransportInDesc->bControlSize - 1); // if (MediaTransportInDesc->bmControls[0] & 1) // p += 1 + (*pData); @@ -1440,7 +1440,7 @@ DisplayVCMediaTransOutputTerminal( PUCHAR pData = NULL; AppendTextBuffer("===>Additional Media Transport Output Terminal Data\r\n"); - AppendTextBuffer("bControlSize: 0x%02X\r\n", + AppendTextBuffer("bControlSize: 0x%02X\r\n", MediaTransportOutDesc->bControlSize); // point to bControlSize @@ -1451,12 +1451,12 @@ DisplayVCMediaTransOutputTerminal( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1465,9 +1465,9 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportControls, + GetStringFromList(slMediaTransportControls, sizeof(slMediaTransportControls) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportCtrl bmControl value")); cMask = cMask << 1; @@ -1482,12 +1482,12 @@ DisplayVCMediaTransOutputTerminal( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1496,18 +1496,18 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes1, + GetStringFromList(slMediaTransportModes1, sizeof(slMediaTransportModes1) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; } - + // Is there a second control? if (1 < * pData) { - // map the second control + // map the second control for ( uBitIndex = 8, cMask = 1; uBitIndex < 16; uBitIndex++ ) { cCheckBit = cMask & *(pData + 2); @@ -1516,9 +1516,9 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes2, + GetStringFromList(slMediaTransportModes2, sizeof(slMediaTransportModes2) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1527,7 +1527,7 @@ DisplayVCMediaTransOutputTerminal( // Is there a third control? if (2 < * pData) { - // map the third control + // map the third control for ( uBitIndex = 16, cMask = 1; uBitIndex < 24; uBitIndex++ ) { cCheckBit = cMask & *(pData + 3); @@ -1536,9 +1536,9 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes3, + GetStringFromList(slMediaTransportModes3, sizeof(slMediaTransportModes3) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1547,7 +1547,7 @@ DisplayVCMediaTransOutputTerminal( // Is there a fourth control? if (3 < * pData) { - // map the fourth control + // map the fourth control for ( uBitIndex = 24, cMask = 1; uBitIndex < 32; uBitIndex++ ) { cCheckBit = cMask & *(pData + 4); @@ -1556,9 +1556,9 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes4, + GetStringFromList(slMediaTransportModes4, sizeof(slMediaTransportModes4) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1567,7 +1567,7 @@ DisplayVCMediaTransOutputTerminal( // Is there a fifth control? if (4 < * pData) { - // map the fourth control + // map the fourth control for ( uBitIndex = 32, cMask = 1; uBitIndex < 40; uBitIndex++ ) { cCheckBit = cMask & *(pData + 5); @@ -1576,9 +1576,9 @@ DisplayVCMediaTransOutputTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slMediaTransportModes5, + GetStringFromList(slMediaTransportModes5, sizeof(slMediaTransportModes5) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid MediaTransportMode value")); cMask = cMask << 1; @@ -1586,13 +1586,13 @@ DisplayVCMediaTransOutputTerminal( } } - // The size of a Media Transport Descriptor is + // The size of a Media Transport Descriptor is // the size of the Descriptor plus // (bControlSize - 1) plus // IF bmControls & 1 THEN 1 (bTransportModeSize) plus // bTransportModeSize - // - p = sizeof(VIDEO_OUTPUT_MTT) + + // + p = sizeof(VIDEO_OUTPUT_MTT) + (MediaTransportOutDesc->bControlSize - 1); if (MediaTransportOutDesc->bmControls[0] & 1) p += 1 + (*pData); @@ -1640,12 +1640,12 @@ DisplayVCCameraTerminal( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1654,18 +1654,18 @@ DisplayVCCameraTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slCameraControl1, + GetStringFromList(slCameraControl1, sizeof(slCameraControl1) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid CamCtrl bmControl value")); cMask = cMask << 1; } - + // Is there a second control? if (1 < * pData) { - // map the second control + // map the second control for ( uBitIndex = 8, cMask = 1; uBitIndex < 16; uBitIndex++ ) { cCheckBit = cMask & *(pData + 2); @@ -1674,9 +1674,9 @@ DisplayVCCameraTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slCameraControl2, + GetStringFromList(slCameraControl2, sizeof(slCameraControl2) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid CamCtrl bmControl value")); cMask = cMask << 1; @@ -1685,7 +1685,7 @@ DisplayVCCameraTerminal( // Is there a third control? if (2 < * pData) { - // map the third control + // map the third control for ( uBitIndex = 16, cMask = 1; uBitIndex < 24; uBitIndex++ ) { cCheckBit = cMask & *(pData + 3); @@ -1694,9 +1694,9 @@ DisplayVCCameraTerminal( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slCameraControl3, + GetStringFromList(slCameraControl3, sizeof(slCameraControl3) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid CamCtrl bmControl value")); cMask = cMask << 1; @@ -1710,7 +1710,7 @@ DisplayVCCameraTerminal( //@@TestCase B7.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The descriptor should be the size of the descriptor structure + //@@The descriptor should be the size of the descriptor structure //@@ plus the number of controls AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", CameraDesc->bLength, p); @@ -1784,16 +1784,16 @@ DisplayVCSelectorUnit ( AppendTextBuffer("bDescriptorSubtype: 0x%02X\r\n", VidSelectorDesc->bDescriptorSubtype); AppendTextBuffer("bUnitID: 0x%02X\r\n", VidSelectorDesc->bUnitID); AppendTextBuffer("bNrInPins: 0x%02X\r\n", VidSelectorDesc->bNrInPins); - if (gDoAnnotation) + if (gDoAnnotation) { AppendTextBuffer("===>List of Connected Unit and Terminal ID's\r\n"); } // baSourceID is a variable length field // Size is in bNrInPins, must be at least 1 (so index starts at 1) - for (i = 1, pData = (PUCHAR) &VidSelectorDesc->baSourceID; + for (i = 1, pData = (PUCHAR) &VidSelectorDesc->baSourceID; i <= VidSelectorDesc->bNrInPins; i++, pData++) { - AppendTextBuffer("baSourceID[%d]: 0x%02X\r\n", + AppendTextBuffer("baSourceID[%d]: 0x%02X\r\n", i, *pData); } @@ -1804,9 +1804,9 @@ DisplayVCSelectorUnit ( { if (*pData) { - // if executing this code, the configuration descriptor has been + // if executing this code, the configuration descriptor has been // obtained. If a device is suspended, then its configuration - // descriptor was not obtained and we do not want errors to be + // descriptor was not obtained and we do not want errors to be // displayed when string descriptors were not obtained. DisplayStringDescriptor(*pData, StringDescs, LatestDevicePowerState); } @@ -1848,7 +1848,7 @@ DisplayVCSelectorUnit ( // baSourceID is a variable length field // Size is in bNrInPins, must be at least 1 (so index starts at 1) - for (i = 1, pData = (PUCHAR) &VidSelectorDesc->baSourceID; + for (i = 1, pData = (PUCHAR) &VidSelectorDesc->baSourceID; i <= VidSelectorDesc->bNrInPins; i++, pData++) { if (*pData < 1) @@ -1908,12 +1908,12 @@ DisplayVCProcessingUnit ( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; AppendTextBuffer("bmControls : "); VDisplayBytes(pData + 1, *pData); - - // map the first control + + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + 1); @@ -1922,18 +1922,18 @@ DisplayVCProcessingUnit ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slProcessorControls1, + GetStringFromList(slProcessorControls1, sizeof(slProcessorControls1) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid PU bmControl value")); cMask = cMask << 1; } - + // Is there a second control? if (1 < * pData) { - // map the second control + // map the second control for ( uBitIndex = 8, cMask = 1; uBitIndex < 16; uBitIndex++ ) { cCheckBit = cMask & *(pData + 2); @@ -1942,19 +1942,19 @@ DisplayVCProcessingUnit ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slProcessorControls2, + GetStringFromList(slProcessorControls2, sizeof(slProcessorControls2) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid PU bmControl value")); cMask = cMask << 1; } } - + // Is there a third control? if (2 < * pData) { - // map the third control + // map the third control for ( uBitIndex = 16, cMask = 1; uBitIndex < 24; uBitIndex++ ) { cCheckBit = cMask & *(pData + 3); @@ -1963,9 +1963,9 @@ DisplayVCProcessingUnit ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slProcessorControls3, + GetStringFromList(slProcessorControls3, sizeof(slProcessorControls3) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid PU bmControl value")); cMask = cMask << 1; @@ -1991,9 +1991,9 @@ DisplayVCProcessingUnit ( { if (*pData) { - // if executing this code, the configuration descriptor has been + // if executing this code, the configuration descriptor has been // obtained. If a device is suspended, then its configuration - // descriptor was not obtained and we do not want errors to be + // descriptor was not obtained and we do not want errors to be // displayed when string descriptors were not obtained. DisplayStringDescriptor(*pData, StringDescs, LatestDevicePowerState); } @@ -2004,14 +2004,14 @@ DisplayVCProcessingUnit ( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; pData = (PUCHAR) VidProcessingDesc + (VidProcessingDesc->bLength - 1); AppendTextBuffer("bmVideoStandards : "); VDisplayBytes(pData, 1); - // map the first control + // map the first control for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData); @@ -2020,9 +2020,9 @@ DisplayVCProcessingUnit ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slProcessorVideoStandards, + GetStringFromList(slProcessorVideoStandards, sizeof(slProcessorVideoStandards) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid PU bmVideoStandards value")); cMask = cMask << 1; @@ -2106,16 +2106,16 @@ DisplayVCExtensionUnit ( AppendTextBuffer("guidExtensionCode: %S\r\n", szGUID); AppendTextBuffer("bNumControls: 0x%02X\r\n", VidExtensionDesc->bNumControls); AppendTextBuffer("bNrInPins: 0x%02X\r\n", VidExtensionDesc->bNrInPins); - if (gDoAnnotation) - { + if (gDoAnnotation) + { AppendTextBuffer("===>List of Connected Units and Terminal ID's\r\n"); } // baSourceID is a variable length field // Size is in bNrInPins, must be at least 1 (so index starts at 1) - for (i = 1, pData = (PUCHAR) &VidExtensionDesc->baSourceID; + for (i = 1, pData = (PUCHAR) &VidExtensionDesc->baSourceID; i <= VidExtensionDesc->bNrInPins; i++, pData++) { - AppendTextBuffer("baSourceID[%d]: 0x%02X\r\n", + AppendTextBuffer("baSourceID[%d]: 0x%02X\r\n", i, *pData); } // point to bControlSize (address of bNrInPins plus number of fields in bNrInPins @@ -2135,9 +2135,9 @@ DisplayVCExtensionUnit ( { UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; - - // map byte + BYTE cMask = 1; + + // map byte for ( ; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData + i); @@ -2149,7 +2149,7 @@ DisplayVCExtensionUnit ( "Vendor-Specific (Optional)"); cMask = cMask << 1; - } + } } } @@ -2166,15 +2166,15 @@ DisplayVCExtensionUnit ( } // size of descriptor struct size (23) + bNrInPins + bControlSize + iExtension size - // -// p = (sizeof(VIDEO_EXTENSION_UNIT) + // +// p = (sizeof(VIDEO_EXTENSION_UNIT) // + VidExtensionDesc->bNrInPins + bControlSize + 1); if (VidExtensionDesc->bLength != bLength) { //@@TestCase B10.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the + //@@The declared length in the device descriptor is not equal to the //@@ required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of 0x%02X incorrect, should be 0x%02X\r\n", VidExtensionDesc->bLength, p); @@ -2204,7 +2204,7 @@ DisplayVCExtensionUnit ( OOPS(); } - for (i = 1, pData = (PUCHAR) &VidExtensionDesc->baSourceID; + for (i = 1, pData = (PUCHAR) &VidExtensionDesc->baSourceID; i <= VidExtensionDesc->bNrInPins; i++, pData++) { if (*pData == 0) @@ -2252,13 +2252,13 @@ DisplayVidInHeader ( AppendTextBuffer(" -> Validated\r\n"); } - AppendTextBuffer("bEndpointAddress: 0x%02X", + AppendTextBuffer("bEndpointAddress: 0x%02X", VidInHeaderDesc->bEndpointAddress); - if (USB_ENDPOINT_DIRECTION_IN(VidInHeaderDesc->bEndpointAddress)) + if (USB_ENDPOINT_DIRECTION_IN(VidInHeaderDesc->bEndpointAddress)) { if (gDoAnnotation) - { - AppendTextBuffer(" -> Direction: IN - EndpointID: %d", + { + AppendTextBuffer(" -> Direction: IN - EndpointID: %d", (VidInHeaderDesc->bEndpointAddress & 0x0F)); } AppendTextBuffer("\r\n"); @@ -2269,9 +2269,9 @@ DisplayVidInHeader ( AppendTextBuffer(" -> Dynamic Format Change %sSupported", ! (VidInHeaderDesc->bmInfo & 0x01) ? "not " : " "); } - AppendTextBuffer("\r\nbTerminalLink: 0x%02X\r\n", + AppendTextBuffer("\r\nbTerminalLink: 0x%02X\r\n", VidInHeaderDesc->bTerminalLink); - AppendTextBuffer("bStillCaptureMethod: 0x%02X", + AppendTextBuffer("bStillCaptureMethod: 0x%02X", VidInHeaderDesc->bStillCaptureMethod); // globally save the StillMethod, then verify value @@ -2287,35 +2287,35 @@ DisplayVidInHeader ( if (gDoAnnotation) { AppendTextBuffer(" -> Invalid Still Capture Method"); - } + } } else { if (0 == StillMethod) - { + { AppendTextBuffer(" -> No Still Capture"); } else { - AppendTextBuffer(" -> Still Capture Method %d", + AppendTextBuffer(" -> Still Capture Method %d", VidInHeaderDesc->bStillCaptureMethod); } } - AppendTextBuffer("\r\nbTriggerSupport: 0x%02X", + AppendTextBuffer("\r\nbTriggerSupport: 0x%02X", VidInHeaderDesc->bTriggerSupport); if(gDoAnnotation) { AppendTextBuffer(" -> "); - if (! VidInHeaderDesc->bTriggerSupport) + if (! VidInHeaderDesc->bTriggerSupport) AppendTextBuffer("No "); AppendTextBuffer("Hardware Triggering Support"); } AppendTextBuffer("\r\n"); - AppendTextBuffer("bTriggerUsage: 0x%02X", + AppendTextBuffer("bTriggerUsage: 0x%02X", VidInHeaderDesc->bTriggerUsage); - if (gDoAnnotation) + if (gDoAnnotation) { if (VidInHeaderDesc->bTriggerSupport != 0) { @@ -2326,7 +2326,7 @@ DisplayVidInHeader ( } } - AppendTextBuffer("\r\nbControlSize: 0x%02X\r\n", + AppendTextBuffer("\r\nbControlSize: 0x%02X\r\n", VidInHeaderDesc->bControlSize); // are there formats to display? @@ -2335,7 +2335,7 @@ DisplayVidInHeader ( UINT uFormatIndex = 1; UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; // There are (bNumFormats) bmaControls fields, each with size (bControlSize) pData = (PUCHAR) &(VidInHeaderDesc->bControlSize); @@ -2355,8 +2355,8 @@ DisplayVidInHeader ( else { VDisplayBytes(pData, VidInHeaderDesc->bControlSize); - - // map the first control + + // map the first control for (uBitIndex = 0, cMask = 1; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pData); @@ -2365,9 +2365,9 @@ DisplayVidInHeader ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slInputHeaderControls, + GetStringFromList(slInputHeaderControls, sizeof(slInputHeaderControls) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid Control value")); cMask = cMask << 1; @@ -2376,16 +2376,16 @@ DisplayVidInHeader ( pData += VidInHeaderDesc->bControlSize; } } - - p = (sizeof(VIDEO_STREAMING_INPUT_HEADER) + + + p = (sizeof(VIDEO_STREAMING_INPUT_HEADER) + (VidInHeaderDesc->bNumFormats * VidInHeaderDesc->bControlSize)); - if (VidInHeaderDesc->bLength != p) + if (VidInHeaderDesc->bLength != p) { //@@TestCase B11.2 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The descriptor should be the size of the descriptor structure - //@@ plus the number of formats times the size of each format + //@@The descriptor should be the size of the descriptor structure + //@@ plus the number of formats times the size of each format AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", VidInHeaderDesc->bLength, p); OOPS(); @@ -2514,7 +2514,7 @@ DisplayVidOutHeader ( // point to first bmaControls pControls++; - // Size of UVC 1.1 Video Output Header is 1.0 size + // Size of UVC 1.1 Video Output Header is 1.0 size // plus 1 (bControlSize field) plus (number of formats * bControlSize) bLength += 1 + (VidOutHeaderDesc->bNumFormats * bControlSize); @@ -2527,7 +2527,7 @@ DisplayVidOutHeader ( UINT uFormatIndex = 1; UINT uBitIndex = 0; BYTE cCheckBit = 0; - BYTE cMask = 1; + BYTE cMask = 1; // There are (bNumFormats) bmaControls fields, each with size (bControlSize) for ( ; uFormatIndex <= VidOutHeaderDesc->bNumFormats; uFormatIndex++, pControls ++) @@ -2542,8 +2542,8 @@ DisplayVidOutHeader ( else { VDisplayBytes(pControls, bControlSize); - - // map the first control + + // map the first control for (uBitIndex = 0, cMask = 1; uBitIndex < 8; uBitIndex++ ) { cCheckBit = cMask & *(pControls); @@ -2552,9 +2552,9 @@ DisplayVidOutHeader ( uBitIndex, cCheckBit ? 1 : 0, cCheckBit ? "yes - " : " no - ", - GetStringFromList(slOutputHeaderControls, + GetStringFromList(slOutputHeaderControls, sizeof(slOutputHeaderControls) / sizeof(STRINGLIST), - cMask, + cMask, "Invalid control value")); cMask = cMask << 1; @@ -2569,11 +2569,11 @@ DisplayVidOutHeader ( //@@TestCase B12.1 (also in Descript.c) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the + //@@The declared length in the device descriptor is not equal to the //@@ required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", VidOutHeaderDesc->bLength, - sizeof(VIDEO_STREAMING_OUTPUT_HEADER)); + (UCHAR) sizeof(VIDEO_STREAMING_OUTPUT_HEADER)); OOPS(); } @@ -2665,7 +2665,7 @@ DisplayStillImageFrame ( AppendTextBuffer("bDescriptorType: 0x%02X\r\n", StillFrameDesc->bDescriptorType); AppendTextBuffer("bDescriptorSubtype: 0x%02X\r\n", StillFrameDesc->bDescriptorSubtype); AppendTextBuffer("bEndpointAddress: 0x%02X\r\n", StillFrameDesc->bEndpointAddress); - AppendTextBuffer("bNumImageSizePatterns: 0x%02X\r\n", + AppendTextBuffer("bNumImageSizePatterns: 0x%02X\r\n", StillFrameDesc->bNumImageSizePatterns); if (StillFrameDesc->bNumImageSizePatterns < 1) { @@ -2681,7 +2681,7 @@ DisplayStillImageFrame ( // point to first StillFrameDesc->dwStillImage structure pXY = (VIDEO_STILL_IMAGE_RECT *) &StillFrameDesc->aStillRect[0]; - for (i = 1; i <= StillFrameDesc->bNumImageSizePatterns; i++, pXY++) + for (i = 1; i <= StillFrameDesc->bNumImageSizePatterns; i++, pXY++) { AppendTextBuffer("wWidth[%d]: 0x%04X\r\n", i, pXY->wWidth); @@ -2694,10 +2694,10 @@ DisplayStillImageFrame ( uNumComp = *pbCurr; AppendTextBuffer("bNumCompressionPattern: 0x%02X\r\n", *pbCurr++); - for (i = 1; i <= uNumComp; i++) + for (i = 1; i <= uNumComp; i++) { - AppendTextBuffer("bCompression[%d]: 0x%02X\r\n", - i, *pbCurr++); + AppendTextBuffer("bCompression[%d]: 0x%02X\r\n", + i, *pbCurr++); } switch(StillMethod) { @@ -2747,9 +2747,9 @@ DisplayStillImageFrame ( "This should be non-zero when using StillMethod 3.\r\n", (StillFrameDesc->bEndpointAddress)); OOPS(); } - if (gDoAnnotation) + if (gDoAnnotation) { - AppendTextBuffer(" -> Direction: IN - EndpointID: %d", + AppendTextBuffer(" -> Direction: IN - EndpointID: %d", (StillFrameDesc->bEndpointAddress & 0x0F)); } AppendTextBuffer("\r\n"); @@ -2807,7 +2807,7 @@ DisplayColorMatching ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", ColorMatchDesc->bLength, - sizeof(VIDEO_COLORFORMAT)); + (UCHAR) sizeof(VIDEO_COLORFORMAT)); OOPS(); } @@ -2835,7 +2835,7 @@ DisplayColorMatching ( //***************************************************************************** // -// DisplayUncompressedFormat() +// DisplayUncompressedFormat() // //***************************************************************************** @@ -2865,13 +2865,13 @@ DisplayUncompressedFormat ( AppendTextBuffer("guidFormat: %S", szGUID); pStr = VidFormatGUIDCodeToName((REFGUID) &UnCompFormatDesc->guidFormat); - if ( pStr ) + if ( pStr ) { if ( gDoAnnotation ) { AppendTextBuffer(" = %s Format", pStr); } - } + } AppendTextBuffer("\r\n"); AppendTextBuffer("bBitsPerPixel: 0x%02X\r\n", UnCompFormatDesc->bBitsPerPixel); AppendTextBuffer("bDefaultFrameIndex: 0x%02X\r\n", UnCompFormatDesc->bDefaultFrameIndex); @@ -2881,11 +2881,11 @@ DisplayUncompressedFormat ( //@@TestCase B15.1 (descript.c line 925) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the required + //@@The declared length in the device descriptor is not equal to the required //@@length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", UnCompFormatDesc->bLength, - sizeof(VIDEO_FORMAT_UNCOMPRESSED)); + (UCHAR) sizeof(VIDEO_FORMAT_UNCOMPRESSED)); OOPS(); } @@ -2904,7 +2904,7 @@ DisplayUncompressedFormat ( //@@TestCase B15.3 (descript.c line 930) //@@ERROR //@@Descriptor Field - bNumFrameDescriptors - //@@bNumFrameDescriptors is set to zero which is not in accordance with the + //@@bNumFrameDescriptors is set to zero which is not in accordance with the //@@USB Video Device Specification AppendTextBuffer("*!*ERROR: bNumFrameDescriptors = 0, must have at least 1 Frame descriptor\r\n"); OOPS(); @@ -2930,7 +2930,7 @@ DisplayUncompressedFormat ( OOPS(); } - if (UnCompFormatDesc->bDefaultFrameIndex == 0 || UnCompFormatDesc->bDefaultFrameIndex > + if (UnCompFormatDesc->bDefaultFrameIndex == 0 || UnCompFormatDesc->bDefaultFrameIndex > UnCompFormatDesc->bNumFrameDescriptors) { //@@TestCase B15.6 (desctipt.c line 945) @@ -2943,28 +2943,28 @@ DisplayUncompressedFormat ( OOPS(); } - AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", + AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", UnCompFormatDesc->bAspectRatioX); - AppendTextBuffer("bAspectRatioY: 0x%02X", + AppendTextBuffer("bAspectRatioY: 0x%02X", UnCompFormatDesc->bAspectRatioY); - if (((UnCompFormatDesc->bmInterlaceFlags & 0x01) && - (UnCompFormatDesc->bAspectRatioY != 0 && + if (((UnCompFormatDesc->bmInterlaceFlags & 0x01) && + (UnCompFormatDesc->bAspectRatioY != 0 && UnCompFormatDesc->bAspectRatioX != 0))) { - if(gDoAnnotation) + if(gDoAnnotation) { AppendTextBuffer(" -> Aspect Ratio is set for a %d:%d display", - (UnCompFormatDesc->bAspectRatioX),(UnCompFormatDesc->bAspectRatioY)); - } - else + (UnCompFormatDesc->bAspectRatioX),(UnCompFormatDesc->bAspectRatioY)); + } + else { if (UnCompFormatDesc->bAspectRatioY != 0 || UnCompFormatDesc->bAspectRatioX != 0) { //@@TestCase B15.7 //@@ERROR //@@Descriptor Field - bAspectRatioX, bAspectRatioY - //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero + //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero //@@ if stream is non-interlaced AppendTextBuffer("\r\n*!*ERROR: Both bAspectRatioX and bAspectRatioY "\ "must equal 0 if stream is non-interlaced"); @@ -2972,27 +2972,27 @@ DisplayUncompressedFormat ( } } } - AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", + AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", UnCompFormatDesc->bmInterlaceFlags); - if (gDoAnnotation) + if (gDoAnnotation) { - AppendTextBuffer(" D0 = 0x%02X Interlaced stream or variable: %s\r\n", + AppendTextBuffer(" D0 = 0x%02X Interlaced stream or variable: %s\r\n", (UnCompFormatDesc->bmInterlaceFlags & 1), (UnCompFormatDesc->bmInterlaceFlags & 1) ? "Yes" : "No"); - AppendTextBuffer(" D1 = 0x%02X Fields per frame: %s\r\n", + AppendTextBuffer(" D1 = 0x%02X Fields per frame: %s\r\n", ((UnCompFormatDesc->bmInterlaceFlags >> 1) & 1), ((UnCompFormatDesc->bmInterlaceFlags >> 1) & 1) ? "1 field" : "2 fields"); - AppendTextBuffer(" D2 = 0x%02X Field 1 first: %s\r\n", + AppendTextBuffer(" D2 = 0x%02X Field 1 first: %s\r\n", ((UnCompFormatDesc->bmInterlaceFlags >> 2) & 1), ((UnCompFormatDesc->bmInterlaceFlags >> 2) & 1) ? "Yes" : "No"); //@@TestCase B15.9 //@@Not yet implemented - Priority 1 //@@Descriptor Field - bmInterlaceFlags //@@Validate that reserved bits (D3) are set to zero. - AppendTextBuffer(" D3 = 0x%02X Reserved%s\r\n", + AppendTextBuffer(" D3 = 0x%02X Reserved%s\r\n", ((UnCompFormatDesc->bmInterlaceFlags >> 3) & 1), - ((UnCompFormatDesc->bmInterlaceFlags >> 3) & 1) ? + ((UnCompFormatDesc->bmInterlaceFlags >> 3) & 1) ? "\r\n*!*ERROR: Reserved to 0" : "" ); AppendTextBuffer(" D4..5 = 0x%02X Field patterns ->", ((UnCompFormatDesc->bmInterlaceFlags >> 4) & 3)); @@ -3038,11 +3038,11 @@ DisplayUncompressedFormat ( //@@TestCase B15.11 //@@Not yet implemented - Priority 1 //@@Descriptor Field - bCopyProtect - //@@Question - Are their reserved bits and should we validate that + //@@Question - Are their reserved bits and should we validate that //@@ reserved bits are set to zero? - AppendTextBuffer("\r\nbCopyProtect: 0x%02X", + AppendTextBuffer("\r\nbCopyProtect: 0x%02X", UnCompFormatDesc->bCopyProtect); - if (gDoAnnotation) + if (gDoAnnotation) { if (UnCompFormatDesc->bCopyProtect) AppendTextBuffer(" -> Duplication Restricted"); @@ -3079,10 +3079,10 @@ DisplayUncompressedFrameType ( //@@DisplayUncompressedFrameType -Uncompressed Frame AppendTextBuffer("\r\n ===>Video Streaming Uncompressed Frame Type Descriptor<===\r\n"); - if (gDoAnnotation) + if (gDoAnnotation) { if(UnCompFrameDesc->bFrameIndex == g_chUNCFrameDefault) - { + { AppendTextBuffer(" --->This is the Default (optimum) Frame index\r\n"); } } @@ -3103,7 +3103,7 @@ DisplayUncompressedFrameType ( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", UnCompFrameDesc->dwDefaultFrameInterval, ((double)UnCompFrameDesc->dwDefaultFrameInterval)/10000.0, (10000000.0/((double)UnCompFrameDesc->dwDefaultFrameInterval)) @@ -3115,10 +3115,10 @@ DisplayUncompressedFrameType ( //@@TestCase B15.1 (descript.c line 925) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the required + //@@The declared length in the device descriptor is not equal to the required //@@length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", - UnCompFrameDesc->bLength, bLength); + UnCompFrameDesc->bLength, (UCHAR) bLength); OOPS(); } @@ -3127,7 +3127,7 @@ DisplayUncompressedFrameType ( //@@TestCase B16.2 (descript.c line 991) //@@ERROR //@@Descriptor Field - bFrameIndex - //@@bFrameIndex must be nonzero + //@@bFrameIndex must be nonzero AppendTextBuffer("*!*ERROR: bFrameIndex = 0, this is a 1 based index\r\n"); OOPS(); } @@ -3187,9 +3187,9 @@ DisplayUncompressedFrameType ( AppendTextBuffer("*!*ERROR: dwMinBitRate should be less than dwMaxBitRate\r\n"); OOPS(); } - else + else { - if (UnCompFrameDesc->bFrameIntervalType == 1 && + if (UnCompFrameDesc->bFrameIntervalType == 1 && UnCompFrameDesc->dwMinBitRate != UnCompFrameDesc->dwMaxBitRate) { //@@TestCase B16.9 @@ -3257,12 +3257,12 @@ DisplayUnComContinuousFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMinFrameInterval, ((double)dwMinFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMinFrameInterval) + 0.5)); - - AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + + AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMaxFrameInterval, ((double)dwMaxFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMaxFrameInterval) + 0.5)); @@ -3367,7 +3367,7 @@ DisplayUnComDiscreteFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", iNdex, *ulFrameInterval, ((double)*ulFrameInterval)/10000.0, (10000000.0/((double)*ulFrameInterval)) @@ -3422,11 +3422,11 @@ DisplayMJPEGFormat ( //@@TestCase B19.1 (descript.c line 1098) //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the + //@@The declared length in the device descriptor is not equal to the //@@ required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", MJPEGFormatDesc->bLength, - sizeof(VIDEO_FORMAT_MJPEG)); + (UCHAR) sizeof(VIDEO_FORMAT_MJPEG)); OOPS(); } @@ -3435,7 +3435,7 @@ DisplayMJPEGFormat ( //@@TestCase B19.2 (descript.c line 1103) //@@ERROR //@@Descriptor Field - bFormatIndex - //@@bFormatIndex is set to zero which is not in accordance with + //@@bFormatIndex is set to zero which is not in accordance with //@@ the USB Video Device Specification AppendTextBuffer("*!*ERROR: bFormatIndex must be non-zero\r\n"); OOPS(); @@ -3446,41 +3446,41 @@ DisplayMJPEGFormat ( //@@TestCase B19.3 (descript.c line 1108) //@@ERROR //@@Descriptor Field - bNumFrameDescriptors - //@@bNumFrameDescriptors is set to zero which is not in accordance + //@@bNumFrameDescriptors is set to zero which is not in accordance //@@ with the USB Video Device Specification AppendTextBuffer("*!*ERROR: bNumFrameDescriptors must be non-zero\r\n"); OOPS(); } - AppendTextBuffer("bmFlags: 0x%02X", + AppendTextBuffer("bmFlags: 0x%02X", (MJPEGFormatDesc->bmFlags & 0x01)); //@@TestCase B19.4 //@@Not yet implemented - Priority 1 //@@Descriptor Field - bmFlags //@@We should validate that reserved bits are set to zero. - if (gDoAnnotation) + if (gDoAnnotation) { if(MJPEGFormatDesc->bmFlags & 0x01) - { + { AppendTextBuffer(" -> Sample Size is Fixed"); } else - { + { AppendTextBuffer(" -> Sample Size is Not Fixed"); } } - AppendTextBuffer("\r\nbDefaultFrameIndex: 0x%02X\r\n", + AppendTextBuffer("\r\nbDefaultFrameIndex: 0x%02X\r\n", MJPEGFormatDesc->bDefaultFrameIndex); - if (MJPEGFormatDesc->bDefaultFrameIndex == 0 || - MJPEGFormatDesc->bDefaultFrameIndex > + if (MJPEGFormatDesc->bDefaultFrameIndex == 0 || + MJPEGFormatDesc->bDefaultFrameIndex > MJPEGFormatDesc->bNumFrameDescriptors) { //@@TestCase B19.5 (descript.c line 1113) //@@ERROR //@@Descriptor Field - bDefaultFrameIndex - //@@bDefaultFrameIndex is not in the domain of constrained by + //@@bDefaultFrameIndex is not in the domain of constrained by //@@ bNumFrameDescriptors AppendTextBuffer("*!*ERROR: bDefaultFrameIndex 0x%02X invalid, should "\ "be between 1 and 0x%02x/r/n", @@ -3489,56 +3489,56 @@ DisplayMJPEGFormat ( OOPS(); } - AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", + AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", MJPEGFormatDesc->bAspectRatioX); - AppendTextBuffer("bAspectRatioY: 0x%02X", + AppendTextBuffer("bAspectRatioY: 0x%02X", MJPEGFormatDesc->bAspectRatioY); - if(((MJPEGFormatDesc->bmInterlaceFlags & 0x01) && - ((MJPEGFormatDesc->bAspectRatioY != 0) && - (MJPEGFormatDesc->bAspectRatioX != 0)))) + if(((MJPEGFormatDesc->bmInterlaceFlags & 0x01) && + ((MJPEGFormatDesc->bAspectRatioY != 0) && + (MJPEGFormatDesc->bAspectRatioX != 0)))) { if (gDoAnnotation) { - AppendTextBuffer(" -> Aspect Ratio is set for a %d:%d display", + AppendTextBuffer(" -> Aspect Ratio is set for a %d:%d display", (MJPEGFormatDesc->bAspectRatioX), (MJPEGFormatDesc->bAspectRatioY)); } } - else + else { if (MJPEGFormatDesc->bAspectRatioY != 0 || MJPEGFormatDesc->bAspectRatioX != 0) { //@@TestCase B19.6 //@@ERROR //@@Descriptor Field - bAspectRatioX and bAspectRatioY - //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero + //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero //@@ if stream is non-interlaced AppendTextBuffer("\r\n*!*ERROR: bAspectRatioX and bAspectRatioY must "\ "be 0 if stream non-Interlaced"); OOPS(); } } - AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", + AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", MJPEGFormatDesc->bmInterlaceFlags); if (gDoAnnotation) { - AppendTextBuffer(" D00 = %x %sInterlaced stream or variable\r\n", + AppendTextBuffer(" D00 = %x %sInterlaced stream or variable\r\n", (MJPEGFormatDesc->bmInterlaceFlags & 1), (MJPEGFormatDesc->bmInterlaceFlags & 1) ? "" : " non-"); - AppendTextBuffer(" D01 = %x %s per frame\r\n", + AppendTextBuffer(" D01 = %x %s per frame\r\n", ((MJPEGFormatDesc->bmInterlaceFlags >> 1) & 1), ((MJPEGFormatDesc->bmInterlaceFlags >> 1) & 1) ? " 1 field" : " 2 fields"); - AppendTextBuffer(" D02 = %x Field 1 %sfirst\r\n", + AppendTextBuffer(" D02 = %x Field 1 %sfirst\r\n", ((MJPEGFormatDesc->bmInterlaceFlags >> 2) & 1), ((MJPEGFormatDesc->bmInterlaceFlags >> 2) & 1) ? "" : "not "); //@@TestCase B19.7 //@@Not yet implemented - Priority 1 //@@Descriptor Field - bmInterlaceFlags //@@Validate that reserved bits (D3) are set to zero. - AppendTextBuffer(" D03 = %x Reserved%s\r\n", + AppendTextBuffer(" D03 = %x Reserved%s\r\n", ((MJPEGFormatDesc->bmInterlaceFlags >> 3) & 1), - ((MJPEGFormatDesc->bmInterlaceFlags >> 3) & 1) ? + ((MJPEGFormatDesc->bmInterlaceFlags >> 3) & 1) ? "\r\n*!*ERROR: non zero" : "" ); AppendTextBuffer(" D4..5 = %x Field patterns ->", ((MJPEGFormatDesc->bmInterlaceFlags >> 4) & 3)); @@ -3583,11 +3583,11 @@ DisplayMJPEGFormat ( //@@TestCase B19.9 //@@Not yet implemented - Priority 1 //@@Descriptor Field - bCopyProtect - //@@Question - Are their reserved bits and should we validate that + //@@Question - Are their reserved bits and should we validate that //@@ reserved bits are set to zero? - AppendTextBuffer("\r\nbCopyProtect: 0x%02X", + AppendTextBuffer("\r\nbCopyProtect: 0x%02X", MJPEGFormatDesc->bCopyProtect); - if (gDoAnnotation) + if (gDoAnnotation) { if (MJPEGFormatDesc->bCopyProtect) AppendTextBuffer(" -> Duplication Restricted"); @@ -3620,10 +3620,10 @@ DisplayMJPEGFrameType ( bLength = SizeOfVideoFrameMjpeg(MJPEGFrameDesc); AppendTextBuffer("\r\n ===>Video Streaming MJPEG Frame Type Descriptor<===\r\n"); - if (gDoAnnotation) + if (gDoAnnotation) { if(MJPEGFrameDesc->bFrameIndex == g_chMJPEGFrameDefault) - { + { AppendTextBuffer(" --->This is the Default (optimum) Frame index\r\n"); } } @@ -3645,7 +3645,7 @@ DisplayMJPEGFrameType ( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", MJPEGFrameDesc->dwDefaultFrameInterval, ((double)MJPEGFrameDesc->dwDefaultFrameInterval)/10000.0, (10000000.0/((double)MJPEGFrameDesc->dwDefaultFrameInterval)) @@ -3659,7 +3659,7 @@ DisplayMJPEGFrameType ( //@@Descriptor Field - bLength //@@The declared length in the device descriptor is less than required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d is incorrect, should be %d\r\n", - MJPEGFrameDesc->bLength, bLength); + MJPEGFrameDesc->bLength, (UCHAR) bLength); OOPS(); } @@ -3796,12 +3796,12 @@ DisplayMJPEGContinuousFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMinFrameInterval, ((double)dwMinFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMinFrameInterval) + 0.5)); - - AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + + AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMaxFrameInterval, ((double)dwMaxFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMaxFrameInterval) + 0.5)); @@ -3907,7 +3907,7 @@ DisplayMJPEGDiscreteFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", iNdex, *ulFrameInterval, ((double)*ulFrameInterval)/10000.0, (10000000.0/((double)*ulFrameInterval)) @@ -3969,7 +3969,7 @@ DisplayMPEG1SSFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d. USBView cannot correctly display descriptor\r\n", MPEG1SSFormatDesc->bLength, - sizeof(VIDEO_FORMAT_MPEG1SS)); + (UCHAR) sizeof(VIDEO_FORMAT_MPEG1SS)); OOPS(); } @@ -4035,7 +4035,7 @@ DisplayMPEG2PSFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d. USBView cannot correctly display descriptor\r\n", MPEG2PSFormatDesc->bLength, - sizeof(VIDEO_FORMAT_MPEG2PS)); + (UCHAR) sizeof(VIDEO_FORMAT_MPEG2PS)); OOPS(); AppendTextBuffer("*!*USBView will try to display the rest of the descriptor but results may not be accurate\r\n"); } @@ -4115,13 +4115,13 @@ DisplayMPEG2TSFormat ( i++; AppendTextBuffer("guidStrideFormat: %S", szGUID); pStr = VidFormatGUIDCodeToName((REFGUID) pStrideGuid); - if(gDoAnnotation) + if(gDoAnnotation) { if (pStr) { AppendTextBuffer(" = %s Format", pStr); } - } + } AppendTextBuffer("\r\n"); bLength = sizeof(VIDEO_FORMAT_MPEG2TS) + sizeof(GUID); } @@ -4134,7 +4134,7 @@ DisplayMPEG2TSFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", MPEG2TSFormatDesc->bLength, - sizeof(VIDEO_FORMAT_MPEG2TS)); + (UCHAR) sizeof(VIDEO_FORMAT_MPEG2TS)); OOPS(); } @@ -4186,7 +4186,7 @@ DisplayMPEG4SLFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d. USBView cannot correctly display descriptor\r\n", MPEG4SLFormatDesc->bLength, - sizeof(VIDEO_FORMAT_MPEG4SL)); + (UCHAR) sizeof(VIDEO_FORMAT_MPEG4SL)); OOPS(); } @@ -4244,13 +4244,13 @@ DisplayStreamPayload ( AppendTextBuffer("guidFormat: %S", szGUID); pStr = VidFormatGUIDCodeToName((REFGUID) &StreamPayloadDesc->guidFormat); - if(gDoAnnotation) + if(gDoAnnotation) { if (pStr) { AppendTextBuffer(" = %s Format", pStr); } - } + } AppendTextBuffer("\r\n"); AppendTextBuffer("dwPacketLength: 0x%02X\r\n", StreamPayloadDesc->dwPacketLength); @@ -4261,7 +4261,7 @@ DisplayStreamPayload ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", StreamPayloadDesc->bLength, - sizeof(PVIDEO_FORMAT_STREAM)); + (UCHAR) sizeof(PVIDEO_FORMAT_STREAM)); OOPS(); } @@ -4302,10 +4302,10 @@ DisplayDVFormat ( AppendTextBuffer("bFormatIndex: 0x%02X\r\n", DVFormatDesc->bFormatIndex); AppendTextBuffer("dwMaxVideoFrameBufferSize: 0x%08X\r\n", DVFormatDesc->dwMaxVideoFrameBufferSize); AppendTextBuffer("bFormatType: 0x%02X\r\n", DVFormatDesc->bFormatType); - if (gDoAnnotation) + if (gDoAnnotation) { AppendTextBuffer(" D0..6 = Format Type ->"); - switch(DVFormatDesc->bFormatType & 0x03) + switch(DVFormatDesc->bFormatType & 0x03) { case 0x00: AppendTextBuffer(" SD-DV\r\n"); @@ -4334,7 +4334,7 @@ DisplayDVFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", DVFormatDesc->bLength, - sizeof(VIDEO_FORMAT_DV)); + (UCHAR) sizeof(VIDEO_FORMAT_DV)); OOPS(); } @@ -4344,7 +4344,7 @@ DisplayDVFormat ( //@@ERROR //@@Descriptor Field - bFormatIndex //@@bFormatIndex invalid - AppendTextBuffer("*!*ERROR: bFormatIndex of 0x%02X is invalid\r\n", + AppendTextBuffer("*!*ERROR: bFormatIndex of 0x%02X is invalid\r\n", DVFormatDesc->bFormatIndex); OOPS(); } @@ -4355,7 +4355,7 @@ DisplayDVFormat ( //@@ERROR //@@Descriptor Field - dwMaxVideoFrameBufferSize //@@dwMaxVideoFrameBufferSize invalid - AppendTextBuffer("*!*ERROR: dwMaxVideoFrameBufferSize of 0x%02X is invalid\r\n", + AppendTextBuffer("*!*ERROR: dwMaxVideoFrameBufferSize of 0x%02X is invalid\r\n", DVFormatDesc->dwMaxVideoFrameBufferSize); OOPS(); } @@ -4420,7 +4420,7 @@ DisplayVendorVidFormat ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d. USBView cannot correctly display descriptor\r\n", VendorVidFormatDesc->bLength, - sizeof(VIDEO_FORMAT_VENDOR)); + (UCHAR) sizeof(VIDEO_FORMAT_VENDOR)); OOPS(); } @@ -4528,10 +4528,10 @@ DisplayVendorVidFrameType ( bLength = SizeOfVideoFrameVendor(VendorVidFrameDesc); AppendTextBuffer("\r\n ===>Video Streaming Vendor Video Frame Type Descriptor<===\r\n"); - if (gDoAnnotation) + if (gDoAnnotation) { if(VendorVidFrameDesc->bFrameIndex == g_chVendorFrameDefault) - { + { AppendTextBuffer(" --->This is the Default (optimum) Frame index\r\n"); } } @@ -4547,7 +4547,7 @@ DisplayVendorVidFrameType ( //@@Descriptor Field - bLength //@@The declared length in the device descriptor is less than required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", - VendorVidFrameDesc->bLength, bLength); + VendorVidFrameDesc->bLength, (UCHAR) bLength); OOPS(); } @@ -4587,7 +4587,7 @@ DisplayVendorVidFrameType ( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", VendorVidFrameDesc->dwDefaultFrameInterval, ((double)VendorVidFrameDesc->dwDefaultFrameInterval)/10000.0, (10000000.0/((double)VendorVidFrameDesc->dwDefaultFrameInterval)) @@ -4645,7 +4645,7 @@ DisplayVendorVidFrameType ( } else { - if (VendorVidFrameDesc->bFrameIntervalType == 1 && + if (VendorVidFrameDesc->bFrameIntervalType == 1 && VendorVidFrameDesc->dwMinBitRate != VendorVidFrameDesc->dwMaxBitRate) { //@@TestCase B29.9 @@ -4726,12 +4726,12 @@ DisplayVendorVidContinuousFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMinFrameInterval, ((double)dwMinFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMinFrameInterval) + 0.5)); - - AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + + AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMaxFrameInterval, ((double)dwMaxFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMaxFrameInterval) + 0.5)); @@ -4836,7 +4836,7 @@ DisplayVendorVidDiscreteFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", iNdex, *ulFrameInterval, ((double)*ulFrameInterval)/10000.0, (10000000.0/((double)*ulFrameInterval)) @@ -4867,7 +4867,7 @@ DisplayVendorVidDiscreteFrameType( //***************************************************************************** // -// DisplayFramePayloadFormat() +// DisplayFramePayloadFormat() // //***************************************************************************** @@ -4897,13 +4897,13 @@ DisplayFramePayloadFormat ( AppendTextBuffer("guidFormat: %S", szGUID); pStr = VidFormatGUIDCodeToName((REFGUID) &FramePayloadFormatDesc->guidFormat); - if ( pStr ) + if ( pStr ) { if ( gDoAnnotation ) { AppendTextBuffer(" = %s Format", pStr); } - } + } AppendTextBuffer("\r\n"); AppendTextBuffer("bBitsPerPixel: 0x%02X\r\n", FramePayloadFormatDesc->bBitsPerPixel); AppendTextBuffer("bDefaultFrameIndex: 0x%02X\r\n", FramePayloadFormatDesc->bDefaultFrameIndex); @@ -4912,11 +4912,11 @@ DisplayFramePayloadFormat ( { //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the required + //@@The declared length in the device descriptor is not equal to the required //@@length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", FramePayloadFormatDesc->bLength, - sizeof(VIDEO_FORMAT_FRAME)); + (UCHAR) sizeof(VIDEO_FORMAT_FRAME)); OOPS(); } @@ -4933,7 +4933,7 @@ DisplayFramePayloadFormat ( { //@@ERROR //@@Descriptor Field - bNumFrameDescriptors - //@@bNumFrameDescriptors is set to zero which is not in accordance with the + //@@bNumFrameDescriptors is set to zero which is not in accordance with the //@@USB Video Device Specification AppendTextBuffer("*!*ERROR: bNumFrameDescriptors = 0, must have at least 1 Frame descriptor\r\n"); OOPS(); @@ -4957,7 +4957,7 @@ DisplayFramePayloadFormat ( OOPS(); } - if (FramePayloadFormatDesc->bDefaultFrameIndex == 0 || FramePayloadFormatDesc->bDefaultFrameIndex > + if (FramePayloadFormatDesc->bDefaultFrameIndex == 0 || FramePayloadFormatDesc->bDefaultFrameIndex > FramePayloadFormatDesc->bNumFrameDescriptors) { //@@ERROR @@ -4969,27 +4969,27 @@ DisplayFramePayloadFormat ( OOPS(); } - AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", + AppendTextBuffer("bAspectRatioX: 0x%02X\r\n", FramePayloadFormatDesc->bAspectRatioX); - AppendTextBuffer("bAspectRatioY: 0x%02X", + AppendTextBuffer("bAspectRatioY: 0x%02X", FramePayloadFormatDesc->bAspectRatioY); - if (((FramePayloadFormatDesc->bmInterlaceFlags & 0x01) && - (FramePayloadFormatDesc->bAspectRatioY != 0 && + if (((FramePayloadFormatDesc->bmInterlaceFlags & 0x01) && + (FramePayloadFormatDesc->bAspectRatioY != 0 && FramePayloadFormatDesc->bAspectRatioX != 0))) { - if(gDoAnnotation) + if(gDoAnnotation) { AppendTextBuffer(" -> Aspect Ratio is set for a %d:%d display", - (FramePayloadFormatDesc->bAspectRatioX),(FramePayloadFormatDesc->bAspectRatioY)); - } - else + (FramePayloadFormatDesc->bAspectRatioX),(FramePayloadFormatDesc->bAspectRatioY)); + } + else { if (FramePayloadFormatDesc->bAspectRatioY != 0 || FramePayloadFormatDesc->bAspectRatioX != 0) { //@@ERROR //@@Descriptor Field - bAspectRatioX, bAspectRatioY - //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero + //@@Verify that that bAspectRatioX and bAspectRatioY are set to zero //@@ if stream is non-interlaced AppendTextBuffer("\r\n*!*ERROR: Both bAspectRatioX and bAspectRatioY "\ "must equal 0 if stream is non-interlaced"); @@ -4997,25 +4997,25 @@ DisplayFramePayloadFormat ( } } } - AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", + AppendTextBuffer("\r\nbmInterlaceFlags: 0x%02X\r\n", FramePayloadFormatDesc->bmInterlaceFlags); - if (gDoAnnotation) + if (gDoAnnotation) { - AppendTextBuffer(" D0 = 0x%02X Interlaced stream or variable: %s\r\n", + AppendTextBuffer(" D0 = 0x%02X Interlaced stream or variable: %s\r\n", (FramePayloadFormatDesc->bmInterlaceFlags & 1), (FramePayloadFormatDesc->bmInterlaceFlags & 1) ? "Yes" : "No"); - AppendTextBuffer(" D1 = 0x%02X Fields per frame: %s\r\n", + AppendTextBuffer(" D1 = 0x%02X Fields per frame: %s\r\n", ((FramePayloadFormatDesc->bmInterlaceFlags >> 1) & 1), ((FramePayloadFormatDesc->bmInterlaceFlags >> 1) & 1) ? "1 field" : "2 fields"); - AppendTextBuffer(" D2 = 0x%02X Field 1 first: %s\r\n", + AppendTextBuffer(" D2 = 0x%02X Field 1 first: %s\r\n", ((FramePayloadFormatDesc->bmInterlaceFlags >> 2) & 1), ((FramePayloadFormatDesc->bmInterlaceFlags >> 2) & 1) ? "Yes" : "No"); //@@Descriptor Field - bmInterlaceFlags //@@Validate that reserved bits (D3) are set to zero. - AppendTextBuffer(" D3 = 0x%02X Reserved%s\r\n", + AppendTextBuffer(" D3 = 0x%02X Reserved%s\r\n", ((FramePayloadFormatDesc->bmInterlaceFlags >> 3) & 1), - ((FramePayloadFormatDesc->bmInterlaceFlags >> 3) & 1) ? + ((FramePayloadFormatDesc->bmInterlaceFlags >> 3) & 1) ? "\r\n*!*ERROR: Reserved to 0" : "" ); AppendTextBuffer(" D4..5 = 0x%02X Field patterns ->", ((FramePayloadFormatDesc->bmInterlaceFlags >> 4) & 3)); @@ -5057,11 +5057,11 @@ DisplayFramePayloadFormat ( } //@@Descriptor Field - bCopyProtect - //@@Question - Are their reserved bits and should we validate that + //@@Question - Are their reserved bits and should we validate that //@@ reserved bits are set to zero? - AppendTextBuffer("\r\nbCopyProtect: 0x%02X", + AppendTextBuffer("\r\nbCopyProtect: 0x%02X", FramePayloadFormatDesc->bCopyProtect); - if (gDoAnnotation) + if (gDoAnnotation) { if (FramePayloadFormatDesc->bCopyProtect) AppendTextBuffer(" -> Duplication Restricted"); @@ -5070,9 +5070,9 @@ DisplayFramePayloadFormat ( } //@@Descriptor Field - bVariableSize - AppendTextBuffer("\r\nbVariableSize: 0x%02X", + AppendTextBuffer("\r\nbVariableSize: 0x%02X", FramePayloadFormatDesc->bVariableSize); - if (gDoAnnotation) + if (gDoAnnotation) { if (FramePayloadFormatDesc->bVariableSize) AppendTextBuffer(" -> Variable Size"); @@ -5112,10 +5112,10 @@ DisplayFramePayloadFrame ( //@@DisplayFramePayloadFrame -Frame Based Payload Frame AppendTextBuffer("\r\n ===>Video Streaming Frame Based Payload Frame Type Descriptor<===\r\n"); - if (gDoAnnotation) + if (gDoAnnotation) { if(FramePayloadFrameDesc->bFrameIndex == g_chFrameBasedFrameDefault) - { + { AppendTextBuffer(" --->This is the Default (optimum) Frame index\r\n"); } } @@ -5135,7 +5135,7 @@ DisplayFramePayloadFrame ( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwDefaultFrameInterval: 0x%08X = %lf mSec (%4.2f Hz)\r\n", FramePayloadFrameDesc->dwDefaultFrameInterval, ((double)FramePayloadFrameDesc->dwDefaultFrameInterval)/10000.0, (10000000.0/((double)FramePayloadFrameDesc->dwDefaultFrameInterval)) @@ -5146,10 +5146,10 @@ DisplayFramePayloadFrame ( { //@@ERROR //@@Descriptor Field - bLength - //@@The declared length in the device descriptor is not equal to the required + //@@The declared length in the device descriptor is not equal to the required //@@length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n", - FramePayloadFrameDesc->bLength, bLength); + FramePayloadFrameDesc->bLength, (UCHAR) bLength); OOPS(); } @@ -5157,7 +5157,7 @@ DisplayFramePayloadFrame ( { //@@ERROR //@@Descriptor Field - bFrameIndex - //@@bFrameIndex must be nonzero + //@@bFrameIndex must be nonzero AppendTextBuffer("*!*ERROR: bFrameIndex = 0, this is a 1 based index\r\n"); OOPS(); } @@ -5210,9 +5210,9 @@ DisplayFramePayloadFrame ( AppendTextBuffer("*!*ERROR: dwMinBitRate should be less than dwMaxBitRate\r\n"); OOPS(); } - else + else { - if (FramePayloadFrameDesc->bFrameIntervalType == 1 && + if (FramePayloadFrameDesc->bFrameIntervalType == 1 && FramePayloadFrameDesc->dwMinBitRate != FramePayloadFrameDesc->dwMaxBitRate) { //@@WARNING @@ -5275,12 +5275,12 @@ DisplayFramePayloadContinuousFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + AppendTextBuffer("dwMinFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMinFrameInterval, ((double)dwMinFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMinFrameInterval) + 0.5)); - - AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", + + AppendTextBuffer("dwMaxFrameInterval: 0x%08X = %lf mSec (%d Hz)\r\n", dwMaxFrameInterval, ((double)dwMaxFrameInterval)/10000.0, (ULONG)(10000000.0/((double)dwMaxFrameInterval) + 0.5)); @@ -5378,7 +5378,7 @@ DisplayFramePayloadDiscreteFrameType( // To convert the frame interval to Hz, we divide by 10,000,000 and then take the inverse - AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", + AppendTextBuffer("dwFrameInterval[%d]: 0x%08X = %lf mSec (%4.2f Hz)\r\n", iNdex, *ulFrameInterval, ((double)*ulFrameInterval)/10000.0, (10000000.0/((double)*ulFrameInterval)) @@ -5435,7 +5435,7 @@ DisplayVSEndpoint ( //@@The declared length in the device descriptor is not equal to the required length in the USB Video Device Specification AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d. USBView cannot correctly display descriptor\r\n", VidEndpointDesc->bLength, - sizeof(VIDEO_CS_INTERRUPT)); + (UCHAR) sizeof(VIDEO_CS_INTERRUPT)); OOPS(); } @@ -5489,17 +5489,17 @@ VidFormatGUIDCodeToName ( if (IsEqualGUID(VidFormatGUIDCode, (REFGUID) &YUY2_Format)) { return (PCHAR) &"YUY2"; - } + } if (IsEqualGUID(VidFormatGUIDCode, (REFGUID) &NV12_Format)) { return (PCHAR) &"NV12"; - } + } #ifdef H264_SUPPORT // GUID pH264 = H264_Format; if (IsEqualGUID(VidFormatGUIDCode, (REFGUID) &H264_Format)) { return (PCHAR) &"H.264"; - } + } #endif return FALSE; diff --git a/usb/usbview/enum.c b/usb/usbview/enum.c index fd427f688..297e0d320 100644 --- a/usb/usbview/enum.c +++ b/usb/usbview/enum.c @@ -296,77 +296,74 @@ EnumerateHostControllers ( { deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - success = SetupDiEnumDeviceInterfaces(deviceInfo, - 0, - (LPGUID)&GUID_CLASS_USB_HOST_CONTROLLER, - index, - &deviceInterfaceData); - - if (!success) + for (int devInterfaceIndex = 0; + SetupDiEnumDeviceInterfaces(deviceInfo, + &deviceInfoData, + (LPGUID)&GUID_CLASS_USB_HOST_CONTROLLER, + devInterfaceIndex, + &deviceInterfaceData); + devInterfaceIndex++) { - OOPS(); - break; - } - - success = SetupDiGetDeviceInterfaceDetail(deviceInfo, - &deviceInterfaceData, - NULL, - 0, - &requiredLength, - NULL); + success = SetupDiGetDeviceInterfaceDetail(deviceInfo, + &deviceInterfaceData, + NULL, + 0, + &requiredLength, + NULL); - if (!success && GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - OOPS(); - break; - } + if (!success && GetLastError() != ERROR_INSUFFICIENT_BUFFER) + { + OOPS(); + break; + } - deviceDetailData = ALLOC(requiredLength); - if (deviceDetailData == NULL) - { - OOPS(); - break; - } + deviceDetailData = ALLOC(requiredLength); + if (deviceDetailData == NULL) + { + OOPS(); + break; + } - deviceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); + deviceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); - success = SetupDiGetDeviceInterfaceDetail(deviceInfo, - &deviceInterfaceData, - deviceDetailData, - requiredLength, - &requiredLength, - NULL); + success = SetupDiGetDeviceInterfaceDetail(deviceInfo, + &deviceInterfaceData, + deviceDetailData, + requiredLength, + &requiredLength, + NULL); - if (!success) - { - OOPS(); - break; - } + if (!success) + { + OOPS(); + break; + } - hHCDev = CreateFile(deviceDetailData->DevicePath, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - OPEN_EXISTING, - 0, - NULL); + hHCDev = CreateFile(deviceDetailData->DevicePath, + GENERIC_WRITE, + FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + 0, + NULL); + + // If the handle is valid, then we've successfully opened a Host + // Controller. Display some info about the Host Controller itself, + // then enumerate the Root Hub attached to the Host Controller. + // + if (hHCDev != INVALID_HANDLE_VALUE) + { + EnumerateHostController(hTreeParent, + hHCDev, + deviceDetailData->DevicePath, + deviceInfo, + &deviceInfoData); - // If the handle is valid, then we've successfully opened a Host - // Controller. Display some info about the Host Controller itself, - // then enumerate the Root Hub attached to the Host Controller. - // - if (hHCDev != INVALID_HANDLE_VALUE) - { - EnumerateHostController(hTreeParent, - hHCDev, - deviceDetailData->DevicePath, - deviceInfo, - &deviceInfoData); + CloseHandle(hHCDev); + } - CloseHandle(hHCDev); + FREE(deviceDetailData); } - - FREE(deviceDetailData); } SetupDiDestroyDeviceInfoList(deviceInfo); diff --git a/usb/wdf_osrfx2_lab/README.md b/usb/wdf_osrfx2_lab/README.md index aee7a8865..d24a43d06 100644 --- a/usb/wdf_osrfx2_lab/README.md +++ b/usb/wdf_osrfx2_lab/README.md @@ -10,6 +10,13 @@ products: # WDF Sample Driver Learning Lab for OSR USB-FX2 +> [!WARNING] +> UMDF 2 is the latest version of UMDF and supersedes UMDF 1. All new UMDF drivers should be written using UMDF 2. No new features are being added to UMDF 1 and there is limited support for UMDF 1 on newer versions of Windows 10. Universal Windows drivers must use UMDF 2. +> +> For more info, see [Getting Started with UMDF](https://docs.microsoft.com/windows-hardware/drivers/wdf/getting-started-with-umdf-version-2). +> +> The UMDF v1 sample can be accessed using `git checkout win11-22h2`. A direct link is: https://github.com/microsoft/Windows-driver-samples/tree/win11-22h2 + The wdf\_osrfx2\_lab sample contains a console test application and a series of iterative drivers for both Kernel-Mode Driver Framework (KMDF) and User-Mode Driver Framework (UMDF) version 1. In the Windows Driver Kit (WDK) for Windows 7 and earlier versions of Windows, the osrusbfx2 sample demonstrated how to perform bulk and interrupt data transfers to an USB device. The sample was written for the OSR USB-FX2 Learning Kit. diff --git a/usb/wdf_osrfx2_lab/kmdf/exe/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/exe/osrusbfx2.vcxproj index 379f780d8..dfcc81e15 100644 --- a/usb/wdf_osrfx2_lab/kmdf/exe/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/exe/osrusbfx2.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -37,7 +37,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -45,7 +45,7 @@ Windows10 False - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application @@ -53,7 +53,7 @@ Windows10 True - Universal + Windows Driver WindowsApplicationForDrivers10.0 Application diff --git a/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.inx b/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.inx index f2172744a..0fc45d1ab 100644 Binary files a/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.inx and b/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.inx differ diff --git a/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.vcxproj index 24e5f83e0..673d4bdc9 100644 --- a/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/step1/osrusbfx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.inx b/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.inx index f2172744a..f7e12d740 100644 Binary files a/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.inx and b/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.inx differ diff --git a/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.vcxproj index d0fcebe4a..bd29a7dbb 100644 --- a/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/step2/osrusbfx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.inx b/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.inx index f2172744a..f7e12d740 100644 Binary files a/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.inx and b/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.inx differ diff --git a/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.vcxproj index 7bfade555..869d9caf7 100644 --- a/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/step3/osrusbfx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.inx b/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.inx index f2172744a..f7e12d740 100644 Binary files a/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.inx and b/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.inx differ diff --git a/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.vcxproj index a6527eaa8..fbe157476 100644 --- a/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/step4/osrusbfx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.inx b/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.inx index f2172744a..f7e12d740 100644 Binary files a/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.inx and b/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.inx differ diff --git a/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.vcxproj b/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.vcxproj index 98cde2a17..e42066037 100644 --- a/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.vcxproj +++ b/usb/wdf_osrfx2_lab/kmdf/step5/osrusbfx2.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj b/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj deleted file mode 100644 index 53ba424d3..000000000 --- a/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj +++ /dev/null @@ -1,223 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {B4244D54-7EBF-43D4-BB6D-C994C182C572} - $(MSBuildProjectName) - Debug - Win32 - {6A99CFCE-4C34-4F5D-B7D4-D810AE496B95} - - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - False - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - Windows10 - True - Desktop - - WindowsApplicationForDrivers10.0 - Application - - - - $(IntDir) - - - - - - - - - - - - - - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - WudfOsrUsbFx2Test - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - true - Level4 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(PreprocessorDefinitions);BUILT_IN_DDK=1;UNICODE=1;_UNICODE=1 - %(AdditionalIncludeDirectories);..\inc;..\..\inc;$(DDK_INC_PATH) - - - %(AdditionalDependencies);setupapi.lib - - - sha256 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj.Filters b/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj.Filters deleted file mode 100644 index a430f986c..000000000 --- a/usb/wdf_osrfx2_lab/umdf/exe/WudfOsrUsbFx2Test.vcxproj.Filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {047255FC-568B-4968-9167-306B7BC95B6D} - - - h;hpp;hxx;hm;inl;inc;xsd - {4B1DCCF4-7F0A-4571-BA4F-DF378E24BD68} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {AC1DECB1-7996-4C71-8D32-0543B4C57AD4} - - - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/exe/dump.c b/usb/wdf_osrfx2_lab/umdf/exe/dump.c deleted file mode 100644 index aef55116c..000000000 --- a/usb/wdf_osrfx2_lab/umdf/exe/dump.c +++ /dev/null @@ -1,444 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - DUMP.C - -Abstract: - - Routines to dump the descriptors information in a human readable form. - -Environment: - - user mode only - ---*/ - -#include -#include -#include -#include "devioctl.h" - -#pragma warning(disable:4200) // -#pragma warning(disable:4201) // nameless struct/union -#pragma warning(disable:4214) // bit field types other than int - -#include -#include "usbdi.h" -#include "public.h" - -#pragma warning(default:4200) -#pragma warning(default:4201) -#pragma warning(default:4214) - -HANDLE -OpenDevice( - _In_ BOOL Synchronous - ); - - -char* -usbDescriptorTypeString(UCHAR bDescriptorType ) -/*++ -Routine Description: - - Called to get ascii string of USB descriptor - -Arguments: - - PUSB_ENDPOINT_DESCRIPTOR->bDescriptorType or - PUSB_DEVICE_DESCRIPTOR->bDescriptorType or - PUSB_INTERFACE_DESCRIPTOR->bDescriptorType or - PUSB_STRING_DESCRIPTOR->bDescriptorType or - PUSB_POWER_DESCRIPTOR->bDescriptorType or - PUSB_CONFIGURATION_DESCRIPTOR->bDescriptorType - -Return Value: - - ptr to string - ---*/ -{ - - switch(bDescriptorType) { - - case USB_DEVICE_DESCRIPTOR_TYPE: - return "USB_DEVICE_DESCRIPTOR_TYPE"; - - case USB_CONFIGURATION_DESCRIPTOR_TYPE: - return "USB_CONFIGURATION_DESCRIPTOR_TYPE"; - - - case USB_STRING_DESCRIPTOR_TYPE: - return "USB_STRING_DESCRIPTOR_TYPE"; - - - case USB_INTERFACE_DESCRIPTOR_TYPE: - return "USB_INTERFACE_DESCRIPTOR_TYPE"; - - - case USB_ENDPOINT_DESCRIPTOR_TYPE: - return "USB_ENDPOINT_DESCRIPTOR_TYPE"; - - -#ifdef USB_POWER_DESCRIPTOR_TYPE // this is the older definintion which is actually obsolete - // workaround for temporary bug in 98ddk, older USB100.h file - case USB_POWER_DESCRIPTOR_TYPE: - return "USB_POWER_DESCRIPTOR_TYPE"; -#endif - -#ifdef USB_RESERVED_DESCRIPTOR_TYPE // this is the current version of USB100.h as in NT5DDK - - case USB_RESERVED_DESCRIPTOR_TYPE: - return "USB_RESERVED_DESCRIPTOR_TYPE"; - - case USB_CONFIG_POWER_DESCRIPTOR_TYPE: - return "USB_CONFIG_POWER_DESCRIPTOR_TYPE"; - - case USB_INTERFACE_POWER_DESCRIPTOR_TYPE: - return "USB_INTERFACE_POWER_DESCRIPTOR_TYPE"; -#endif // for current nt5ddk version of USB100.h - - default: - return "??? UNKNOWN!!"; - } -} - - -char * -usbEndPointTypeString(UCHAR bmAttributes) -/*++ -Routine Description: - - Called to get ascii string of endpt descriptor type - -Arguments: - - PUSB_ENDPOINT_DESCRIPTOR->bmAttributes - -Return Value: - - ptr to string - ---*/ -{ - UINT typ = bmAttributes & USB_ENDPOINT_TYPE_MASK; - - - switch( typ) { - case USB_ENDPOINT_TYPE_INTERRUPT: - return "USB_ENDPOINT_TYPE_INTERRUPT"; - - case USB_ENDPOINT_TYPE_BULK: - return "USB_ENDPOINT_TYPE_BULK"; - - case USB_ENDPOINT_TYPE_ISOCHRONOUS: - return "USB_ENDPOINT_TYPE_ISOCHRONOUS"; - - case USB_ENDPOINT_TYPE_CONTROL: - return "USB_ENDPOINT_TYPE_CONTROL"; - - default: - return "??? UNKNOWN!!"; - } -} - - -char * -usbConfigAttributesString(UCHAR bmAttributes) -/*++ -Routine Description: - - Called to get ascii string of USB_CONFIGURATION_DESCRIPTOR attributes - -Arguments: - - PUSB_CONFIGURATION_DESCRIPTOR->bmAttributes - -Return Value: - - ptr to string - ---*/ -{ - UINT typ = bmAttributes & USB_CONFIG_POWERED_MASK; - - - switch( typ) { - - case USB_CONFIG_BUS_POWERED: - return "USB_CONFIG_BUS_POWERED"; - - case USB_CONFIG_SELF_POWERED: - return "USB_CONFIG_SELF_POWERED"; - - case USB_CONFIG_REMOTE_WAKEUP: - return "USB_CONFIG_REMOTE_WAKEUP"; - - - default: - return "??? UNKNOWN!!"; - } -} - - -void -print_USB_CONFIGURATION_DESCRIPTOR(PUSB_CONFIGURATION_DESCRIPTOR cd) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB config descriptor - -Arguments: - - ptr to USB configuration descriptor - -Return Value: - - none - ---*/ -{ - printf("\n===================\nUSB_CONFIGURATION_DESCRIPTOR\n"); - - printf( - "bLength = 0x%x, decimal %u\n", cd->bLength, cd->bLength - ); - - printf( - "bDescriptorType = 0x%x ( %s )\n", cd->bDescriptorType, - usbDescriptorTypeString( cd->bDescriptorType ) - ); - - printf( - "wTotalLength = 0x%x, decimal %u\n", cd->wTotalLength, cd->wTotalLength - ); - - printf( - "bNumInterfaces = 0x%x, decimal %u\n", cd->bNumInterfaces, cd->bNumInterfaces - ); - - printf( - "bConfigurationValue = 0x%x, decimal %u\n", - cd->bConfigurationValue, cd->bConfigurationValue - ); - - printf( - "iConfiguration = 0x%x, decimal %u\n", cd->iConfiguration, cd->iConfiguration - ); - - printf( - "bmAttributes = 0x%x ( %s )\n", cd->bmAttributes, - usbConfigAttributesString( cd->bmAttributes ) - ); - - printf( - "MaxPower = 0x%x, decimal %u\n", cd->MaxPower, cd->MaxPower - ); -} - - -void -print_USB_INTERFACE_DESCRIPTOR(PUSB_INTERFACE_DESCRIPTOR id, UINT ix) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB interface descriptor - -Arguments: - - ptr to USB interface descriptor - -Return Value: - - none - ---*/ -{ - printf("\n-----------------------------\nUSB_INTERFACE_DESCRIPTOR #%u\n", ix); - - - printf( - "bLength = 0x%x\n", id->bLength - ); - - - printf( - "bDescriptorType = 0x%x ( %s )\n", id->bDescriptorType, - usbDescriptorTypeString( id->bDescriptorType ) - ); - - - printf( - "bInterfaceNumber = 0x%x\n", id->bInterfaceNumber - ); - printf( - "bAlternateSetting = 0x%x\n", id->bAlternateSetting - ); - printf( - "bNumEndpoints = 0x%x\n", id->bNumEndpoints - ); - printf( - "bInterfaceClass = 0x%x\n", id->bInterfaceClass - ); - printf( - "bInterfaceSubClass = 0x%x\n", id->bInterfaceSubClass - ); - printf( - "bInterfaceProtocol = 0x%x\n", id->bInterfaceProtocol - ); - printf( - "bInterface = 0x%x\n", id->iInterface - ); -} - - -void -print_USB_ENDPOINT_DESCRIPTOR(PUSB_ENDPOINT_DESCRIPTOR ed, int i) -/*++ -Routine Description: - - Called to do formatted ascii dump to console of a USB endpoint descriptor - -Arguments: - - ptr to USB endpoint descriptor, - index of this endpt in interface desc - -Return Value: - - none - ---*/ -{ - printf( - "------------------------------\nUSB_ENDPOINT_DESCRIPTOR for Pipe%02d\n", i - ); - - printf( - "bLength = 0x%x\n", ed->bLength - ); - - printf( - "bDescriptorType = 0x%x ( %s )\n", ed->bDescriptorType, - usbDescriptorTypeString( ed->bDescriptorType ) - ); - - if ( USB_ENDPOINT_DIRECTION_IN( ed->bEndpointAddress ) ) { - printf( - "bEndpointAddress= 0x%x ( INPUT )\n", ed->bEndpointAddress - ); - } else { - printf( - "bEndpointAddress= 0x%x ( OUTPUT )\n", ed->bEndpointAddress - ); - } - - printf( - "bmAttributes= 0x%x ( %s )\n", ed->bmAttributes, - usbEndPointTypeString ( ed->bmAttributes ) - ); - - printf( - "wMaxPacketSize= 0x%x, decimal %u\n", ed->wMaxPacketSize, - ed->wMaxPacketSize - ); - - printf( - "bInterval = 0x%x, decimal %u\n", ed->bInterval, ed->bInterval - ); -} - - -BOOL -DumpUsbConfig() -/*++ -Routine Description: - - Called to do formatted ascii dump to console of USB - configuration, interface, and endpoint descriptors. - -Arguments: - - none - -Return Value: - - TRUE or FALSE - ---*/ -{ - HANDLE hDev; - UINT success; - int siz, nBytes; - char buf[256] = {0}; - - hDev = OpenDevice(TRUE); - if(hDev == INVALID_HANDLE_VALUE) - { - return FALSE; - } - - siz = sizeof(buf); - - success = DeviceIoControl(hDev, - IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR, - NULL, - 0, - buf, - siz, - (PULONG) &nBytes, - NULL); - - if(success == FALSE) { - printf("Ioct - GetConfigDesc failed %u\n", GetLastError()); - } else { - - ULONG i; - UINT j, n; - char *pch; - PUSB_CONFIGURATION_DESCRIPTOR cd; - PUSB_INTERFACE_DESCRIPTOR id; - PUSB_ENDPOINT_DESCRIPTOR ed; - - pch = buf; - n = 0; - - cd = (PUSB_CONFIGURATION_DESCRIPTOR) pch; - - print_USB_CONFIGURATION_DESCRIPTOR( cd ); - - pch += cd->bLength; - - do { - id = (PUSB_INTERFACE_DESCRIPTOR) pch; - - print_USB_INTERFACE_DESCRIPTOR(id, n++); - - pch += id->bLength; - for (j=0; jbNumEndpoints; j++) { - - ed = (PUSB_ENDPOINT_DESCRIPTOR) pch; - - print_USB_ENDPOINT_DESCRIPTOR(ed,j); - - pch += ed->bLength; - } - i = (ULONG)(pch - buf); - - } while (iwTotalLength); - } - - CloseHandle(hDev); - - return success; - -} - diff --git a/usb/wdf_osrfx2_lab/umdf/exe/testapp.c b/usb/wdf_osrfx2_lab/umdf/exe/testapp.c deleted file mode 100644 index 48f494922..000000000 --- a/usb/wdf_osrfx2_lab/umdf/exe/testapp.c +++ /dev/null @@ -1,1367 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - - THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR - PURPOSE. - -Module Name: - - TESTAPP.C - -Abstract: - - Console test app for osrusbfx2 driver. - -Environment: - - user mode only - ---*/ - -#include -_Analysis_mode_(_Analysis_code_type_user_code_); - -#include -#include -#include -#include - -#include "devioctl.h" -#include "strsafe.h" - -#pragma warning(push) -#pragma warning(disable:4200) // -#pragma warning(disable:4201) // nameless struct/union -#pragma warning(disable:4214) // bit field types other than int - -#include -#include -#include "usbdi.h" -#include "public.h" - -#pragma warning(pop) - -#define WHILE(a) \ -while(__pragma(warning(disable:4127)) a __pragma(warning(disable:4127))) - -#define countof(x) (sizeof(x) / sizeof(x[0])) - -#define MAX_DEVPATH_LENGTH 256 -#define NUM_ASYNCH_IO 100 -#define BUFFER_SIZE 1024 -#define READER_TYPE 1 -#define WRITER_TYPE 2 - -BOOL G_fDumpUsbConfig = FALSE; // flags set in response to console command line switches -BOOL G_fDumpReadData = FALSE; -BOOL G_fRead = FALSE; -BOOL G_fWrite = FALSE; -BOOL G_fPlayWithDevice = FALSE; -BOOL G_fPerformAsyncIo = FALSE; -ULONG G_IterationCount = 1; //count of iterations of the test we are to perform -int G_WriteLen = 512; // #bytes to write -int G_ReadLen = 512; // #bytes to read -PCWSTR G_SendFileName = NULL; -ULONG G_SendFileInterval = 1; - -BOOL -DumpUsbConfig( // defined in dump.c - ); - -typedef enum _INPUT_FUNCTION { - LIGHT_ONE_BAR = 1, - CLEAR_ONE_BAR, - LIGHT_ALL_BARS, - CLEAR_ALL_BARS, - GET_BAR_GRAPH_LIGHT_STATE, - GET_SWITCH_STATE, - GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE, - GET_7_SEGEMENT_STATE, - SET_7_SEGEMENT_STATE, - RESET_DEVICE, - REENUMERATE_DEVICE, -} INPUT_FUNCTION; - -_Success_ (return != FALSE) -BOOL -GetDevicePath( - IN LPGUID InterfaceGuid, - _Out_writes_(BufLen) PWSTR DevicePath, - _In_ size_t BufLen - ) -{ - HDEVINFO HardwareDeviceInfo; - SP_DEVICE_INTERFACE_DATA DeviceInterfaceData; - PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL; - ULONG Length, RequiredLength = 0; - BOOL bResult; - HRESULT hr; - - HardwareDeviceInfo = SetupDiGetClassDevs( - InterfaceGuid, - NULL, - NULL, - (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); - - if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) { - wprintf(L"SetupDiGetClassDevs failed!\n"); - return FALSE; - } - - DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - - bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo, - 0, - InterfaceGuid, - 0, - &DeviceInterfaceData); - - if (bResult == FALSE) { - - LPVOID lpMsgBuf; - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR) &lpMsgBuf, - 0, - NULL - )) { - - printf("SetupDiEnumDeviceInterfaces failed: %s", (LPSTR)lpMsgBuf); - LocalFree(lpMsgBuf); - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - return FALSE; - } - - SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - NULL, - 0, - &RequiredLength, - NULL - ); - - DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) - LocalAlloc(LMEM_FIXED, RequiredLength); - - if (DeviceInterfaceDetailData == NULL) { - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - wprintf(L"Failed to allocate memory.\n"); - return FALSE; - } - - DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); - - Length = RequiredLength; - - bResult = SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - DeviceInterfaceDetailData, - Length, - &RequiredLength, - NULL); - - if (bResult == FALSE) { - - LPVOID lpMsgBuf; - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR) &lpMsgBuf, - 0, - NULL)) { - - printf("Error in SetupDiGetDeviceInterfaceDetail: %s\n", (LPSTR)lpMsgBuf); - LocalFree(lpMsgBuf); - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - return FALSE; - } - - hr = StringCchCopy(DevicePath, - BufLen, - DeviceInterfaceDetailData->DevicePath); - if (FAILED(hr)) { - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - return FALSE; - } - - SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); - LocalFree(DeviceInterfaceDetailData); - - return TRUE; - -} - -_Check_return_ -_Ret_notnull_ -_Success_(return != INVALID_HANDLE_VALUE) -HANDLE -OpenDevice( - _In_ BOOL Synchronous - ) - -/*++ -Routine Description: - - Called by main() to open an instance of our device after obtaining its name - -Arguments: - - Synchronous - TRUE, if Device is to be opened for synchronous access. - FALSE, otherwise. - -Return Value: - - Device handle on success else INVALID_HANDLE_VALUE - ---*/ - -{ - HANDLE hDev; - WCHAR completeDeviceName[MAX_DEVPATH_LENGTH]; - - if ( !GetDevicePath( - (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, - completeDeviceName, - countof(completeDeviceName)) ) - { - return INVALID_HANDLE_VALUE; - } - - wprintf(L"DeviceName = (%s)\n", completeDeviceName); - - hDev = CreateFile(completeDeviceName, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, // default security - OPEN_EXISTING, - ((Synchronous ? FILE_ATTRIBUTE_NORMAL : FILE_FLAG_OVERLAPPED) | SECURITY_IMPERSONATION), - NULL); - - if (hDev == INVALID_HANDLE_VALUE) { - wprintf(L"Failed to open the device, error - %d", GetLastError()); - } else { - wprintf(L"Opened the device successfully.\n"); - } - - return hDev; -} - - - -VOID -Usage() - -/*++ -Routine Description: - - Called by main() to dump usage info to the console when - the app is called with no parms or with an invalid parm - -Arguments: - - None - -Return Value: - - None - ---*/ - -{ - wprintf(L"Usage for osrusbfx2 testapp:\n"); - wprintf(L"-r where n is number of bytes to read\n"); - wprintf(L"-w where n is number of bytes to write\n"); - wprintf(L"-c where n is number of iterations (default = 1)\n"); - wprintf(L"-v -- dumps read data\n"); - wprintf(L"-p to control bar LEDs, seven segment, and dip switch\n"); - wprintf(L"-a to perform asynchronous I/O\n"); - wprintf(L"-u to dump USB configuration and pipe info \n"); - wprintf(L"-f [interval-seconds] to send a text file to the seven-segment display (UMDF only)\n"); - - return; -} - - -void -Parse( - _In_ int argc, - _In_reads_(argc) LPWSTR *argv - ) - -/*++ -Routine Description: - - Called by main() to parse command line parms - -Arguments: - - argc and argv that was passed to main() - -Return Value: - - Sets global flags as per user function request - ---*/ - -{ - int i; - PWSTR endchar; - - if ( argc < 2 ) // give usage if invoked with no parms - Usage(); - - for (i=0; i= argc) { - Usage(); - exit(1); - } - else { - G_ReadLen = wcstoul(&argv[i+1][0], &endchar, 10); - G_fRead = TRUE; - } - i++; - break; - case L'w': - case L'W': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_WriteLen = wcstoul(&argv[i+1][0], &endchar, 10); - G_fWrite = TRUE; - } - i++; - break; - case L'c': - case L'C': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_IterationCount = wcstoul(&argv[i+1][0], &endchar, 10); - } - i++; - break; - case L'f': - case L'F': - if (i+1 >= argc) { - Usage(); - exit(1); - } - else { - G_SendFileName = argv[i+1]; - } - - i++; - - if (i+1 < argc) { - G_SendFileInterval = wcstoul(&argv[i+1][0], &endchar, 10); - } - i++; - - break; - case L'u': - case L'U': - G_fDumpUsbConfig = TRUE; - break; - case L'p': - case L'P': - G_fPlayWithDevice = TRUE; - break; - case L'a': - case L'A': - G_fPerformAsyncIo = TRUE; - break; - case L'v': - case L'V': - G_fDumpReadData = TRUE; - break; - default: - Usage(); - } - } - } -} - -BOOL -Compare_Buffs( - _In_reads_bytes_(length) PVOID *buff1, - _In_reads_bytes_(length) PVOID *buff2, - _In_ int length - ) -/*++ -Routine Description: - - Called to verify read and write buffers match for loopback test - -Arguments: - - buffers to compare and length - -Return Value: - - TRUE if buffers match, else FALSE - ---*/ -{ - int ok = 1; - - if (memcmp(buff1, buff2, length )) { - // Edi, and Esi point to the mismatching char and ecx indicates the - // remaining length. - ok = 0; - } - - return ok; -} - -#define NPERLN 8 - -VOID -Dump( - UCHAR *b, - int len -) - -/*++ -Routine Description: - - Called to do formatted ascii dump to console of the io buffer - -Arguments: - - buffer and length - -Return Value: - - none - ---*/ - -{ - ULONG i; - ULONG longLen = (ULONG)len / sizeof( ULONG ); - PULONG pBuf = (PULONG) b; - - // dump an ordinal ULONG for each sizeof(ULONG)'th byte - wprintf(L"\n****** BEGIN DUMP LEN decimal %d, 0x%x\n", len,len); - for (i=0; i 8){ - wprintf(L"Invalid bar number!\n"); - goto Error; - } - - bar--; // normalize to 0 to 7 - - barGraphState.BarsAsUChar = 1 << (UCHAR)bar; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case CLEAR_ONE_BAR: - - - wprintf(L"Which Bar (input number 1 thru 8)?\n"); - if (scanf_s ("%d", &bar) <= 0) { - - wprintf(L"Error reading input!\n"); - goto Error; - - } - - if(bar == 0 || bar > 8){ - wprintf(L"Invalid bar number!\n"); - goto Error; - } - - bar--; - - // - // Read the current state - // - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &barGraphState, // Ptr to OutBuffer - sizeof(BAR_GRAPH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - if (barGraphState.BarsAsUChar & (1 << bar)) { - - wprintf(L"Bar is set...Clearing it\n"); - barGraphState.BarsAsUChar &= ~(1 << bar); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - - } - - } else { - - wprintf(L"Bar not set.\n"); - - } - - break; - - case LIGHT_ALL_BARS: - - barGraphState.BarsAsUChar = 0xFF; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case CLEAR_ALL_BARS: - - barGraphState.BarsAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, - &barGraphState, // Ptr to InBuffer - sizeof(BAR_GRAPH_STATE), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - - case GET_BAR_GRAPH_LIGHT_STATE: - - barGraphState.BarsAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &barGraphState, // Ptr to OutBuffer - sizeof(BAR_GRAPH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Bar Graph: \n"); - wprintf(L" Bar8 is %s\n", barGraphState.Bar8 ? L"ON" : L"OFF"); - wprintf(L" Bar7 is %s\n", barGraphState.Bar7 ? L"ON" : L"OFF"); - wprintf(L" Bar6 is %s\n", barGraphState.Bar6 ? L"ON" : L"OFF"); - wprintf(L" Bar5 is %s\n", barGraphState.Bar5 ? L"ON" : L"OFF"); - wprintf(L" Bar4 is %s\n", barGraphState.Bar4 ? L"ON" : L"OFF"); - wprintf(L" Bar3 is %s\n", barGraphState.Bar3 ? L"ON" : L"OFF"); - wprintf(L" Bar2 is %s\n", barGraphState.Bar2 ? L"ON" : L"OFF"); - wprintf(L" Bar1 is %s\n", barGraphState.Bar1 ? L"ON" : L"OFF"); - - break; - - case GET_SWITCH_STATE: - - switchState.SwitchesAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_READ_SWITCHES, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &switchState, // Ptr to OutBuffer - sizeof(SWITCH_STATE), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Switches: \n"); - wprintf(L" Switch8 is %s\n", switchState.Switch8 ? L"ON" : L"OFF"); - wprintf(L" Switch7 is %s\n", switchState.Switch7 ? L"ON" : L"OFF"); - wprintf(L" Switch6 is %s\n", switchState.Switch6 ? L"ON" : L"OFF"); - wprintf(L" Switch5 is %s\n", switchState.Switch5 ? L"ON" : L"OFF"); - wprintf(L" Switch4 is %s\n", switchState.Switch4 ? L"ON" : L"OFF"); - wprintf(L" Switch3 is %s\n", switchState.Switch3 ? L"ON" : L"OFF"); - wprintf(L" Switch2 is %s\n", switchState.Switch2 ? L"ON" : L"OFF"); - wprintf(L" Switch1 is %s\n", switchState.Switch1 ? L"ON" : L"OFF"); - - break; - - case GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE: - - switchState.SwitchesAsUChar = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &switchState, // Ptr to OutBuffer - sizeof(switchState), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"Switches: %d\n",index); - wprintf(L" Switch8 is %s\n", switchState.Switch8 ? L"ON" : L"OFF"); - wprintf(L" Switch7 is %s\n", switchState.Switch7 ? L"ON" : L"OFF"); - wprintf(L" Switch6 is %s\n", switchState.Switch6 ? L"ON" : L"OFF"); - wprintf(L" Switch5 is %s\n", switchState.Switch5 ? L"ON" : L"OFF"); - wprintf(L" Switch4 is %s\n", switchState.Switch4 ? L"ON" : L"OFF"); - wprintf(L" Switch3 is %s\n", switchState.Switch3 ? L"ON" : L"OFF"); - wprintf(L" Switch2 is %s\n", switchState.Switch2 ? L"ON" : L"OFF"); - wprintf(L" Switch1 is %s\n", switchState.Switch1 ? L"ON" : L"OFF"); - - break; - - case GET_7_SEGEMENT_STATE: - - sevenSegment = 0; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - &sevenSegment, // Ptr to OutBuffer - sizeof(UCHAR), // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"7 Segment mask: 0x%x\n", sevenSegment); - break; - - case SET_7_SEGEMENT_STATE: - - for (i = 0; i < 8; i++) { - - sevenSegment = 1 << i; - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY, - &sevenSegment, // Ptr to InBuffer - sizeof(UCHAR), // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - 0)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - wprintf(L"This is %d\n", i); - Sleep(500); - - } - - wprintf(L"7 Segment mask: 0x%x\n", sevenSegment); - break; - - case RESET_DEVICE: - - wprintf(L"Reset the device\n"); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_RESET_DEVICE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - NULL)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - break; - - case REENUMERATE_DEVICE: - - wprintf(L"Re-enumerate the device\n"); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_REENUMERATE_DEVICE, - NULL, // Ptr to InBuffer - 0, // Length of InBuffer - NULL, // Ptr to OutBuffer - 0, // Length of OutBuffer - &index, // BytesReturned - NULL)) { // Ptr to Overlapped structure - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - // - // Close the handle to the device and exit out so that - // the driver can unload when the device is surprise-removed - // and reenumerated. - // - default: - - result = TRUE; - goto Error; - - } - - } // end of while loop - -Error: - - CloseHandle(deviceHandle); - return result; - -} - -BOOL -SendFileToDevice( - _In_ PCWSTR FileName - ) -{ - HANDLE deviceHandle; - - struct - { - USHORT delay; - WCHAR buffer[MAX_PATH + 1]; - } playback; - - ULONG bufferCch; - - DWORD code; - BOOL result = FALSE; - - // - // Open a handle to the device. - // - - deviceHandle = OpenDevice(FALSE); - - if (deviceHandle == INVALID_HANDLE_VALUE) { - - wprintf(L"Unable to find any OSR FX2 devices!\n"); - - return FALSE; - - } - - // - // Convert the file name from relative to absolute. - // - - bufferCch = GetFullPathName(FileName, - countof(playback.buffer), - playback.buffer, - NULL); - - if (bufferCch == 0) - { - wprintf(L"Error getting full path name for %s - %d\n", - FileName, - GetLastError()); - goto Error; - } - - if ((G_SendFileInterval * 1000) >= ((USHORT) 0xffff)) - { - wprintf(L"Error - delay is too large. Remember that it's in terms of seconds.\n"); - goto Error; - } - - playback.delay = (USHORT) (G_SendFileInterval * 1000); - - if (!DeviceIoControl(deviceHandle, - IOCTL_OSRUSBFX2_PLAY_FILE, - &playback, - sizeof(playback), - NULL, - 0, - &bufferCch, - 0)) { - - code = GetLastError(); - - wprintf(L"DeviceIoControl failed with error 0x%x\n", code); - - goto Error; - } - - result = TRUE; - -Error: - - CloseHandle(deviceHandle); - return result; -} - -ULONG -AsyncIo( - PVOID ThreadParameter - ) -{ - HANDLE hDevice = INVALID_HANDLE_VALUE; - HANDLE hCompletionPort = NULL; - OVERLAPPED *pOvList = NULL; - PUCHAR buf = NULL; - ULONG_PTR i; - ULONG ioType = (ULONG)(ULONG_PTR)ThreadParameter; - ULONG error; - - hDevice = OpenDevice(FALSE); - - if (hDevice == INVALID_HANDLE_VALUE) { - wprintf(L"Cannot open device %d\n", GetLastError()); - goto Error; - } - - hCompletionPort = CreateIoCompletionPort(hDevice, NULL, 1, 0); - - if (hCompletionPort == NULL) { - wprintf(L"Cannot open completion port %d \n",GetLastError()); - goto Error; - } - - pOvList = (OVERLAPPED *)malloc(NUM_ASYNCH_IO * sizeof(OVERLAPPED)); - - if (pOvList == NULL) { - wprintf(L"Cannot allocate overlapped array \n"); - goto Error; - } - - buf = (PUCHAR)malloc(NUM_ASYNCH_IO * BUFFER_SIZE); - - if (buf == NULL) { - wprintf(L"Cannot allocate buffer \n"); - goto Error; - } - - ZeroMemory(pOvList, NUM_ASYNCH_IO * sizeof(OVERLAPPED)); - ZeroMemory(buf, NUM_ASYNCH_IO * BUFFER_SIZE); - - // - // Issue asynch I/O - // - - for (i = 0; i < NUM_ASYNCH_IO; i++) { - if (ioType == READER_TYPE) { - if ( ReadFile( hDevice, - buf + (i* BUFFER_SIZE), - BUFFER_SIZE, - NULL, - &pOvList[i]) == 0) { - - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L" %Iu th read failed %d \n",i, GetLastError()); - goto Error; - } - } - - } else { - if ( WriteFile( hDevice, - buf + (i* BUFFER_SIZE), - BUFFER_SIZE, - NULL, - &pOvList[i]) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L" %Iu th write failed %d \n",i, GetLastError()); - goto Error; - } - } - } - } - - // - // Wait for the I/Os to complete. If one completes then reissue the I/O - // - - WHILE (1) { - OVERLAPPED *completedOv; - ULONG_PTR key; - ULONG numberOfBytesTransferred; - - if ( GetQueuedCompletionStatus(hCompletionPort, &numberOfBytesTransferred, - &key, &completedOv, INFINITE) == 0) { - wprintf(L"GetQueuedCompletionStatus failed %d\n", GetLastError()); - goto Error; - } - - // - // Read successfully completed. Issue another one. - // - - if (ioType == READER_TYPE) { - - i = completedOv - pOvList; - - wprintf(L"Number of bytes read by request number %Iu is %d\n", - i, numberOfBytesTransferred); - - if ( ReadFile( hDevice, - buf + (i * BUFFER_SIZE), - BUFFER_SIZE, - NULL, - completedOv) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L"%Iu th Read failed %d \n", i, GetLastError()); - goto Error; - } - } - } else { - - i = completedOv - pOvList; - - wprintf(L"Number of bytes written by request number %Iu is %d\n", - i, numberOfBytesTransferred); - - if ( WriteFile( hDevice, - buf + (i * BUFFER_SIZE), - BUFFER_SIZE, - NULL, - completedOv) == 0) { - error = GetLastError(); - if (error != ERROR_IO_PENDING) { - wprintf(L"%Iu th write failed %d \n", i, GetLastError()); - goto Error; - } - } - } - } - -Error: - if (hDevice != INVALID_HANDLE_VALUE) { - CloseHandle(hDevice); - } - - if (hCompletionPort) { - CloseHandle(hCompletionPort); - } - - if (pOvList) { - free(pOvList); - } - if (buf) { - free(buf); - } - - return 1; - -} - - -int -_cdecl -wmain( - _In_ int argc, - _In_reads_(argc) LPWSTR *argv - ) -/*++ -Routine Description: - - Entry point to rwbulk.exe - Parses cmdline, performs user-requested tests - -Arguments: - - argc, argv standard console 'c' app arguments - -Return Value: - - Zero - ---*/ - -{ - PWSTR * pinBuf = NULL; - PWSTR * poutBuf = NULL; - int nBytesRead; - int nBytesWrite; - int ok; - int retValue = 0; - UINT success; - HANDLE hRead = INVALID_HANDLE_VALUE; - HANDLE hWrite = INVALID_HANDLE_VALUE; - ULONG fail = 0L; - ULONG i; - - - Parse(argc, argv ); - - // - // dump USB configuation and pipe info - // - if (G_fDumpUsbConfig) { - DumpUsbConfig(); - } - - if (G_fPlayWithDevice) { - PlayWithDevice(); - goto exit; - } - - if (G_SendFileName != NULL) - { - SendFileToDevice(G_SendFileName); - goto exit; - } - - if (G_fPerformAsyncIo) { - HANDLE th1; - - // - // Create a reader thread - // - th1 = CreateThread( NULL, // Default Security Attrib. - 0, // Initial Stack Size, - AsyncIo, // Thread Func - (LPVOID)READER_TYPE, - 0, // Creation Flags - NULL ); // Don't need the Thread Id. - - if (th1 == NULL) { - wprintf(L"Couldn't create reader thread - error %d\n", GetLastError()); - retValue = 1; - goto exit; - } - - // - // Use this thread for peforming write. - // - AsyncIo((PVOID)WRITER_TYPE); - - goto exit; - } - - // - // doing a read, write, or both test - // - if ((G_fRead) || (G_fWrite)) { - - if (G_fRead) { - if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping - while( G_ReadLen % sizeof( ULONG ) ) { - G_ReadLen++; - } - } - - // - // open the output file - // - hRead = OpenDevice(TRUE); - if(hRead == INVALID_HANDLE_VALUE) { - retValue = 1; - goto exit; - } - - pinBuf = malloc(G_ReadLen); - if (pinBuf == 0) { - retValue = 1; - goto exit; - } - } - - if (G_fWrite) { - if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping - while( G_WriteLen % sizeof( ULONG ) ) { - G_WriteLen++; - } - } - - // - // open the output file - // - hWrite = OpenDevice(TRUE); - if(hWrite == INVALID_HANDLE_VALUE) { - retValue = 1; - goto exit; - } - - poutBuf = malloc(G_WriteLen); - if (poutBuf == 0) { - retValue = 1; - goto exit; - } - } - - for (i = 0; i < G_IterationCount; i++) { - ULONG j; - - if (G_fWrite && poutBuf && hWrite != INVALID_HANDLE_VALUE) { - - PULONG pOut = (PULONG) poutBuf; - ULONG numLongs = G_WriteLen / sizeof( ULONG ); - - // - // put some data in the output buffer - // - for (j=0; j - -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT2_UNKNOWN -#define VER_FILEDESCRIPTION_STR "OSRUSBFX2 Bulk & Isoch Read and Write test App for UMDF" -#define VER_INTERNALNAME_STR "WudfOsrUsbFx2Test.exe" -#define VER_ORIGINALFILENAME_STR "WudfOsrUsbFx2Test.exe" - -#include - - diff --git a/usb/wdf_osrfx2_lab/umdf/inc/WUDFOsrUsbPublic.h b/usb/wdf_osrfx2_lab/umdf/inc/WUDFOsrUsbPublic.h deleted file mode 100644 index 6681fa146..000000000 --- a/usb/wdf_osrfx2_lab/umdf/inc/WUDFOsrUsbPublic.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - WUDFOsrUsbPublic.h - -Abstract: - - This module contains the common declarations shared by driver - and user applications for the UMDF OSR device sample. - - Note that this driver does NOT use the same device interface GUID - as the KMDF OSR USB sample. - -Environment: - - user and kernel - ---*/ - -#pragma once - -// -// Define an Interface Guid so that app can find the device and talk to it. -// - -// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} -DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, - 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); - diff --git a/usb/wdf_osrfx2_lab/umdf/inc/list.h b/usb/wdf_osrfx2_lab/umdf/inc/list.h deleted file mode 100644 index 38d0b1e90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/inc/list.h +++ /dev/null @@ -1,77 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - list.h - -Abstract: - - This module contains doubly linked list macros - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -FORCEINLINE -VOID -InitializeListHead( - IN PLIST_ENTRY ListHead - ) -{ - ListHead->Flink = ListHead->Blink = ListHead; -} - -FORCEINLINE -BOOLEAN -RemoveEntryList( - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - PLIST_ENTRY Flink; - - Flink = Entry->Flink; - Blink = Entry->Blink; - Blink->Flink = Flink; - Flink->Blink = Blink; - return (BOOLEAN)(Flink == Blink); -} - -FORCEINLINE -VOID -InsertHeadList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Flink; - - Flink = ListHead->Flink; - Entry->Flink = Flink; - Entry->Blink = ListHead; - Flink->Blink = Entry; - ListHead->Flink = Entry; -} - -FORCEINLINE -VOID -InsertTailList( - IN PLIST_ENTRY ListHead, - IN PLIST_ENTRY Entry - ) -{ - PLIST_ENTRY Blink; - - Blink = ListHead->Blink; - Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; - ListHead->Blink = Entry; -} diff --git a/usb/wdf_osrfx2_lab/umdf/inc/public.h b/usb/wdf_osrfx2_lab/umdf/inc/public.h deleted file mode 100644 index 2c3f6805c..000000000 --- a/usb/wdf_osrfx2_lab/umdf/inc/public.h +++ /dev/null @@ -1,217 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - public.h - -Abstract: - - Public definitions for the OSR_FX2 device operations. - -Environment: - - User & Kernel mode - ---*/ - -#ifndef _PUBLIC_H -#define _PUBLIC_H - -#include - -#include "WudfOsrUsbPublic.h" - - -// -// Define the structures that will be used by the IOCTL -// interface to the driver -// - -// -// BAR_GRAPH_STATE -// -// BAR_GRAPH_STATE is a bit field structure with each -// bit corresponding to one of the bar graph on the -// OSRFX2 Development Board -// -#include - -#pragma warning( push ) -#pragma warning( disable : 4201 ) // nameless struct/union -#pragma warning( disable : 4214 ) // bit-field type other than int - -typedef struct _BAR_GRAPH_STATE { - - union { - - struct { - // - // Individual bars starting from the - // top of the stack of bars - // - // NOTE: There are actually 10 bars, - // but the very top two do not light - // and are not counted here - // - UCHAR Bar1 : 1; - UCHAR Bar2 : 1; - UCHAR Bar3 : 1; - UCHAR Bar4 : 1; - UCHAR Bar5 : 1; - UCHAR Bar6 : 1; - UCHAR Bar7 : 1; - UCHAR Bar8 : 1; - }; - - // - // The state of all the bar graph as a single - // UCHAR - // - UCHAR BarsAsUChar; - - }; - -}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; - -// -// SWITCH_STATE -// -// SWITCH_STATE is a bit field structure with each -// bit corresponding to one of the switches on the -// OSRFX2 Development Board -// -typedef struct _SWITCH_STATE { - - union { - struct { - // - // Individual switches starting from the - // left of the set of switches - // - UCHAR Switch1 : 1; - UCHAR Switch2 : 1; - UCHAR Switch3 : 1; - UCHAR Switch4 : 1; - UCHAR Switch5 : 1; - UCHAR Switch6 : 1; - UCHAR Switch7 : 1; - UCHAR Switch8 : 1; - }; - - // - // The state of all the switches as a single - // UCHAR - // - UCHAR SwitchesAsUChar; - - }; - - -}SWITCH_STATE, *PSWITCH_STATE; - -// -// Seven segment display bit values. -// - -// -// Undefine conflicting MFC constant -// -#undef SS_CENTER -#undef SS_LEFT -#undef SS_RIGHT - -#define SS_TOP 0x01 -#define SS_TOP_LEFT 0x40 -#define SS_TOP_RIGHT 0x02 -#define SS_CENTER 0x20 -#define SS_BOTTOM_LEFT 0x10 -#define SS_BOTTOM_RIGHT 0x04 -#define SS_BOTTOM 0x80 -#define SS_DOT 0x08 - -// -// FILE_PLAYBACK -// -// FILE_PLAYBACK structure contains the parameters for the PLAY_FILE I/O Control. -// - -typedef struct _FILE_PLAYBACK -{ - // - // The delay between changes in the display, in milliseconds. - // - - USHORT Delay; - - // - // The data file path. - // - - WCHAR Path[1]; -} FILE_PLAYBACK, *PFILE_PLAYBACK; - -#include - -#define IOCTL_INDEX 0x800 -#define FILE_DEVICE_OSRUSBFX2 65500U - -#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 1, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 3, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 4, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 5, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - - -#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 6, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 7, \ - METHOD_BUFFERED, \ - FILE_READ_ACCESS) - - -#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 8, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ - IOCTL_INDEX + 9, \ - METHOD_OUT_DIRECT, \ - FILE_READ_ACCESS) - -#define IOCTL_OSRUSBFX2_PLAY_FILE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ - IOCTL_INDEX + 10, \ - METHOD_BUFFERED, \ - FILE_WRITE_ACCESS) - -#pragma warning(pop) - -#endif - diff --git a/usb/wdf_osrfx2_lab/umdf/inc/usb_hw.h b/usb/wdf_osrfx2_lab/umdf/inc/usb_hw.h deleted file mode 100644 index d6e983f1a..000000000 --- a/usb/wdf_osrfx2_lab/umdf/inc/usb_hw.h +++ /dev/null @@ -1,233 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation. All rights reserved. - -Module Name: - - Usb.h - -Abstract: - - Contains prototypes for interfacing with a USB connected device. These - are copied from the KMDF WDFUSB.H header file (but with the WDF specific - portions removed) - -Environment: - - kernel mode only - ---*/ - -#pragma once - -typedef enum _WINUSB_BMREQUEST_DIRECTION { - BmRequestHostToDevice = BMREQUEST_HOST_TO_DEVICE, - BmRequestDeviceToHost = BMREQUEST_DEVICE_TO_HOST, -} WINUSB_BMREQUEST_DIRECTION; - -typedef enum _WINUSB_BMREQUEST_TYPE { - BmRequestStandard = BMREQUEST_STANDARD, - BmRequestClass = BMREQUEST_CLASS, - BmRequestVendor = BMREQUEST_VENDOR, -} WINUSB_BMREQUEST_TYPE; - -typedef enum _WINUSB_BMREQUEST_RECIPIENT { - BmRequestToDevice = BMREQUEST_TO_DEVICE, - BmRequestToInterface = BMREQUEST_TO_INTERFACE, - BmRequestToEndpoint = BMREQUEST_TO_ENDPOINT, - BmRequestToOther = BMREQUEST_TO_OTHER, -} WINUSB_BMREQUEST_RECIPIENT; - -typedef enum _WINUSB_DEVICE_TRAITS { - WINUSB_DEVICE_TRAIT_SELF_POWERED = 0x00000001, - WINUSB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE = 0x00000002, - WINUSB_DEVICE_TRAIT_AT_HIGH_SPEED = 0x00000004, -} WINUSB_DEVICE_TRAITS; - -typedef enum _WdfUsbTargetDeviceSelectInterfaceType { - WdfUsbTargetDeviceSelectInterfaceTypeInterface = 0x10, - WdfUsbTargetDeviceSelectInterfaceTypeUrb = 0x11, -} WdfUsbTargetDeviceSelectInterfaceType; - - - -typedef union _WINUSB_CONTROL_SETUP_PACKET { - struct { - union { - #pragma warning(disable:4214) // bit field types other than int - struct { - // - // Valid values are BMREQUEST_TO_DEVICE, BMREQUEST_TO_INTERFACE, - // BMREQUEST_TO_ENDPOINT, BMREQUEST_TO_OTHER - // - BYTE Recipient:2; - - BYTE Reserved:3; - - // - // Valid values are BMREQUEST_STANDARD, BMREQUEST_CLASS, - // BMREQUEST_VENDOR - // - BYTE Type:2; - - // - // Valid values are BMREQUEST_HOST_TO_DEVICE, - // BMREQUEST_DEVICE_TO_HOST - // - BYTE Dir:1; - } Request; - #pragma warning(default:4214) // bit field types other than int - BYTE Byte; - } bm; - - BYTE bRequest; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wValue; - - union { - struct { - BYTE LowByte; - BYTE HiByte; - } Bytes; - USHORT Value; - } wIndex; - - USHORT wLength; - } Packet; - - struct { - BYTE Bytes[8]; - } Generic; - - WINUSB_SETUP_PACKET WinUsb; - -} WINUSB_CONTROL_SETUP_PACKET, *PWINUSB_CONTROL_SETUP_PACKET; - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_CLASS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestClass; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_VENDOR( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_DIRECTION Direction, - WINUSB_BMREQUEST_RECIPIENT Recipient, - BYTE Request, - USHORT Value, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) Direction; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestVendor; - Packet->Packet.bm.Request.Recipient = (BYTE) Recipient; - - Packet->Packet.bRequest = Request; - Packet->Packet.wValue.Value = Value; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_FEATURE( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT FeatureSelector, - USHORT Index, - BOOLEAN SetFeature - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestHostToDevice; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - if (SetFeature) { - Packet->Packet.bRequest = USB_REQUEST_SET_FEATURE; - } - else { - Packet->Packet.bRequest = USB_REQUEST_CLEAR_FEATURE; - } - - Packet->Packet.wValue.Value = FeatureSelector; - Packet->Packet.wIndex.Value = Index; - - // Packet->Packet.wLength will be set by the formatting function -} - -VOID -FORCEINLINE -WINUSB_CONTROL_SETUP_PACKET_INIT_GET_STATUS( - PWINUSB_CONTROL_SETUP_PACKET Packet, - WINUSB_BMREQUEST_RECIPIENT BmRequestRecipient, - USHORT Index - ) -{ - RtlZeroMemory(Packet, sizeof(WINUSB_CONTROL_SETUP_PACKET)); - - Packet->Packet.bm.Request.Dir = (BYTE) BmRequestDeviceToHost; - Packet->Packet.bm.Request.Type = (BYTE) BmRequestStandard; - Packet->Packet.bm.Request.Recipient = (BYTE) BmRequestRecipient; - - Packet->Packet.bRequest = USB_REQUEST_GET_STATUS; - Packet->Packet.wIndex.Value = Index; - Packet->Packet.wValue.Value = 0; - - // Packet->Packet.wLength will be set by the formatting function -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step1/Device.cpp b/usb/wdf_osrfx2_lab/umdf/step1/Device.cpp deleted file mode 100644 index 68c1245ce..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/Device.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton sample driver's - device callback object. - - The skeleton sample device does very little. It does not implement either - of the PNP interfaces so once the device is setup, it won't ever get any - callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" - -#include "device.tmh" - - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the skeleton driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the skeleton driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the skeleton is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - return CUnknown::QueryInterface(InterfaceId, Object); -} diff --git a/usb/wdf_osrfx2_lab/umdf/step1/Device.h b/usb/wdf_osrfx2_lab/umdf/step1/Device.h deleted file mode 100644 index 24954a6b1..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/Device.h +++ /dev/null @@ -1,128 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -// -// Class for the iotrace driver. -// - -class CMyDevice : - public CUnknown -{ - -// -// Private data members. -// -private: - // - // Weak reference to framework device - // - - IWDFDevice *m_FxDevice; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL) - { - } - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step1/Driver.cpp b/usb/wdf_osrfx2_lab/umdf/step1/Driver.cpp deleted file mode 100644 index bac5caca9..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step1/Driver.h b/usb/wdf_osrfx2_lab/umdf/step1/Driver.h deleted file mode 100644 index 800ab1d9a..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the skeleton sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.ctl b/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.rc b/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.inx b/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.inx deleted file mode 100644 index 4a4398245..000000000 Binary files a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.inx and /dev/null differ diff --git a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj b/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj deleted file mode 100644 index 676fbe6e7..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj +++ /dev/null @@ -1,279 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {94BDC8D1-B62F-4200-9873-D403B6D30301} - $(MSBuildProjectName) - 1 - 1 - Debug - Win32 - {A2C76CA1-1B47-420E-9768-93D69A3266B6} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2_1 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_1 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_1 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_1 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj.Filters b/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj.Filters deleted file mode 100644 index 6b21dc4a0..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/WUDFOsrUsbFx2_1.vcxproj.Filters +++ /dev/null @@ -1,43 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {83D4660B-A09F-4A40-A1FD-237876304103} - - - h;hpp;hxx;hm;inl;inc;xsd - {3C16D1C8-B1DE-467D-9DF0-AE732A9B8915} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {E23C96E3-DE9A-457A-A1D4-DA476B16AD08} - - - inf;inv;inx;mof;mc; - {C71DC5A8-0692-4670-A5B8-B6706FA885E7} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step1/comsup.cpp b/usb/wdf_osrfx2_lab/umdf/step1/comsup.cpp deleted file mode 100644 index 9c9aec3b5..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step1/comsup.h b/usb/wdf_osrfx2_lab/umdf/step1/comsup.h deleted file mode 100644 index dedf78c84..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step1/dllsup.cpp b/usb/wdf_osrfx2_lab/umdf/step1/dllsup.cpp deleted file mode 100644 index bd681ac22..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the skeleton sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - skeleton driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step1/exports.def b/usb/wdf_osrfx2_lab/umdf/step1/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/wdf_osrfx2_lab/umdf/step1/internal.h b/usb/wdf_osrfx2_lab/umdf/step1/internal.h deleted file mode 100644 index 374931e05..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step1/internal.h +++ /dev/null @@ -1,150 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Skeleton - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/wdf_osrfx2_lab/umdf/step2/Device.cpp b/usb/wdf_osrfx2_lab/umdf/step2/Device.cpp deleted file mode 100644 index 433309ca6..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/Device.cpp +++ /dev/null @@ -1,483 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton sample driver's - device callback object. - - The skeleton sample device does very little. It does not implement either - of the PNP interfaces so once the device is setup, it won't ever get any - callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" - -#include "device.tmh" - -CMyDevice::~CMyDevice( - ) -{ -} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the skeleton driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_OSRUSBFX2, - NULL); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the skeleton driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the skeleton is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackHardware))) - { - *Object = QueryIPnpCallbackHardware(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnPrepareHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked to ready the driver - to talk to hardware. It opens the handle to the - device and talks to it using the WINUSB interface. - It invokes WINUSB to discver the interfaces and stores - the information related to bulk endpoints. - -Arguments: - - FxDevice : Pointer to the WDF device interface - -Return Value: - - HRESULT - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - // - // Get the device name. - // Get the length to allocate first - // - - hr = m_FxDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Device name %S", - deviceName - ); - } - - // - // Create USB I/O Targets and configure them - // - - if (SUCCEEDED(hr)) - { - hr = CreateUsbIoTargets(); - } - - if (SUCCEEDED(hr)) - { - ULONG length = sizeof(m_Speed); - - hr = m_pIUsbTargetDevice->RetrieveDeviceInformation(DEVICE_SPEED, - &length, - &m_Speed); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb device speed information %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Speed - %x\n", - m_Speed - ); - } - - delete[] deviceName; - - return hr; -} - -HRESULT -CMyDevice::OnReleaseHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. - -Arguments: - - FxDevice - Pointer to the Device object. - -Return Value: - - HRESULT - Always succeeds. - ---*/ -{ - // - // Remove I/O target from object tree before any potential subsequent - // OnPrepareHardware creates a new one - // - - if (m_pIUsbTargetDevice) - { - m_pIUsbTargetDevice->DeleteWdfObject(); - } - - return S_OK; -} - -HRESULT -CMyDevice::CreateUsbIoTargets( - ) -/*++ - -Routine Description: - - This routine creates Usb device, interface and pipe objects - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr; - IWDFUsbTargetFactory * pIUsbTargetFactory = NULL; - IWDFUsbTargetDevice * pIUsbTargetDevice = NULL; - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pIUsbTargetFactory)); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb target factory %!HRESULT!", - hr - ); - } - - if (SUCCEEDED(hr)) - { - hr = pIUsbTargetFactory->CreateUsbTargetDevice( - &pIUsbTargetDevice); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to create USB Device I/O Target %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - m_pIUsbTargetDevice = pIUsbTargetDevice; - - // - // Release the creation reference as object tree will maintain a reference - // - - pIUsbTargetDevice->Release(); - } - - SAFE_RELEASE(pIUsbTargetFactory); - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step2/Device.h b/usb/wdf_osrfx2_lab/umdf/step2/Device.h deleted file mode 100644 index dadbfd5b5..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/Device.h +++ /dev/null @@ -1,180 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -// -// Class for the iotrace driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackHardware -{ - -// -// Private data members. -// -private: - // - // Weak reference to framework device - // - IWDFDevice *m_FxDevice; - - // - // USB Device I/O Target - // - IWDFUsbTargetDevice * m_pIUsbTargetDevice; - - - // - // Device Speed (Low, Full, High) - // - UCHAR m_Speed; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_pIUsbTargetDevice(NULL), - m_Speed(0) - { - } - - ~CMyDevice( - ); - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - // - // Helper methods - // - - HRESULT - CreateUsbIoTargets( - VOID - ); - - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - - IPnpCallbackHardware * - QueryIPnpCallbackHardware( - VOID - ) - { - AddRef(); - return static_cast(this); - } - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IPnpCallbackHardware - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnPrepareHardware( - _In_ IWDFDevice *FxDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnReleaseHardware( - _In_ IWDFDevice *FxDevice - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step2/Driver.cpp b/usb/wdf_osrfx2_lab/umdf/step2/Driver.cpp deleted file mode 100644 index bac5caca9..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step2/Driver.h b/usb/wdf_osrfx2_lab/umdf/step2/Driver.h deleted file mode 100644 index 800ab1d9a..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the skeleton sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.ctl b/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.rc b/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.inx b/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.inx deleted file mode 100644 index 2e6a18f80..000000000 Binary files a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.inx and /dev/null differ diff --git a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj b/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj deleted file mode 100644 index c73716b9c..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj +++ /dev/null @@ -1,279 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {808B6774-93FA-4ABF-A23F-35C55FA80B80} - $(MSBuildProjectName) - 1 - 1 - Debug - Win32 - {A944547C-61E9-47C5-82EC-797D95019735} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2_2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_2 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_2 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj.Filters b/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj.Filters deleted file mode 100644 index 228729fe9..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/WUDFOsrUsbFx2_2.vcxproj.Filters +++ /dev/null @@ -1,43 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {CAFDA06D-52D2-4C5B-B355-1D19E80B1C72} - - - h;hpp;hxx;hm;inl;inc;xsd - {2C5F0467-9539-41AD-95E0-0BD835F2F9EE} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {310FFCBB-E46B-43FA-B790-61A981127DBF} - - - inf;inv;inx;mof;mc; - {04E87A31-118A-4F72-8349-D26123A6EE71} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step2/comsup.cpp b/usb/wdf_osrfx2_lab/umdf/step2/comsup.cpp deleted file mode 100644 index 9c9aec3b5..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step2/comsup.h b/usb/wdf_osrfx2_lab/umdf/step2/comsup.h deleted file mode 100644 index dedf78c84..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step2/dllsup.cpp b/usb/wdf_osrfx2_lab/umdf/step2/dllsup.cpp deleted file mode 100644 index bd681ac22..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the skeleton sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - skeleton driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step2/exports.def b/usb/wdf_osrfx2_lab/umdf/step2/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/wdf_osrfx2_lab/umdf/step2/internal.h b/usb/wdf_osrfx2_lab/umdf/step2/internal.h deleted file mode 100644 index 374931e05..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step2/internal.h +++ /dev/null @@ -1,150 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Skeleton - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.cpp b/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.cpp deleted file mode 100644 index 48de237d2..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "winioctl.h" - -#include "ControlQueue.tmh" - -CMyControlQueue::CMyControlQueue( - _In_ PCMyDevice Device - ) : CMyQueue(Device) -{ - -} - -HRESULT -STDMETHODCALLTYPE -CMyControlQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDeviceIoControl(); - - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyControlQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyControlQueue queue = NULL; - HRESULT hr = S_OK; - - queue = new CMyControlQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyControlQueue::Initialize( - VOID - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - hr = __super::Initialize(WdfIoQueueDispatchSequential, - false, - true); - - // - // return the status. - // - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyControlQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *FxQueue, - _In_ IWDFIoRequest *FxRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Aruments: - - FxQueue - Framework Queue instance - FxRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Lenth of input buffer - OutputBufferSizeInBytes - Lenth of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - UNREFERENCED_PARAMETER(OutputBufferSizeInBytes); - - IWDFMemory *memory = NULL; - PVOID buffer; - - SIZE_T bigBufferCb; - - ULONG information = 0; - - bool completeRequest = true; - - HRESULT hr = S_OK; - - switch (ControlCode) - { - case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - break; - } - - default: - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION); - break; - } - } - - if (completeRequest) - { - FxRequest->CompleteWithInformation(hr, information); - } - - return; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.h b/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.h deleted file mode 100644 index 251521e1b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/ControlQueue.h +++ /dev/null @@ -1,101 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.h - -Abstract: - - This file defines the queue callback object for handling device I/O - control requests. This is a serialized queue. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyControlQueue : public IQueueCallbackDeviceIoControl, - public CMyQueue -{ - HRESULT - Initialize( - VOID - ); - -public: - - CMyControlQueue( - _In_ PCMyDevice Device - ); - - virtual - ~CMyControlQueue( - VOID - ) - { - return; - } - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // - // IQueueCallbackDeviceIoControl - // - STDMETHOD_ (void, OnDeviceIoControl)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); -}; - diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Device.cpp b/usb/wdf_osrfx2_lab/umdf/step3/Device.cpp deleted file mode 100644 index 20c997c5d..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Device.cpp +++ /dev/null @@ -1,644 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton sample driver's - device callback object. - - The skeleton sample device does very little. It does not implement either - of the PNP interfaces so once the device is setup, it won't ever get any - callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" - -#include "device.tmh" - -CMyDevice::~CMyDevice( - ) -{ -} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the skeleton driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - - // - // Create the control queue and configure forwarding for IOCTL requests. - // - - if (SUCCEEDED(hr)) - { - hr = CMyControlQueue::CreateInstance(this, &m_ControlQueue); - - if (SUCCEEDED(hr)) - { - hr = m_ControlQueue->Configure(); - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->ConfigureRequestDispatching( - m_ControlQueue->GetFxQueue(), - WdfRequestDeviceIoControl, - true - ); - } - m_ControlQueue->Release(); - } - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_OSRUSBFX2, - NULL); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the skeleton driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the skeleton is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackHardware))) - { - *Object = QueryIPnpCallbackHardware(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnPrepareHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked to ready the driver - to talk to hardware. It opens the handle to the - device and talks to it using the WINUSB interface. - It invokes WINUSB to discver the interfaces and stores - the information related to bulk endpoints. - -Arguments: - - FxDevice : Pointer to the WDF device interface - -Return Value: - - HRESULT - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - // - // Get the device name. - // Get the length to allocate first - // - - hr = m_FxDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Device name %S", - deviceName - ); - } - - // - // Create USB I/O Targets and configure them - // - - if (SUCCEEDED(hr)) - { - hr = CreateUsbIoTargets(); - } - - if (SUCCEEDED(hr)) - { - ULONG length = sizeof(m_Speed); - - hr = m_pIUsbTargetDevice->RetrieveDeviceInformation(DEVICE_SPEED, - &length, - &m_Speed); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb device speed information %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Speed - %x\n", - m_Speed - ); - } - - delete[] deviceName; - - return hr; -} - -HRESULT -CMyDevice::OnReleaseHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. - -Arguments: - - FxDevice - Pointer to the Device object. - -Return Value: - - HRESULT - Always succeeds. - ---*/ -{ - // - // Remove I/O target from object tree before any potential subsequent - // OnPrepareHardware creates a new one - // - - if (m_pIUsbTargetDevice) - { - m_pIUsbTargetDevice->DeleteWdfObject(); - } - - return S_OK; -} - -HRESULT -CMyDevice::CreateUsbIoTargets( - ) -/*++ - -Routine Description: - - This routine creates Usb device, interface and pipe objects - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr; - IWDFUsbTargetFactory * pIUsbTargetFactory = NULL; - IWDFUsbTargetDevice * pIUsbTargetDevice = NULL; - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pIUsbTargetFactory)); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb target factory %!HRESULT!", - hr - ); - } - - if (SUCCEEDED(hr)) - { - hr = pIUsbTargetFactory->CreateUsbTargetDevice( - &pIUsbTargetDevice); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to create USB Device I/O Target %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - m_pIUsbTargetDevice = pIUsbTargetDevice; - - // - // Release the creation reference as object tree will maintain a reference - // - - pIUsbTargetDevice->Release(); - } - - SAFE_RELEASE(pIUsbTargetFactory); - - return hr; -} - -HRESULT -CMyDevice::SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesTransferred - ); - - - return hr; -} - -HRESULT -CMyDevice::SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ) -{ - HRESULT hr = S_OK; - HRESULT hrRequest = S_OK; - IWDFIoRequest *pWdfRequest = NULL; - IWDFDriver * FxDriver = NULL; - IWDFMemory * FxMemory = NULL; - IWDFRequestCompletionParams * FxComplParams = NULL; - IWDFUsbRequestCompletionParams * FxUsbComplParams = NULL; - - *LengthTransferred = 0; - - hr = m_FxDevice->CreateRequest( NULL, //pCallbackInterface - NULL, //pParentObject - &pWdfRequest); - hrRequest = hr; - - if (SUCCEEDED(hr)) - { - m_FxDevice->GetDriver(&FxDriver); - - hr = FxDriver->CreatePreallocatedWdfMemory( Buffer, - BufferLength, - NULL, //pCallbackInterface - pWdfRequest, //pParetObject - &FxMemory ); - } - - if (SUCCEEDED(hr)) - { - hr = m_pIUsbTargetDevice->FormatRequestForControlTransfer( pWdfRequest, - SetupPacket, - FxMemory, - NULL); //TransferOffset - } - - if (SUCCEEDED(hr)) - { - hr = pWdfRequest->Send( m_pIUsbTargetDevice, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - 0); //Timeout - } - - if (SUCCEEDED(hr)) - { - pWdfRequest->GetCompletionParams(&FxComplParams); - - hr = FxComplParams->GetCompletionStatus(); - } - - if (SUCCEEDED(hr)) - { - HRESULT hrQI = FxComplParams->QueryInterface(IID_PPV_ARGS(&FxUsbComplParams)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - WUDF_TEST_DRIVER_ASSERT( WdfUsbRequestTypeDeviceControlTransfer == - FxUsbComplParams->GetCompletedUsbRequestType() ); - - FxUsbComplParams->GetDeviceControlTransferParameters( NULL, - LengthTransferred, - NULL, - NULL ); - } - - SAFE_RELEASE(FxUsbComplParams); - SAFE_RELEASE(FxComplParams); - SAFE_RELEASE(FxMemory); - - if (SUCCEEDED(hrRequest)) - { - pWdfRequest->DeleteWdfObject(); - } - SAFE_RELEASE(pWdfRequest); - - SAFE_RELEASE(FxDriver); - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Device.h b/usb/wdf_osrfx2_lab/umdf/step3/Device.h deleted file mode 100644 index 6d3435827..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Device.h +++ /dev/null @@ -1,203 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -// -// Define the vendor commands supported by our device -// -#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 - -// -// Class for the iotrace driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackHardware -{ - -// -// Private data members. -// -private: - // - // Weak reference to framework device - // - IWDFDevice *m_FxDevice; - - // - // Weak reference to the control queue - // - PCMyControlQueue m_ControlQueue; - - // - // USB Device I/O Target - // - IWDFUsbTargetDevice * m_pIUsbTargetDevice; - - - // - // Device Speed (Low, Full, High) - // - UCHAR m_Speed; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_ControlQueue(NULL), - m_pIUsbTargetDevice(NULL), - m_Speed(0) - { - } - - ~CMyDevice( - ); - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - // - // Helper methods - // - - HRESULT - CreateUsbIoTargets( - VOID - ); - - HRESULT - SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - - IPnpCallbackHardware * - QueryIPnpCallbackHardware( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IPnpCallbackHardware - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnPrepareHardware( - _In_ IWDFDevice *FxDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnReleaseHardware( - _In_ IWDFDevice *FxDevice - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Driver.cpp b/usb/wdf_osrfx2_lab/umdf/step3/Driver.cpp deleted file mode 100644 index bac5caca9..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Driver.h b/usb/wdf_osrfx2_lab/umdf/step3/Driver.h deleted file mode 100644 index 800ab1d9a..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the skeleton sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.ctl b/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.rc b/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Queue.cpp b/usb/wdf_osrfx2_lab/umdf/step3/Queue.cpp deleted file mode 100644 index c56b38bbc..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Queue.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.tmh" - -CMyQueue::CMyQueue( - _In_ PCMyDevice Device - ) : - m_FxQueue(NULL), - m_Device(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - hr = CUnknown::QueryInterface(InterfaceId, Object); - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ) -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the I/O Queue object. - // - - { - IUnknown *callback = QueryIUnknown(); - - hr = m_Device->GetFxDevice()->CreateIoQueue( - callback, - Default, - DispatchType, - PowerManaged, - FALSE, - &fxQueue - ); - callback->Release(); - } - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // Release the creation reference on the queue. This object will be - // destroyed before the queue so we don't need to have a reference out - // on it. - // - - fxQueue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::Configure( - VOID - ) -{ - return S_OK; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/Queue.h b/usb/wdf_osrfx2_lab/umdf/step3/Queue.h deleted file mode 100644 index 5659224bb..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/Queue.h +++ /dev/null @@ -1,93 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyQueue : - public CUnknown -{ -protected: - // - // Unreferenced pointer to the partner Fx device. - // - - IWDFIoQueue *m_FxQueue; - - // - // Unreferenced pointer to the parent device. - // - - PCMyDevice m_Device; - - HRESULT - Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ); - -protected: - - CMyQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyQueue(); - - HRESULT - Configure( - VOID - ); - -public: - - IWDFIoQueue * - GetFxQueue( - VOID - ) - { - return m_FxQueue; - } - - - PCMyDevice - GetDevice( - VOID - ) - { - return m_Device; - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.inx b/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.inx deleted file mode 100644 index 1430ec458..000000000 Binary files a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.inx and /dev/null differ diff --git a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj b/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj deleted file mode 100644 index 1bccba8b6..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj +++ /dev/null @@ -1,279 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {4BED411D-1B55-4A64-84C9-36EC25F083D2} - $(MSBuildProjectName) - 1 - 1 - Debug - Win32 - {9EBE799A-093D-4C8A-9CDC-63244A61D166} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2_3 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_3 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_3 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_3 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj.Filters b/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj.Filters deleted file mode 100644 index 1007a3534..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/WUDFOsrUsbFx2_3.vcxproj.Filters +++ /dev/null @@ -1,49 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {275FF43B-A34B-4413-A946-DB6C89B85700} - - - h;hpp;hxx;hm;inl;inc;xsd - {3E57B132-7C76-4977-9406-304A1D0E3E93} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {9A62ABB9-1665-44C3-A018-B30C085A8EC5} - - - inf;inv;inx;mof;mc; - {6FE8DFE2-D3E3-4713-9FD8-A937B598C72C} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step3/comsup.cpp b/usb/wdf_osrfx2_lab/umdf/step3/comsup.cpp deleted file mode 100644 index 9c9aec3b5..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step3/comsup.h b/usb/wdf_osrfx2_lab/umdf/step3/comsup.h deleted file mode 100644 index dedf78c84..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step3/dllsup.cpp b/usb/wdf_osrfx2_lab/umdf/step3/dllsup.cpp deleted file mode 100644 index bd681ac22..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the skeleton sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - skeleton driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step3/exports.def b/usb/wdf_osrfx2_lab/umdf/step3/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/wdf_osrfx2_lab/umdf/step3/internal.h b/usb/wdf_osrfx2_lab/umdf/step3/internal.h deleted file mode 100644 index 7db8f1c42..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step3/internal.h +++ /dev/null @@ -1,152 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Skeleton - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" -#include "ControlQueue.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.cpp b/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.cpp deleted file mode 100644 index 48de237d2..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "winioctl.h" - -#include "ControlQueue.tmh" - -CMyControlQueue::CMyControlQueue( - _In_ PCMyDevice Device - ) : CMyQueue(Device) -{ - -} - -HRESULT -STDMETHODCALLTYPE -CMyControlQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackDeviceIoControl))) - { - hr = S_OK; - *Object = QueryIQueueCallbackDeviceIoControl(); - - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyControlQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyControlQueue queue = NULL; - HRESULT hr = S_OK; - - queue = new CMyControlQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyControlQueue::Initialize( - VOID - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - hr = __super::Initialize(WdfIoQueueDispatchSequential, - false, - true); - - // - // return the status. - // - - return hr; -} - -VOID -STDMETHODCALLTYPE -CMyControlQueue::OnDeviceIoControl( - _In_ IWDFIoQueue *FxQueue, - _In_ IWDFIoRequest *FxRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ) -/*++ - -Routine Description: - - - DeviceIoControl dispatch routine - -Aruments: - - FxQueue - Framework Queue instance - FxRequest - Framework Request instance - ControlCode - IO Control Code - InputBufferSizeInBytes - Lenth of input buffer - OutputBufferSizeInBytes - Lenth of output buffer - - Always succeeds DeviceIoIoctl -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(FxQueue); - UNREFERENCED_PARAMETER(OutputBufferSizeInBytes); - - IWDFMemory *memory = NULL; - PVOID buffer; - - SIZE_T bigBufferCb; - - ULONG information = 0; - - bool completeRequest = true; - - HRESULT hr = S_OK; - - switch (ControlCode) - { - case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: - { - // - // Make sure the buffer is big enough to hold the input for the - // control transfer. - // - - if (InputBufferSizeInBytes < sizeof(BAR_GRAPH_STATE)) - { - hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - } - else - { - FxRequest->GetInputMemory(&memory); - } - - // - // Get the data buffer and use it to set the bar graph on the - // device. - // - - if (SUCCEEDED(hr)) - { - buffer = memory->GetDataBuffer(&bigBufferCb); - memory->Release(); - - hr = m_Device->SetBarGraphDisplay((PBAR_GRAPH_STATE) buffer); - } - - break; - } - - default: - { - hr = HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION); - break; - } - } - - if (completeRequest) - { - FxRequest->CompleteWithInformation(hr, information); - } - - return; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.h b/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.h deleted file mode 100644 index 251521e1b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/ControlQueue.h +++ /dev/null @@ -1,101 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - ControlQueue.h - -Abstract: - - This file defines the queue callback object for handling device I/O - control requests. This is a serialized queue. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyControlQueue : public IQueueCallbackDeviceIoControl, - public CMyQueue -{ - HRESULT - Initialize( - VOID - ); - -public: - - CMyControlQueue( - _In_ PCMyDevice Device - ); - - virtual - ~CMyControlQueue( - VOID - ) - { - return; - } - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyControlQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return S_OK; - } - - IQueueCallbackDeviceIoControl * - QueryIQueueCallbackDeviceIoControl( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - // - // Wdf Callbacks - // - - // - // IQueueCallbackDeviceIoControl - // - STDMETHOD_ (void, OnDeviceIoControl)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ ULONG ControlCode, - _In_ SIZE_T InputBufferSizeInBytes, - _In_ SIZE_T OutputBufferSizeInBytes - ); -}; - diff --git a/usb/wdf_osrfx2_lab/umdf/step4/Device.cpp b/usb/wdf_osrfx2_lab/umdf/step4/Device.cpp deleted file mode 100644 index bc6700c5c..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/Device.cpp +++ /dev/null @@ -1,812 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Device.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton sample driver's - device callback object. - - The skeleton sample device does very little. It does not implement either - of the PNP interfaces so once the device is setup, it won't ever get any - callbacks until the device is removed. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "initguid.h" -#include "usb_hw.h" - -#include "device.tmh" - -CMyDevice::~CMyDevice( - ) -{ -} - -HRESULT -CMyDevice::CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit, - _Out_ PCMyDevice *Device - ) -/*++ - - Routine Description: - - This method creates and initializs an instance of the skeleton driver's - device callback object. - - Arguments: - - FxDeviceInit - the settings for the device. - - Device - a location to store the referenced pointer to the device object. - - Return Value: - - Status - ---*/ -{ - PCMyDevice device; - HRESULT hr; - - // - // Allocate a new instance of the device class. - // - - device = new CMyDevice(); - - if (NULL == device) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the instance. - // - - hr = device->Initialize(FxDriver, FxDeviceInit); - - if (SUCCEEDED(hr)) - { - *Device = device; - } - else - { - device->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Initialize( - _In_ IWDFDriver * FxDriver, - _In_ IWDFDeviceInitialize * FxDeviceInit - ) -/*++ - - Routine Description: - - This method initializes the device callback object and creates the - partner device object. - - The method should perform any device-specific configuration that: - * could fail (these can't be done in the constructor) - * must be done before the partner object is created -or- - * can be done after the partner object is created and which aren't - influenced by any device-level parameters the parent (the driver - in this case) might set. - - Arguments: - - FxDeviceInit - the settings for this device. - - Return Value: - - status. - ---*/ -{ - IWDFDevice *fxDevice = NULL; - - HRESULT hr = S_OK; - - // - // TODO: If you're writing a filter driver then indicate that here. - // - // FxDeviceInit->SetFilter(); - // - - // - // Set no locking unless you need an automatic callbacks synchronization - // - - FxDeviceInit->SetLockingConstraint(None); - - // - // TODO: Any per-device initialization which must be done before - // creating the partner object. - // - - // - // Create a new FX device object and assign the new callback object to - // handle any device level events that occur. - // - - // - // QueryIUnknown references the IUnknown interface that it returns - // (which is the same as referencing the device). We pass that to - // CreateDevice, which takes its own reference if everything works. - // - - if (SUCCEEDED(hr)) - { - IUnknown *unknown = this->QueryIUnknown(); - - hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice); - - unknown->Release(); - } - - // - // If that succeeded then set our FxDevice member variable. - // - - if (SUCCEEDED(hr)) - { - m_FxDevice = fxDevice; - - // - // Drop the reference we got from CreateDevice. Since this object - // is partnered with the framework object they have the same - // lifespan - there is no need for an additional reference. - // - - fxDevice->Release(); - } - - return hr; -} - -HRESULT -CMyDevice::Configure( - VOID - ) -/*++ - - Routine Description: - - This method is called after the device callback object has been initialized - and returned to the driver. It would setup the device's queues and their - corresponding callback objects. - - Arguments: - - FxDevice - the framework device object for which we're handling events. - - Return Value: - - status - ---*/ -{ - HRESULT hr = S_OK; - - hr = CMyReadWriteQueue::CreateInstance(this, &m_ReadWriteQueue); - - if (FAILED(hr)) - { - return hr; - } - - // - // We use default queue for read/write - // - - hr = m_ReadWriteQueue->Configure(); - - m_ReadWriteQueue->Release(); - - // - // Create the control queue and configure forwarding for IOCTL requests. - // - - if (SUCCEEDED(hr)) - { - hr = CMyControlQueue::CreateInstance(this, &m_ControlQueue); - - if (SUCCEEDED(hr)) - { - hr = m_ControlQueue->Configure(); - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->ConfigureRequestDispatching( - m_ControlQueue->GetFxQueue(), - WdfRequestDeviceIoControl, - true - ); - } - m_ControlQueue->Release(); - } - } - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_OSRUSBFX2, - NULL); - } - - return hr; -} - -HRESULT -CMyDevice::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method is called to get a pointer to one of the object's callback - interfaces. - - Since the skeleton driver doesn't support any of the device events, this - method simply calls the base class's BaseQueryInterface. - - If the skeleton is extended to include device event interfaces then this - method must be changed to check the IID and return pointers to them as - appropriate. - - Arguments: - - InterfaceId - the interface being requested - - Object - a location to store the interface pointer if successful - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - HRESULT hr; - - if (IsEqualIID(InterfaceId, __uuidof(IPnpCallbackHardware))) - { - *Object = QueryIPnpCallbackHardware(); - hr = S_OK; - } - else - { - hr = CUnknown::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -HRESULT -CMyDevice::OnPrepareHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked to ready the driver - to talk to hardware. It opens the handle to the - device and talks to it using the WINUSB interface. - It invokes WINUSB to discver the interfaces and stores - the information related to bulk endpoints. - -Arguments: - - FxDevice : Pointer to the WDF device interface - -Return Value: - - HRESULT - ---*/ -{ - PWSTR deviceName = NULL; - DWORD deviceNameCch = 0; - - HRESULT hr; - - // - // Get the device name. - // Get the length to allocate first - // - - hr = m_FxDevice->RetrieveDeviceName(NULL, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - - // - // Allocate the buffer - // - - if (SUCCEEDED(hr)) - { - deviceName = new WCHAR[deviceNameCch]; - - if (deviceName == NULL) - { - hr = E_OUTOFMEMORY; - } - } - - // - // Get the actual name - // - - if (SUCCEEDED(hr)) - { - hr = m_FxDevice->RetrieveDeviceName(deviceName, &deviceNameCch); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get device name %!hresult!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Device name %S", - deviceName - ); - } - - // - // Create USB I/O Targets and configure them - // - - if (SUCCEEDED(hr)) - { - hr = CreateUsbIoTargets(); - } - - if (SUCCEEDED(hr)) - { - ULONG length = sizeof(m_Speed); - - hr = m_pIUsbTargetDevice->RetrieveDeviceInformation(DEVICE_SPEED, - &length, - &m_Speed); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb device speed information %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_DEVICE, - "%!FUNC! Speed - %x\n", - m_Speed - ); - } - - if (SUCCEEDED(hr)) - { - hr = ConfigureUsbPipes(); - } - - delete[] deviceName; - - return hr; -} - -HRESULT -CMyDevice::OnReleaseHardware( - _In_ IWDFDevice * /* FxDevice */ - ) -/*++ - -Routine Description: - - This routine is invoked when the device is being removed or stopped - It releases all resources allocated for this device. - -Arguments: - - FxDevice - Pointer to the Device object. - -Return Value: - - HRESULT - Always succeeds. - ---*/ -{ - // - // Remove I/O target from object tree before any potential subsequent - // OnPrepareHardware creates a new one - // - - if (m_pIUsbTargetDevice) - { - m_pIUsbTargetDevice->DeleteWdfObject(); - } - - return S_OK; -} - -HRESULT -CMyDevice::CreateUsbIoTargets( - ) -/*++ - -Routine Description: - - This routine creates Usb device, interface and pipe objects - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr; - UCHAR NumEndPoints = 0; - IWDFUsbTargetFactory * pIUsbTargetFactory = NULL; - IWDFUsbTargetDevice * pIUsbTargetDevice = NULL; - IWDFUsbInterface * pIUsbInterface = NULL; - IWDFUsbTargetPipe * pIUsbPipe = NULL; - - hr = m_FxDevice->QueryInterface(IID_PPV_ARGS(&pIUsbTargetFactory)); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Cannot get usb target factory %!HRESULT!", - hr - ); - } - - if (SUCCEEDED(hr)) - { - hr = pIUsbTargetFactory->CreateUsbTargetDevice( - &pIUsbTargetDevice); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to create USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbTargetDevice = pIUsbTargetDevice; - - // - // Release the creation reference as object tree will maintain a reference - // - - pIUsbTargetDevice->Release(); - } - } - - if (SUCCEEDED(hr)) - { - UCHAR NumInterfaces = pIUsbTargetDevice->GetNumInterfaces(); - - WUDF_TEST_DRIVER_ASSERT(1 == NumInterfaces); - - hr = pIUsbTargetDevice->RetrieveUsbInterface(0, &pIUsbInterface); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB interface from USB Device I/O Target %!HRESULT!", - hr - ); - } - else - { - m_pIUsbInterface = pIUsbInterface; - - pIUsbInterface->Release(); //release creation reference - } - } - - if (SUCCEEDED(hr)) - { - NumEndPoints = pIUsbInterface->GetNumEndPoints(); - - if (NumEndPoints != NUM_OSRUSB_ENDPOINTS) { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Has %d endpoints, expected %d, returning %!HRESULT! ", - NumEndPoints, - NUM_OSRUSB_ENDPOINTS, - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - for (UCHAR PipeIndex = 0; PipeIndex < NumEndPoints; PipeIndex++) - { - hr = pIUsbInterface->RetrieveUsbPipeObject(PipeIndex, - &pIUsbPipe); - - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to retrieve USB Pipe for PipeIndex %d, %!HRESULT!", - PipeIndex, - hr - ); - } - else - { - if ( pIUsbPipe->IsInEndPoint() && (UsbdPipeTypeBulk == pIUsbPipe->GetType()) ) - { - m_pIUsbInputPipe = pIUsbPipe; - } - else if ( pIUsbPipe->IsOutEndPoint() && (UsbdPipeTypeBulk == pIUsbPipe->GetType()) ) - { - m_pIUsbOutputPipe = pIUsbPipe; - } - else - { - pIUsbPipe->DeleteWdfObject(); - } - - SAFE_RELEASE(pIUsbPipe); //release creation reference - } - } - - if (NULL == m_pIUsbInputPipe || NULL == m_pIUsbOutputPipe) - { - hr = E_UNEXPECTED; - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Input or output pipe not found, returning %!HRESULT!", - hr - ); - } - } - - SAFE_RELEASE(pIUsbTargetFactory); - - return hr; -} - -HRESULT -CMyDevice::ConfigureUsbPipes( - ) -/*++ - -Routine Description: - - This routine retrieves the IDs for the bulk end points of the USB device. - -Arguments: - - None - -Return Value: - - HRESULT ---*/ -{ - HRESULT hr = S_OK; - LONG timeout; - - // - // Set timeout policies for input/output pipes - // - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbInputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for input pipe %!HRESULT!", - hr - ); - } - } - - if (SUCCEEDED(hr)) - { - timeout = ENDPOINT_TIMEOUT; - - hr = m_pIUsbOutputPipe->SetPipePolicy(PIPE_TRANSFER_TIMEOUT, - sizeof(timeout), - &timeout); - if (FAILED(hr)) - { - TraceEvents(TRACE_LEVEL_ERROR, - TEST_TRACE_DEVICE, - "%!FUNC! Unable to set timeout policy for output pipe %!HRESULT!", - hr - ); - } - } - - return hr; -} - -HRESULT -CMyDevice::SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ) -/*++ - - Routine Description: - - This method synchronously sets the bar graph display on the OSR USB-FX2 - device using the buffers in the FxRequest as input. - - Arguments: - - FxRequest - the request to set the bar-graph info. - - Return Value: - - Status - ---*/ -{ - WINUSB_CONTROL_SETUP_PACKET setupPacket; - - ULONG bytesTransferred; - - HRESULT hr = S_OK; - - // - // Setup the control packet. - // - - WINUSB_CONTROL_SETUP_PACKET_INIT( &setupPacket, - BmRequestHostToDevice, - BmRequestToDevice, - USBFX2LK_SET_BARGRAPH_DISPLAY, - 0, - 0 ); - - // - // Issue the request to WinUsb. - // - - hr = SendControlTransferSynchronously( - &(setupPacket.WinUsb), - (PUCHAR) BarGraphState, - sizeof(BAR_GRAPH_STATE), - &bytesTransferred - ); - - - return hr; -} - -HRESULT -CMyDevice::SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ) -{ - HRESULT hr = S_OK; - HRESULT hrRequest = S_OK; - IWDFIoRequest *pWdfRequest = NULL; - IWDFDriver * FxDriver = NULL; - IWDFMemory * FxMemory = NULL; - IWDFRequestCompletionParams * FxComplParams = NULL; - IWDFUsbRequestCompletionParams * FxUsbComplParams = NULL; - - *LengthTransferred = 0; - - hr = m_FxDevice->CreateRequest( NULL, //pCallbackInterface - NULL, //pParentObject - &pWdfRequest); - hrRequest = hr; - - if (SUCCEEDED(hr)) - { - m_FxDevice->GetDriver(&FxDriver); - - hr = FxDriver->CreatePreallocatedWdfMemory( Buffer, - BufferLength, - NULL, //pCallbackInterface - pWdfRequest, //pParetObject - &FxMemory ); - } - - if (SUCCEEDED(hr)) - { - hr = m_pIUsbTargetDevice->FormatRequestForControlTransfer( pWdfRequest, - SetupPacket, - FxMemory, - NULL); //TransferOffset - } - - if (SUCCEEDED(hr)) - { - hr = pWdfRequest->Send( m_pIUsbTargetDevice, - WDF_REQUEST_SEND_OPTION_SYNCHRONOUS, - 0); //Timeout - } - - if (SUCCEEDED(hr)) - { - pWdfRequest->GetCompletionParams(&FxComplParams); - - hr = FxComplParams->GetCompletionStatus(); - } - - if (SUCCEEDED(hr)) - { - HRESULT hrQI = FxComplParams->QueryInterface(IID_PPV_ARGS(&FxUsbComplParams)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI)); - - WUDF_TEST_DRIVER_ASSERT( WdfUsbRequestTypeDeviceControlTransfer == - FxUsbComplParams->GetCompletedUsbRequestType() ); - - FxUsbComplParams->GetDeviceControlTransferParameters( NULL, - LengthTransferred, - NULL, - NULL ); - } - - SAFE_RELEASE(FxUsbComplParams); - SAFE_RELEASE(FxComplParams); - SAFE_RELEASE(FxMemory); - - if (SUCCEEDED(hrRequest)) - { - pWdfRequest->DeleteWdfObject(); - } - SAFE_RELEASE(pWdfRequest); - - SAFE_RELEASE(FxDriver); - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/Device.h b/usb/wdf_osrfx2_lab/umdf/step4/Device.h deleted file mode 100644 index fe5acfed4..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/Device.h +++ /dev/null @@ -1,256 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Device.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample - driver's device callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once -#include "internal.h" - -#define ENDPOINT_TIMEOUT 10000 -#define NUM_OSRUSB_ENDPOINTS 3 - -// -// Define the vendor commands supported by our device -// -#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 - -// -// Class for the iotrace driver. -// - -class CMyDevice : - public CUnknown, - public IPnpCallbackHardware -{ - -// -// Private data members. -// -private: - // - // Weak reference to framework device - // - IWDFDevice *m_FxDevice; - - // - // Weak reference to the control queue - // - PCMyReadWriteQueue m_ReadWriteQueue; - - // - // Weak reference to the control queue - // - PCMyControlQueue m_ControlQueue; - - // - // USB Device I/O Target - // - IWDFUsbTargetDevice * m_pIUsbTargetDevice; - - // - // USB Interface - // - IWDFUsbInterface * m_pIUsbInterface; - - // - // USB Input pipe for Reads - // - IWDFUsbTargetPipe * m_pIUsbInputPipe; - - // - // USB Output pipe for writes - // - IWDFUsbTargetPipe * m_pIUsbOutputPipe; - - // - // Device Speed (Low, Full, High) - // - UCHAR m_Speed; - -// -// Private methods. -// - -private: - - CMyDevice( - VOID - ) : - m_FxDevice(NULL), - m_ControlQueue(NULL), - m_ReadWriteQueue(NULL), - m_pIUsbTargetDevice(NULL), - m_pIUsbInterface(NULL), - m_pIUsbInputPipe(NULL), - m_pIUsbOutputPipe(NULL), - m_Speed(0) - { - } - - ~CMyDevice( - ); - - HRESULT - Initialize( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - // - // Helper methods - // - - HRESULT - CreateUsbIoTargets( - VOID - ); - - - HRESULT - ConfigureUsbPipes( - ); - - HRESULT - SendControlTransferSynchronously( - _In_ PWINUSB_SETUP_PACKET SetupPacket, - _Inout_updates_(BufferLength) PBYTE Buffer, - _In_ ULONG BufferLength, - _Out_ PULONG LengthTransferred - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _In_ IWDFDriver *FxDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit, - _Out_ PCMyDevice *Device - ); - - IWDFDevice * - GetFxDevice( - VOID - ) - { - return m_FxDevice; - } - - HRESULT - Configure( - VOID - ); - - IPnpCallbackHardware * - QueryIPnpCallbackHardware( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - SetBarGraphDisplay( - _In_ PBAR_GRAPH_STATE BarGraphState - ); - - // - //returns a weak reference to input pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetInputPipe( - ) - { - return m_pIUsbInputPipe; - } - - // - //returns a weak reference to output pipe - //DO NOT release it - // - IWDFUsbTargetPipe * - GetOutputPipe( - ) - { - return m_pIUsbOutputPipe; - } - -// -// COM methods -// -public: - - // - // IUnknown methods. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IPnpCallbackHardware - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnPrepareHardware( - _In_ IWDFDevice *FxDevice - ); - - virtual - HRESULT - STDMETHODCALLTYPE - OnReleaseHardware( - _In_ IWDFDevice *FxDevice - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step4/Driver.cpp b/usb/wdf_osrfx2_lab/umdf/step4/Driver.cpp deleted file mode 100644 index bac5caca9..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/Driver.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - Driver.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample's - core driver callback object. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "driver.tmh" - -HRESULT -CMyDriver::CreateInstance( - _Out_ PCMyDriver *Driver - ) -/*++ - - Routine Description: - - This static method is invoked in order to create and initialize a new - instance of the driver class. The caller should arrange for the object - to be released when it is no longer in use. - - Arguments: - - Driver - a location to store a referenced pointer to the new instance - - Return Value: - - S_OK if successful, or error otherwise. - ---*/ -{ - PCMyDriver driver; - HRESULT hr; - - // - // Allocate the callback object. - // - - driver = new CMyDriver(); - - if (NULL == driver) - { - return E_OUTOFMEMORY; - } - - // - // Initialize the callback object. - // - - hr = driver->Initialize(); - - if (SUCCEEDED(hr)) - { - // - // Store a pointer to the new, initialized object in the output - // parameter. - // - - *Driver = driver; - } - else - { - - // - // Release the reference on the driver object to get it to delete - // itself. - // - - driver->Release(); - } - - return hr; -} - -HRESULT -CMyDriver::Initialize( - VOID - ) -/*++ - - Routine Description: - - This method is called to initialize a newly created driver callback object - before it is returned to the creator. Unlike the constructor, the - Initialize method contains operations which could potentially fail. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - return S_OK; -} - -HRESULT -CMyDriver::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Interface - ) -/*++ - - Routine Description: - - This method returns a pointer to the requested interface on the callback - object.. - - Arguments: - - InterfaceId - the IID of the interface to query/reference - - Interface - a location to store the interface pointer. - - Return Value: - - S_OK if the interface is supported. - E_NOINTERFACE if it is not supported. - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IDriverEntry))) - { - *Interface = QueryIDriverEntry(); - return S_OK; - } - else - { - return CUnknown::QueryInterface(InterfaceId, Interface); - } -} - -HRESULT -CMyDriver::OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ) -/*++ - - Routine Description: - - The FX invokes this method when it wants to install our driver on a device - stack. This method creates a device callback object, then calls the Fx - to create an Fx device object and associate the new callback object with - it. - - Arguments: - - FxWdfDriver - the Fx driver object. - - FxDeviceInit - the initialization information for the device. - - Return Value: - - status - ---*/ -{ - HRESULT hr; - - PCMyDevice device = NULL; - - // - // TODO: Do any per-device initialization (reading settings from the - // registry for example) that's necessary before creating your - // device callback object here. Otherwise you can leave such - // initialization to the initialization of the device event - // handler. - // - - // - // Create a new instance of our device callback object - // - - hr = CMyDevice::CreateInstance(FxWdfDriver, FxDeviceInit, &device); - - // - // TODO: Change any per-device settings that the object exposes before - // calling Configure to let it complete its initialization. - // - - // - // If that succeeded then call the device's construct method. This - // allows the device to create any queues or other structures that it - // needs now that the corresponding fx device object has been created. - // - - if (SUCCEEDED(hr)) - { - hr = device->Configure(); - } - - // - // Release the reference on the device callback object now that it's been - // associated with an fx device object. - // - - if (NULL != device) - { - device->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/Driver.h b/usb/wdf_osrfx2_lab/umdf/step4/Driver.h deleted file mode 100644 index 800ab1d9a..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/Driver.h +++ /dev/null @@ -1,149 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Driver.h - -Abstract: - - This module contains the type definitions for the UMDF Skeleton sample's - driver callback class. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// This class handles driver events for the skeleton sample. In particular -// it supports the OnDeviceAdd event, which occurs when the driver is called -// to setup per-device handlers for a new device stack. -// - -class CMyDriver : public CUnknown, public IDriverEntry -{ -// -// Private data members. -// -private: - -// -// Private methods. -// -private: - - // - // Returns a refernced pointer to the IDriverEntry interface. - // - - IDriverEntry * - QueryIDriverEntry( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - HRESULT - Initialize( - VOID - ); - -// -// Public methods -// -public: - - // - // The factory method used to create an instance of this driver. - // - - static - HRESULT - CreateInstance( - _Out_ PCMyDriver *Driver - ); - -// -// COM methods -// -public: - - // - // IDriverEntry methods - // - - virtual - HRESULT - STDMETHODCALLTYPE - OnInitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return S_OK; - } - - virtual - HRESULT - STDMETHODCALLTYPE - OnDeviceAdd( - _In_ IWDFDriver *FxWdfDriver, - _In_ IWDFDeviceInitialize *FxDeviceInit - ); - - virtual - VOID - STDMETHODCALLTYPE - OnDeinitialize( - _In_ IWDFDriver *FxWdfDriver - ) - { - UNREFERENCED_PARAMETER(FxWdfDriver); - - return; - } - - // - // IUnknown methods. - // - // We have to implement basic ones here that redirect to the - // base class becuase of the multiple inheritance. - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.ctl b/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.ctl deleted file mode 100644 index 4dab56ae3..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.ctl +++ /dev/null @@ -1 +0,0 @@ -da5fbdfd-1eae-4ecf-b426-a3818f325ddb WudfOsrUsbFx2TraceGuid diff --git a/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.rc b/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.rc deleted file mode 100644 index 36f10ea90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/OsrUsbFx2.rc +++ /dev/null @@ -1,21 +0,0 @@ -//--------------------------------------------------------------------------- -// OsrUsbDevice.rc -// -// Copyright (c) Microsoft Corporation, All Rights Reserved -//--------------------------------------------------------------------------- - - -#include -#include - -// -// TODO: Change the file description and file names to match your binary. -// - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT_UNKNOWN -#define VER_FILEDESCRIPTION_STR "WDF:UMDF OSR USB Fx2 User-Mode Driver Sample" -#define VER_INTERNALNAME_STR "WUDFOsrUsbFx2" -#define VER_ORIGINALFILENAME_STR "WUDFOsrUsbFx2.dll" - -#include "common.ver" diff --git a/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.cpp b/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.cpp deleted file mode 100644 index 21f425488..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.cpp +++ /dev/null @@ -1,423 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "ReadWriteQueue.tmh" - -VOID -CMyReadWriteQueue::OnCompletion( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ) -{ - UNREFERENCED_PARAMETER(pIoTarget); - UNREFERENCED_PARAMETER(pContext); - - pWdfRequest->CompleteWithInformation( - pParams->GetCompletionStatus(), - pParams->GetInformation() - ); -} - -void -CMyReadWriteQueue::ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ) -{ - // - //First set the completion callback - // - - IRequestCallbackRequestCompletion * pCompletionCallback = NULL; - HRESULT hrQI = this->QueryInterface(IID_PPV_ARGS(&pCompletionCallback)); - WUDF_TEST_DRIVER_ASSERT(SUCCEEDED(hrQI) && (NULL != pCompletionCallback)); - - pRequest->SetCompletionCallback( - pCompletionCallback, - NULL - ); - - pCompletionCallback->Release(); - pCompletionCallback = NULL; - - // - //Send down the request - // - - HRESULT hrSend = S_OK; - hrSend = pRequest->Send(pIoTarget, - 0, //flags - 0); //timeout - - if (FAILED(hrSend)) - { - pRequest->CompleteWithInformation(hrSend, 0); - } - - return; -} - - -CMyReadWriteQueue::CMyReadWriteQueue( - _In_ PCMyDevice Device - ) : - CMyQueue(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyReadWriteQueue::~CMyReadWriteQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyReadWriteQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - - if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackWrite))) - { - hr = S_OK; - *Object = QueryIQueueCallbackWrite(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackRead))) - { - hr = S_OK; - *Object = QueryIQueueCallbackRead(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IRequestCallbackRequestCompletion))) - { - hr = S_OK; - *Object = QueryIRequestCallbackRequestCompletion(); - } - else if (IsEqualIID(InterfaceId, __uuidof(IQueueCallbackIoStop))) - { - hr = S_OK; - *Object = QueryIQueueCallbackIoStop(); - } - else - { - hr = CMyQueue::QueryInterface(InterfaceId, Object); - } - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyReadWriteQueue::CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ) -/*++ - -Routine Description: - - - CreateInstance creates an instance of the queue object. - -Aruments: - - ppUkwn - OUT parameter is an IUnknown interface to the queue object - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - PCMyReadWriteQueue queue; - HRESULT hr = S_OK; - - queue = new CMyReadWriteQueue(Device); - - if (NULL == queue) - { - hr = E_OUTOFMEMORY; - } - - // - // Call the queue callback object to initialize itself. This will create - // its partner queue framework object. - // - - if (SUCCEEDED(hr)) - { - hr = queue->Initialize(); - } - - if (SUCCEEDED(hr)) - { - *Queue = queue; - } - else - { - SAFE_RELEASE(queue); - } - - return hr; -} - -HRESULT -CMyReadWriteQueue::Initialize( - ) -{ - HRESULT hr; - - // - // First initialize the base class. This will create the partner FxIoQueue - // object and setup automatic forwarding of I/O controls. - // - - hr = __super::Initialize(WdfIoQueueDispatchParallel, - true, - true); - - // - // return the status. - // - - return hr; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnWrite( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToWrite - ) -/*++ - -Routine Description: - - - Write dispatch routine - IQueueCallbackWrite - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToWrite - Lenth of bytes in the write buffer - - Allocate and copy data to local buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToWrite - ); - - HRESULT hr = S_OK; - IWDFMemory * pInputMemory = NULL; - IWDFUsbTargetPipe * pOutputPipe = m_Device->GetOutputPipe(); - - pWdfRequest->GetInputMemory(&pInputMemory); - - hr = pOutputPipe->FormatRequestForWrite( - pWdfRequest, - NULL, //pFile - pInputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, pOutputPipe); - } - - SAFE_RELEASE(pInputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnRead( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T BytesToRead - ) -/*++ - -Routine Description: - - - Read dispatch routine - IQueueCallbackRead - -Aruments: - - pWdfQueue - Framework Queue instance - pWdfRequest - Framework Request instance - BytesToRead - Lenth of bytes in the read buffer - - Copy available data into the read buffer -Return Value: - - VOID - ---*/ -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC!: Queue %p Request %p BytesToTransfer %d\n", - this, - pWdfRequest, - (ULONG)(ULONG_PTR)BytesToRead - ); - - HRESULT hr = S_OK; - IWDFMemory * pOutputMemory = NULL; - - pWdfRequest->GetOutputMemory(&pOutputMemory); - - hr = m_Device->GetInputPipe()->FormatRequestForRead( - pWdfRequest, - NULL, //pFile - pOutputMemory, - NULL, //Memory offset - NULL //DeviceOffset - ); - - if (FAILED(hr)) - { - pWdfRequest->Complete(hr); - } - else - { - ForwardFormattedRequest(pWdfRequest, m_Device->GetInputPipe()); - } - - SAFE_RELEASE(pOutputMemory); - - return; -} - -STDMETHODIMP_ (void) -CMyReadWriteQueue::OnIoStop( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ) -{ - UNREFERENCED_PARAMETER(pWdfQueue); - - - // - // Because of device level locking we know that if our driver - // owns the request and we get here, our OnRead/OnWrite callback - // has returned and the request has been sent to I/O target - // - - if (ActionFlags == WdfRequestStopActionSuspend ) - { - // - // UMDF does not support an equivalent to WdfRequestStopAcknowledge. - // - // Cancel the request so that the power management operation can continue. - // - // NOTE: if cancelling the request would have an adverse affect and if the - // requests are expected to complete very quickly then leaving the - // request running may be a better option. - // - - pWdfRequest->CancelSentRequest(); - } - else if(ActionFlags == WdfRequestStopActionPurge) - { - // - // Cancel the sent request since we are asked to purge the request - // - - pWdfRequest->CancelSentRequest(); - } - - return; -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.h b/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.h deleted file mode 100644 index 4f1a98c13..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/ReadWriteQueue.h +++ /dev/null @@ -1,163 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - - -#define MAX_TRANSFER_SIZE(x) 64*1024*1024 - -// -// Queue Callback Object. -// - -class CMyReadWriteQueue : - public IQueueCallbackRead, - public IQueueCallbackWrite, - public IRequestCallbackRequestCompletion, - public IQueueCallbackIoStop, - public CMyQueue -{ -protected: - HRESULT - Initialize( - ); - - void - ForwardFormattedRequest( - _In_ IWDFIoRequest* pRequest, - _In_ IWDFIoTarget* pIoTarget - ); - -public: - - CMyReadWriteQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyReadWriteQueue(); - - static - HRESULT - CreateInstance( - _In_ PCMyDevice Device, - _Out_ PCMyReadWriteQueue *Queue - ); - - HRESULT - Configure( - VOID - ) - { - return CMyQueue::Configure(); - } - - IQueueCallbackWrite * - QueryIQueueCallbackWrite( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackRead * - QueryIQueueCallbackRead( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IRequestCallbackRequestCompletion * - QueryIRequestCallbackRequestCompletion( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - IQueueCallbackIoStop* - QueryIQueueCallbackIoStop( - VOID - ) - { - AddRef(); - return static_cast(this); - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - - // - // Wdf Callbacks - // - - // - // IQueueCallbackWrite - // - STDMETHOD_ (void, OnWrite)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToWrite - ); - - // - // IQueueCallbackRead - // - STDMETHOD_ (void, OnRead)( - _In_ IWDFIoQueue *pWdfQueue, - _In_ IWDFIoRequest *pWdfRequest, - _In_ SIZE_T NumOfBytesToRead - ); - - // - //IRequestCallbackRequestCompletion - // - - STDMETHOD_ (void, OnCompletion)( - _In_ IWDFIoRequest* pWdfRequest, - _In_ IWDFIoTarget* pIoTarget, - _In_ IWDFRequestCompletionParams* pParams, - _In_ PVOID pContext - ); - - // - //IQueueCallbackIoStop - // - - STDMETHOD_ (void, OnIoStop)( - _In_ IWDFIoQueue * pWdfQueue, - _In_ IWDFIoRequest * pWdfRequest, - _In_ ULONG ActionFlags - ); - -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.inx b/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.inx deleted file mode 100644 index 225c377f1..000000000 Binary files a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.inx and /dev/null differ diff --git a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj b/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj deleted file mode 100644 index ea987abd1..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj +++ /dev/null @@ -1,279 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {48343119-5771-494E-977E-0D439A45BF65} - $(MSBuildProjectName) - 1 - 1 - Debug - Win32 - {F45B07B6-EA19-4312-9BB3-5CF1BAFF50A8} - - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - False - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - Windows10 - True - Desktop - UMDF - WindowsUserModeDriver10.0 - DynamicLibrary - - - - $(IntDir) - - - - - - - - - - - - - - - - true - true - internal.h - - - true - true - internal.h - - - - WUDFOsrUsbFx2_4 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_4 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_4 - 0x0A00 - 0x0A000000 - - - WUDFOsrUsbFx2_4 - 0x0A00 - 0x0A000000 - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - true - Level4 - %(DisableSpecificWarnings);4201 - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - %(PreprocessorDefinitions);_UNICODE;UNICODE - - - _DllMainCRTStartup@12 - _DllMainCRTStartup - - - sha256 - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - - - %(AdditionalIncludeDirectories);..\..\inc;..\inc - - - %(AdditionalDependencies);$(SDK_LIB_PATH)\strsafe.lib;$(SDK_LIB_PATH)\kernel32.lib;$(SDK_LIB_PATH)\advapi32.lib - exports.def - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj.Filters b/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj.Filters deleted file mode 100644 index 43c2d8813..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/WUDFOsrUsbFx2_4.vcxproj.Filters +++ /dev/null @@ -1,52 +0,0 @@ - - - - - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* - {FFDE5D69-37F8-4393-A23B-564E903D88CD} - - - h;hpp;hxx;hm;inl;inc;xsd - {0B249192-6B94-4C90-BD54-09BDA2702DF1} - - - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml - {080D7F17-64DE-4D25-95ED-5FB56D2F35D7} - - - inf;inv;inx;mof;mc; - {71EC47E9-66DB-49A4-A668-16475FA16BB4} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/usb/wdf_osrfx2_lab/umdf/step4/comsup.cpp b/usb/wdf_osrfx2_lab/umdf/step4/comsup.cpp deleted file mode 100644 index 9c9aec3b5..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/comsup.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.cpp - -Abstract: - - This module contains implementations for the functions and methods - used for providing COM support. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" - -#include "comsup.tmh" - -// -// Implementation of CUnknown methods. -// - -CUnknown::CUnknown( - VOID - ) : m_ReferenceCount(1) -/*++ - - Routine Description: - - Constructor for an instance of the CUnknown class. This simply initializes - the reference count of the object to 1. The caller is expected to - call Release() if it wants to delete the object once it has been allocated. - - Arguments: - - None - - Return Value: - - None - ---*/ -{ - // do nothing. -} - -HRESULT -STDMETHODCALLTYPE -CUnknown::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method provides the basic support for query interface on CUnknown. - If the interface requested is IUnknown it references the object and - returns an interface pointer. Otherwise it returns an error. - - Arguments: - - InterfaceId - the IID being requested - - Object - a location to store the interface pointer to return. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - if (IsEqualIID(InterfaceId, __uuidof(IUnknown))) - { - *Object = QueryIUnknown(); - return S_OK; - } - else - { - *Object = NULL; - return E_NOINTERFACE; - } -} - -IUnknown * -CUnknown::QueryIUnknown( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IUnknown interface. - - This allows other methods to convert a CUnknown pointer into an IUnknown - pointer without a typecast and without calling QueryInterface and dealing - with the return value. - - Arguments: - - None - - Return Value: - - A pointer to the object's IUnknown interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::AddRef( - VOID - ) -/*++ - - Routine Description: - - This method adds one to the object's reference count. - - Arguments: - - None - - Return Value: - - The new reference count. The caller should only use this for debugging - as the object's actual reference count can change while the caller - examines the return value. - ---*/ -{ - return InterlockedIncrement(&m_ReferenceCount); -} - -ULONG -STDMETHODCALLTYPE -CUnknown::Release( - VOID - ) -/*++ - - Routine Description: - - This method subtracts one to the object's reference count. If the count - goes to zero, this method deletes the object. - - Arguments: - - None - - Return Value: - - The new reference count. If the caller uses this value it should only be - to check for zero (i.e. this call caused or will cause deletion) or - non-zero (i.e. some other call may have caused deletion, but this one - didn't). - ---*/ -{ - ULONG count = InterlockedDecrement(&m_ReferenceCount); - - if (count == 0) - { - delete this; - } - return count; -} - -// -// Implementation of CClassFactory methods. -// - -// -// Define storage for the factory's static lock count variable. -// - -LONG CClassFactory::s_LockCount = 0; - -IClassFactory * -CClassFactory::QueryIClassFactory( - VOID - ) -/*++ - - Routine Description: - - This helper method references the object and returns a pointer to the - object's IClassFactory interface. - - This allows other methods to convert a CClassFactory pointer into an - IClassFactory pointer without a typecast and without dealing with the - return value QueryInterface. - - Arguments: - - None - - Return Value: - - A referenced pointer to the object's IClassFactory interface. - ---*/ -{ - AddRef(); - return static_cast(this); -} - -HRESULT -CClassFactory::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - - Routine Description: - - This method attempts to retrieve the requested interface from the object. - - If the interface is found then the reference count on that interface (and - thus the object itself) is incremented. - - Arguments: - - InterfaceId - the interface the caller is requesting. - - Object - a location to store the interface pointer. - - Return Value: - - S_OK or E_NOINTERFACE - ---*/ -{ - // - // This class only supports IClassFactory so check for that. - // - - if (IsEqualIID(InterfaceId, __uuidof(IClassFactory))) - { - *Object = QueryIClassFactory(); - return S_OK; - } - else - { - // - // See if the base class supports the interface. - // - - return CUnknown::QueryInterface(InterfaceId, Object); - } -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::CreateInstance( - _In_opt_ IUnknown * /* OuterObject */, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ) -/*++ - - Routine Description: - - This COM method is the factory routine - it creates instances of the driver - callback class and returns the specified interface on them. - - Arguments: - - OuterObject - only used for aggregation, which our driver callback class - does not support. - - InterfaceId - the interface ID the caller would like to get from our - new object. - - Object - a location to store the referenced interface pointer to the new - object. - - Return Value: - - Status. - ---*/ -{ - HRESULT hr; - - PCMyDriver driver; - - *Object = NULL; - - hr = CMyDriver::CreateInstance(&driver); - - if (SUCCEEDED(hr)) - { - hr = driver->QueryInterface(InterfaceId, Object); - driver->Release(); - } - - return hr; -} - -HRESULT -STDMETHODCALLTYPE -CClassFactory::LockServer( - _In_ BOOL Lock - ) -/*++ - - Routine Description: - - This COM method can be used to keep the DLL in memory. However since the - driver's DllCanUnloadNow function always returns false, this has little - effect. Still it tracks the number of lock and unlock operations. - - Arguments: - - Lock - Whether the caller wants to lock or unlock the "server" - - Return Value: - - S_OK - ---*/ -{ - if (Lock) - { - InterlockedIncrement(&s_LockCount); - } - else - { - InterlockedDecrement(&s_LockCount); - } - return S_OK; -} - diff --git a/usb/wdf_osrfx2_lab/umdf/step4/comsup.h b/usb/wdf_osrfx2_lab/umdf/step4/comsup.h deleted file mode 100644 index dedf78c84..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/comsup.h +++ /dev/null @@ -1,215 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - ComSup.h - -Abstract: - - This module contains classes and functions use for providing COM support - code. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Forward type declarations. They are here rather than in internal.h as -// you only need them if you choose to use these support classes. -// - -typedef class CUnknown *PCUnknown; -typedef class CClassFactory *PCClassFactory; - -// -// Base class to implement IUnknown. You can choose to derive your COM -// classes from this class, or simply implement IUnknown in each of your -// classes. -// - -class CUnknown : public IUnknown -{ - -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The reference count for this object. Initialized to 1 in the - // constructor. - // - - LONG m_ReferenceCount; - -// -// Protected data members and methods. These are accessible by the subclasses -// but not by other classes. -// -protected: - - // - // The constructor and destructor are protected to ensure that only the - // subclasses of CUnknown can create and destroy instances. - // - - CUnknown( - VOID - ); - - // - // The destructor MUST be virtual. Since any instance of a CUnknown - // derived class should only be deleted from within CUnknown::Release, - // the destructor MUST be virtual or only CUnknown::~CUnknown will get - // invoked on deletion. - // - // If you see that your CMyDevice specific destructor is never being - // called, make sure you haven't deleted the virtual destructor here. - // - - virtual - ~CUnknown( - VOID - ) - { - // Do nothing - } - -// -// Public Methods. These are accessible by any class. -// -public: - - IUnknown * - QueryIUnknown( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ); - - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ); - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; - -// -// Class factory support class. Create an instance of this from your -// DllGetClassObject method and modify the implementation to create -// an instance of your driver event handler class. -// - -class CClassFactory : public CUnknown, public IClassFactory -{ -// -// Private data members and methods. These are only accessible by the methods -// of this class. -// -private: - - // - // The lock count. This is shared across all instances of IClassFactory - // and can be queried through the public IsLocked method. - // - - static LONG s_LockCount; - -// -// Public Methods. These are accessible by any class. -// -public: - - IClassFactory * - QueryIClassFactory( - VOID - ); - -// -// COM Methods. -// -public: - - // - // IUnknown methods - // - - virtual - ULONG - STDMETHODCALLTYPE - AddRef( - VOID - ) - { - return __super::AddRef(); - } - - _At_(this, __drv_freesMem(object)) - virtual - ULONG - STDMETHODCALLTYPE - Release( - VOID - ) - { - return __super::Release(); - } - - virtual - HRESULT - STDMETHODCALLTYPE - QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); - - // - // IClassFactory methods. - // - - virtual - HRESULT - STDMETHODCALLTYPE - CreateInstance( - _In_opt_ IUnknown *OuterObject, - _In_ REFIID InterfaceId, - _Out_ PVOID *Object - ); - - virtual - HRESULT - STDMETHODCALLTYPE - LockServer( - _In_ BOOL Lock - ); -}; diff --git a/usb/wdf_osrfx2_lab/umdf/step4/dllsup.cpp b/usb/wdf_osrfx2_lab/umdf/step4/dllsup.cpp deleted file mode 100644 index bd681ac22..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/dllsup.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved. - -Module Name: - - dllsup.cpp - -Abstract: - - This module contains the implementation of the UMDF Skeleton Sample - Driver's entry point and its exported functions for providing COM support. - - This module can be copied without modification to a new UMDF driver. It - depends on some of the code in comsup.cpp & comsup.h to handle DLL - registration and creating the first class factory. - - This module is dependent on the following defines: - - MYDRIVER_TRACING_ID - A wide string passed to WPP when initializing - tracing. For example the skeleton uses - L"Microsoft\\UMDF\\Skeleton" - - MYDRIVER_CLASS_ID - A GUID encoded in struct format used to - initialize the driver's ClassID. - - These are defined in internal.h for the skeleton sample. If you choose - to use a different primary include file, you should ensure they are - defined there as well. - -Environment: - - WDF User-Mode Driver Framework (WDF:UMDF) - ---*/ - -#include "internal.h" -#include "dllsup.tmh" - -const GUID CLSID_MyDriverCoClass = MYDRIVER_CLASS_ID; - -BOOL -WINAPI -DllMain( - HINSTANCE ModuleHandle, - DWORD Reason, - PVOID /* Reserved */ - ) -/*++ - - Routine Description: - - This is the entry point and exit point for the I/O trace driver. This - does very little as the I/O trace driver has minimal global data. - - This method initializes tracing, and saves the module handle away in a - global variable so that it can be referenced should the COM registration - code (Dll[Un]RegisterServer) be called. - - Arguments: - - ModuleHandle - the DLL handle for this module. - - Reason - the reason this entry point was called. - - Reserved - unused - - Return Value: - - TRUE - ---*/ -{ - UNREFERENCED_PARAMETER(ModuleHandle); - - if (DLL_PROCESS_ATTACH == Reason) - { - // - // Initialize tracing. - // - - WPP_INIT_TRACING(MYDRIVER_TRACING_ID); - } - else if (DLL_PROCESS_DETACH == Reason) - { - // - // Cleanup tracing. - // - - WPP_CLEANUP(); - } - - return TRUE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllCanUnloadNow( - VOID - ) -/*++ - - Routine Description: - - Called by the COM runtime when determining whether or not this module - can be unloaded. Our answer is always "no". - - Arguments: - - None - - Return Value: - - S_FALSE - ---*/ -{ - return S_FALSE; -} - -_Use_decl_annotations_ -HRESULT -STDAPICALLTYPE -DllGetClassObject( - REFCLSID ClassId, - REFIID InterfaceId, - LPVOID *Interface - ) -/*++ - - Routine Description: - - This routine is called by COM in order to instantiate the - skeleton driver callback object and do an initial query interface on it. - - This method only creates an instance of the driver's class factory, as this - is the minimum required to support UMDF. - - Arguments: - - ClassId - the CLSID of the object being "gotten" - - InterfaceId - the interface the caller wants from that object. - - Interface - a location to store the referenced interface pointer - - Return Value: - - S_OK if the function succeeds or error indicating the cause of the - failure. - ---*/ -{ - PCClassFactory factory; - - HRESULT hr = S_OK; - - *Interface = NULL; - - // - // If the CLSID doesn't match that of our "coclass" (defined in the IDL - // file) then we can't create the object the caller wants. This may - // indicate that the COM registration is incorrect, and another CLSID - // is referencing this drvier. - // - - if (IsEqualCLSID(ClassId, CLSID_MyDriverCoClass) == false) - { - Trace( - TRACE_LEVEL_ERROR, - L"ERROR: Called to create instance of unrecognized class (%!GUID!)", - &ClassId - ); - - return CLASS_E_CLASSNOTAVAILABLE; - } - - // - // Create an instance of the class factory for the caller. - // - - factory = new CClassFactory(); - - if (NULL == factory) - { - hr = E_OUTOFMEMORY; - } - - // - // Query the object we created for the interface the caller wants. After - // that we release the object. This will drive the reference count to - // 1 (if the QI succeeded an referenced the object) or 0 (if the QI failed). - // In the later case the object is automatically deleted. - // - - if (SUCCEEDED(hr)) - { - hr = factory->QueryInterface(InterfaceId, Interface); - factory->Release(); - } - - return hr; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/exports.def b/usb/wdf_osrfx2_lab/umdf/step4/exports.def deleted file mode 100644 index 15f923d3b..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/exports.def +++ /dev/null @@ -1,4 +0,0 @@ -; WudfOsrUsbDriver.def : Declares the module parameters. - -EXPORTS - DllGetClassObject PRIVATE diff --git a/usb/wdf_osrfx2_lab/umdf/step4/internal.h b/usb/wdf_osrfx2_lab/umdf/step4/internal.h deleted file mode 100644 index 86487dd90..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/internal.h +++ /dev/null @@ -1,154 +0,0 @@ -/*++ - -Copyright (C) Microsoft Corporation, All Rights Reserved - -Module Name: - - Internal.h - -Abstract: - - This module contains the local type definitions for the UMDF Skeleton - driver sample. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) -#endif - -// -// Include the WUDF Headers -// - -#include "wudfddi.h" - -// -// Use specstrings for in/out annotation of function parameters. -// - -#include "specstrings.h" - -// -// Get limits on common data types (ULONG_MAX for example) -// - -#include "limits.h" - -// -// We need usb I/O targets to talk to the OSR device. -// - -#include "wudfusb.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "public.h" - -// -// Include the header shared between the drivers and the test applications. -// - -#include "WUDFOsrUsbPublic.h" - -// -// Forward definitions of classes in the other header files. -// - -typedef class CMyDriver *PCMyDriver; -typedef class CMyDevice *PCMyDevice; -typedef class CMyQueue *PCMyQueue; - -typedef class CMyControlQueue *PCMyControlQueue; -typedef class CMyReadWriteQueue *PCMyReadWriteQueue; - -// -// Define the tracing flags. -// -// TODO: Choose a different trace control GUID -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - WudfOsrUsbFx2TraceGuid, (da5fbdfd,1eae,4ecf,b426,a3818f325ddb), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TEST_TRACE_DRIVER) \ - WPP_DEFINE_BIT(TEST_TRACE_DEVICE) \ - WPP_DEFINE_BIT(TEST_TRACE_QUEUE) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// - -// -// Driver specific #defines -// -// TODO: Change these values to be appropriate for your driver. -// - -#define MYDRIVER_TRACING_ID L"Microsoft\\UMDF\\OsrUsb" -#define MYDRIVER_CLASS_ID {0x0865b2b0, 0x6b73, 0x428f, {0xa3, 0xea, 0x21, 0x72, 0x83, 0x2d, 0x6b, 0xfc}} - -// -// Include the type specific headers. -// - -#include "comsup.h" -#include "driver.h" -#include "device.h" -#include "queue.h" -#include "ControlQueue.h" -#include "ReadWriteQueue.h" -#include "list.h" - -__forceinline -#ifdef _PREFAST_ -__declspec(noreturn) -#endif -VOID -WdfTestNoReturn( - VOID - ) -{ - // do nothing. -} - -#define WUDF_TEST_DRIVER_ASSERT(p) \ -{ \ - if ( !(p) ) \ - { \ - DebugBreak(); \ - WdfTestNoReturn(); \ - } \ -} - -#define SAFE_RELEASE(p) {if ((p)) { (p)->Release(); (p) = NULL; }} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/queue.cpp b/usb/wdf_osrfx2_lab/umdf/step4/queue.cpp deleted file mode 100644 index c56b38bbc..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/queue.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.cpp - -Abstract: - - This file implements the I/O queue interface and performs - the read/write/ioctl operations. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#include "internal.h" -#include "queue.tmh" - -CMyQueue::CMyQueue( - _In_ PCMyDevice Device - ) : - m_FxQueue(NULL), - m_Device(Device) -{ -} - -// -// Queue destructor. -// Free up the buffer, wait for thread to terminate and -// - -CMyQueue::~CMyQueue( - VOID - ) -/*++ - -Routine Description: - - - IUnknown implementation of Release - -Aruments: - - -Return Value: - - ULONG (reference count after Release) - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TEST_TRACE_QUEUE, - "%!FUNC! Entry" - ); - -} - - -HRESULT -STDMETHODCALLTYPE -CMyQueue::QueryInterface( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ) -/*++ - -Routine Description: - - - Query Interface - -Aruments: - - Follows COM specifications - -Return Value: - - HRESULT indicatin success or failure - ---*/ -{ - HRESULT hr; - - hr = CUnknown::QueryInterface(InterfaceId, Object); - - return hr; -} - -// -// Initialize -// - -HRESULT -CMyQueue::Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ) -{ - IWDFIoQueue *fxQueue; - HRESULT hr; - - // - // Create the I/O Queue object. - // - - { - IUnknown *callback = QueryIUnknown(); - - hr = m_Device->GetFxDevice()->CreateIoQueue( - callback, - Default, - DispatchType, - PowerManaged, - FALSE, - &fxQueue - ); - callback->Release(); - } - - if (SUCCEEDED(hr)) - { - m_FxQueue = fxQueue; - - // - // Release the creation reference on the queue. This object will be - // destroyed before the queue so we don't need to have a reference out - // on it. - // - - fxQueue->Release(); - } - - return hr; -} - -HRESULT -CMyQueue::Configure( - VOID - ) -{ - return S_OK; -} diff --git a/usb/wdf_osrfx2_lab/umdf/step4/queue.h b/usb/wdf_osrfx2_lab/umdf/step4/queue.h deleted file mode 100644 index 5659224bb..000000000 --- a/usb/wdf_osrfx2_lab/umdf/step4/queue.h +++ /dev/null @@ -1,93 +0,0 @@ -/*++ - -Copyright (c) Microsoft Corporation, All Rights Reserved - -Module Name: - - queue.h - -Abstract: - - This file defines the queue callback interface. - -Environment: - - Windows User-Mode Driver Framework (WUDF) - ---*/ - -#pragma once - -// -// Queue Callback Object. -// - -class CMyQueue : - public CUnknown -{ -protected: - // - // Unreferenced pointer to the partner Fx device. - // - - IWDFIoQueue *m_FxQueue; - - // - // Unreferenced pointer to the parent device. - // - - PCMyDevice m_Device; - - HRESULT - Initialize( - _In_ WDF_IO_QUEUE_DISPATCH_TYPE DispatchType, - _In_ bool Default, - _In_ bool PowerManaged - ); - -protected: - - CMyQueue( - _In_ PCMyDevice Device - ); - - virtual ~CMyQueue(); - - HRESULT - Configure( - VOID - ); - -public: - - IWDFIoQueue * - GetFxQueue( - VOID - ) - { - return m_FxQueue; - } - - - PCMyDevice - GetDevice( - VOID - ) - { - return m_Device; - } - - // - // IUnknown - // - - STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();} - - _At_(this, __drv_freesMem(object)) - STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();} - - STDMETHOD_(HRESULT, QueryInterface)( - _In_ REFIID InterfaceId, - _Outptr_ PVOID *Object - ); -}; diff --git a/usb/wdf_osrfx2_lab/wdf_osrfx2_lab.sln b/usb/wdf_osrfx2_lab/wdf_osrfx2_lab.sln index 105c66432..13795799c 100644 --- a/usb/wdf_osrfx2_lab/wdf_osrfx2_lab.sln +++ b/usb/wdf_osrfx2_lab/wdf_osrfx2_lab.sln @@ -17,18 +17,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Step5", "Step5", "{20339A89 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{BC1A657D-F736-42B1-8B6F-65660268D1E4}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Step1", "Step1", "{5B8D9AE9-CD64-4BDE-924B-85E2CFF7AC6D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Umdf", "Umdf", "{891C089F-780C-4983-8C50-1A1C9BEB0593}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Step2", "Step2", "{9C88D019-1CD4-44BD-8355-75C0F1A0D348}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Step3", "Step3", "{F9F19F6E-0B8B-4ED0-BA15-75455AC110D4}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Step4", "Step4", "{852E07AA-FE41-404F-BE25-30B5BCE596B7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{CAFB7E8F-109E-4224-BD53-EE93946311DF}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrusbfx2", "kmdf\step1\osrusbfx2.vcxproj", "{E54BDD18-FDE9-42BF-BC23-343F8764B387}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrusbfx2", "kmdf\step2\osrusbfx2.vcxproj", "{CE2CAF81-E96B-4C32-9BE9-58238742D295}" @@ -41,16 +29,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrusbfx2", "kmdf\step5\osr EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrusbfx2", "kmdf\exe\osrusbfx2.vcxproj", "{6EED5CDD-5526-40DC-97F9-582857E10187}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2_1", "umdf\step1\WUDFOsrUsbFx2_1.vcxproj", "{94BDC8D1-B62F-4200-9873-D403B6D30301}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2_2", "umdf\step2\WUDFOsrUsbFx2_2.vcxproj", "{808B6774-93FA-4ABF-A23F-35C55FA80B80}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2_3", "umdf\step3\WUDFOsrUsbFx2_3.vcxproj", "{4BED411D-1B55-4A64-84C9-36EC25F083D2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WUDFOsrUsbFx2_4", "umdf\step4\WUDFOsrUsbFx2_4.vcxproj", "{48343119-5771-494E-977E-0D439A45BF65}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WudfOsrUsbFx2Test", "umdf\exe\WudfOsrUsbFx2Test.vcxproj", "{B4244D54-7EBF-43D4-BB6D-C994C182C572}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -107,46 +85,6 @@ Global {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|x64.Build.0 = Debug|x64 {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|x64.ActiveCfg = Release|x64 {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|x64.Build.0 = Release|x64 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Debug|Win32.ActiveCfg = Debug|Win32 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Debug|Win32.Build.0 = Debug|Win32 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Release|Win32.ActiveCfg = Release|Win32 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Release|Win32.Build.0 = Release|Win32 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Debug|x64.ActiveCfg = Debug|x64 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Debug|x64.Build.0 = Debug|x64 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Release|x64.ActiveCfg = Release|x64 - {94BDC8D1-B62F-4200-9873-D403B6D30301}.Release|x64.Build.0 = Release|x64 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Debug|Win32.ActiveCfg = Debug|Win32 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Debug|Win32.Build.0 = Debug|Win32 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Release|Win32.ActiveCfg = Release|Win32 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Release|Win32.Build.0 = Release|Win32 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Debug|x64.ActiveCfg = Debug|x64 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Debug|x64.Build.0 = Debug|x64 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Release|x64.ActiveCfg = Release|x64 - {808B6774-93FA-4ABF-A23F-35C55FA80B80}.Release|x64.Build.0 = Release|x64 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Debug|Win32.ActiveCfg = Debug|Win32 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Debug|Win32.Build.0 = Debug|Win32 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Release|Win32.ActiveCfg = Release|Win32 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Release|Win32.Build.0 = Release|Win32 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Debug|x64.ActiveCfg = Debug|x64 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Debug|x64.Build.0 = Debug|x64 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Release|x64.ActiveCfg = Release|x64 - {4BED411D-1B55-4A64-84C9-36EC25F083D2}.Release|x64.Build.0 = Release|x64 - {48343119-5771-494E-977E-0D439A45BF65}.Debug|Win32.ActiveCfg = Debug|Win32 - {48343119-5771-494E-977E-0D439A45BF65}.Debug|Win32.Build.0 = Debug|Win32 - {48343119-5771-494E-977E-0D439A45BF65}.Release|Win32.ActiveCfg = Release|Win32 - {48343119-5771-494E-977E-0D439A45BF65}.Release|Win32.Build.0 = Release|Win32 - {48343119-5771-494E-977E-0D439A45BF65}.Debug|x64.ActiveCfg = Debug|x64 - {48343119-5771-494E-977E-0D439A45BF65}.Debug|x64.Build.0 = Debug|x64 - {48343119-5771-494E-977E-0D439A45BF65}.Release|x64.ActiveCfg = Release|x64 - {48343119-5771-494E-977E-0D439A45BF65}.Release|x64.Build.0 = Release|x64 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Debug|Win32.ActiveCfg = Debug|Win32 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Debug|Win32.Build.0 = Debug|Win32 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Release|Win32.ActiveCfg = Release|Win32 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Release|Win32.Build.0 = Release|Win32 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Debug|x64.ActiveCfg = Debug|x64 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Debug|x64.Build.0 = Debug|x64 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Release|x64.ActiveCfg = Release|x64 - {B4244D54-7EBF-43D4-BB6D-C994C182C572}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -158,21 +96,11 @@ Global {AE6270A1-FAC6-45B2-A641-9BFAF534DD01} = {A9C9BC25-9393-405C-A366-B7F457CAD629} {EEB5FBCF-333A-4D54-B937-C24FB0CC10EB} = {20339A89-50EB-4567-9AD9-BF3B2484D1EA} {6EED5CDD-5526-40DC-97F9-582857E10187} = {BC1A657D-F736-42B1-8B6F-65660268D1E4} - {94BDC8D1-B62F-4200-9873-D403B6D30301} = {5B8D9AE9-CD64-4BDE-924B-85E2CFF7AC6D} - {808B6774-93FA-4ABF-A23F-35C55FA80B80} = {9C88D019-1CD4-44BD-8355-75C0F1A0D348} - {4BED411D-1B55-4A64-84C9-36EC25F083D2} = {F9F19F6E-0B8B-4ED0-BA15-75455AC110D4} - {48343119-5771-494E-977E-0D439A45BF65} = {852E07AA-FE41-404F-BE25-30B5BCE596B7} - {B4244D54-7EBF-43D4-BB6D-C994C182C572} = {CAFB7E8F-109E-4224-BD53-EE93946311DF} {D00328D3-8C3F-4702-B819-5A3830E7FA70} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} {46FAA529-1596-416E-82DA-C7BE08A96774} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} {DB521009-ED4B-48E6-85CE-9C5B8B6CA915} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} {A9C9BC25-9393-405C-A366-B7F457CAD629} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} {20339A89-50EB-4567-9AD9-BF3B2484D1EA} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} {BC1A657D-F736-42B1-8B6F-65660268D1E4} = {EA42BA41-FC92-4985-80CA-B8BAC85DA33D} - {5B8D9AE9-CD64-4BDE-924B-85E2CFF7AC6D} = {891C089F-780C-4983-8C50-1A1C9BEB0593} - {9C88D019-1CD4-44BD-8355-75C0F1A0D348} = {891C089F-780C-4983-8C50-1A1C9BEB0593} - {F9F19F6E-0B8B-4ED0-BA15-75455AC110D4} = {891C089F-780C-4983-8C50-1A1C9BEB0593} - {852E07AA-FE41-404F-BE25-30B5BCE596B7} = {891C089F-780C-4983-8C50-1A1C9BEB0593} - {CAFB7E8F-109E-4224-BD53-EE93946311DF} = {891C089F-780C-4983-8C50-1A1C9BEB0593} EndGlobalSection EndGlobal diff --git a/video/pixlib/PixLib.vcxproj b/video/pixlib/PixLib.vcxproj index 673a9ad88..abd7956b5 100644 --- a/video/pixlib/PixLib.vcxproj +++ b/video/pixlib/PixLib.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 StaticLibrary diff --git a/wia/ProdScan/ProdScan.inx b/wia/ProdScan/ProdScan.inx index 33d0da88b..6e8036ef9 100644 Binary files a/wia/ProdScan/ProdScan.inx and b/wia/ProdScan/ProdScan.inx differ diff --git a/wia/microdrv/testmcro.inx b/wia/microdrv/testmcro.inx index 5cd679a71..86e3d2209 100644 Binary files a/wia/microdrv/testmcro.inx and b/wia/microdrv/testmcro.inx differ diff --git a/wia/microdrv/testmcro.vcxproj b/wia/microdrv/testmcro.vcxproj index aba1dedaa..e382e4dea 100644 --- a/wia/microdrv/testmcro.vcxproj +++ b/wia/microdrv/testmcro.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/wia/wiadriverex/errhandler/errhandler.vcxproj b/wia/wiadriverex/errhandler/errhandler.vcxproj index 5d1b8a2fb..054b48281 100644 --- a/wia/wiadriverex/errhandler/errhandler.vcxproj +++ b/wia/wiadriverex/errhandler/errhandler.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/wia/wiadriverex/segfilter/segfilter.vcxproj b/wia/wiadriverex/segfilter/segfilter.vcxproj index 32c9db8c7..ff4321ca7 100644 --- a/wia/wiadriverex/segfilter/segfilter.vcxproj +++ b/wia/wiadriverex/segfilter/segfilter.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/wia/wiadriverex/uiext2/uiext2.vcxproj b/wia/wiadriverex/uiext2/uiext2.vcxproj index e38167abb..b9baba936 100644 --- a/wia/wiadriverex/uiext2/uiext2.vcxproj +++ b/wia/wiadriverex/uiext2/uiext2.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/wia/wiadriverex/usd/WiaDriver.inx b/wia/wiadriverex/usd/WiaDriver.inx index d7feb02fa..5d394e80d 100644 Binary files a/wia/wiadriverex/usd/WiaDriver.inx and b/wia/wiadriverex/usd/WiaDriver.inx differ diff --git a/wmi/wmiacpi/acpimof.vcxproj b/wmi/wmiacpi/acpimof.vcxproj index c0965badd..15803d3ce 100644 --- a/wmi/wmiacpi/acpimof.vcxproj +++ b/wmi/wmiacpi/acpimof.vcxproj @@ -29,7 +29,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -37,7 +37,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -45,7 +45,7 @@ Windows10 False - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary @@ -53,7 +53,7 @@ Windows10 True - Desktop + Windows Driver WindowsApplicationForDrivers10.0 DynamicLibrary diff --git a/wmi/wmisamp/WmiSamp.vcxproj b/wmi/wmisamp/WmiSamp.vcxproj index 098d3cefb..a0ae2b2aa 100644 --- a/wmi/wmisamp/WmiSamp.vcxproj +++ b/wmi/wmisamp/WmiSamp.vcxproj @@ -30,7 +30,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -38,7 +38,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -46,7 +46,7 @@ Windows10 False - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver @@ -54,7 +54,7 @@ Windows10 True - Universal + Windows Driver KMDF WindowsKernelModeDriver10.0 Driver diff --git a/wmi/wmisamp/wmisamp.inx b/wmi/wmisamp/wmisamp.inx index 800fda274..bdf4152fe 100644 Binary files a/wmi/wmisamp/wmisamp.inx and b/wmi/wmisamp/wmisamp.inx differ diff --git a/wpd/WpdBasicHardwareDriver/WpdBasicHardwareDriver.inx b/wpd/WpdBasicHardwareDriver/WpdBasicHardwareDriver.inx index 4f11ac230..53feb1554 100644 Binary files a/wpd/WpdBasicHardwareDriver/WpdBasicHardwareDriver.inx and b/wpd/WpdBasicHardwareDriver/WpdBasicHardwareDriver.inx differ diff --git a/wpd/WpdHelloWorldDriver/WpdHelloWorldDriver.inx b/wpd/WpdHelloWorldDriver/WpdHelloWorldDriver.inx index f79d78104..fe1a0b4b1 100644 Binary files a/wpd/WpdHelloWorldDriver/WpdHelloWorldDriver.inx and b/wpd/WpdHelloWorldDriver/WpdHelloWorldDriver.inx differ diff --git a/wpd/WpdMultiTransportDriver/WpdMultiTransportDriver.inx b/wpd/WpdMultiTransportDriver/WpdMultiTransportDriver.inx index b8504e047..3cd7d91b3 100644 Binary files a/wpd/WpdMultiTransportDriver/WpdMultiTransportDriver.inx and b/wpd/WpdMultiTransportDriver/WpdMultiTransportDriver.inx differ diff --git a/wpd/WpdServiceSampleDriver/WpdServiceSampleDriver.inx b/wpd/WpdServiceSampleDriver/WpdServiceSampleDriver.inx index cbf328cad..5802867f2 100644 Binary files a/wpd/WpdServiceSampleDriver/WpdServiceSampleDriver.inx and b/wpd/WpdServiceSampleDriver/WpdServiceSampleDriver.inx differ