Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4227 lines
103 KiB

  1. /*++
  2. Copyright (c) 1997 Microsoft Corporation
  3. Module Name:
  4. arbiter.c
  5. Abstract:
  6. This module contains support routines for the Pnp resource arbiters.
  7. Author:
  8. Andrew Thornton (andrewth) 1-April-1997
  9. Environment:
  10. Kernel mode
  11. Revision History:
  12. --*/
  13. #include "arbp.h"
  14. #define REGSTR_KEY_ROOTENUM L"ROOT"
  15. //
  16. // Conditional compilation constants
  17. //
  18. #define ALLOW_BOOT_ALLOC_CONFLICTS 1
  19. #define PLUG_FEST_HACKS 0
  20. //
  21. // Pool Tags
  22. //
  23. #define ARBITER_ALLOCATION_STATE_TAG 'AbrA'
  24. #define ARBITER_ORDERING_LIST_TAG 'LbrA'
  25. #define ARBITER_MISC_TAG 'MbrA'
  26. #define ARBITER_RANGE_LIST_TAG 'RbrA'
  27. #define ARBITER_CONFLICT_INFO_TAG 'CbrA'
  28. //
  29. // Constants
  30. //
  31. #define PATH_ARBITERS L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Arbiters"
  32. #define KEY_ALLOCATIONORDER L"AllocationOrder"
  33. #define KEY_RESERVEDRESOURCES L"ReservedResources"
  34. #define ARBITER_ORDERING_GROW_SIZE 8
  35. //
  36. // Macros
  37. //
  38. //
  39. // PVOID
  40. // FULL_INFO_DATA(
  41. // IN PKEY_VALUE_FULL_INFORMATION k
  42. // );
  43. //
  44. // This macro returns the pointer to the beginning of the data area of a
  45. // KEY_VALUE_FULL_INFORMATION structure.
  46. //
  47. #define FULL_INFO_DATA(k) ((PCHAR)(k) + (k)->DataOffset)
  48. //
  49. // BOOLEAN
  50. // DISJOINT(
  51. // IN ULONGLONG s1,
  52. // IN ULONGLONG e1,
  53. // IN ULONGLONG s2,
  54. // IN ULONGLONG e2
  55. // );
  56. //
  57. #define DISJOINT(s1,e1,s2,e2) \
  58. ( ((s1) < (s2) && (e1) < (s2)) \
  59. ||((s2) < (s1) && (e2) < (s1)) )
  60. //
  61. // VOID
  62. // ArbpWstrToUnicodeString(
  63. // IN PUNICODE_STRING u,
  64. // IN PWSTR p
  65. // );
  66. //
  67. #define ArbpWstrToUnicodeString(u, p) \
  68. (u)->Length = ((u)->MaximumLength = \
  69. (USHORT) (sizeof((p))) - sizeof(WCHAR)); \
  70. (u)->Buffer = (p)
  71. //
  72. // ULONG
  73. // INDEX_FROM_PRIORITY(
  74. // LONG Priority
  75. // );
  76. //
  77. #define ORDERING_INDEX_FROM_PRIORITY(P) \
  78. ( (ULONG) ( (P) > 0 ? (P) - 1 : ((P) * -1) - 1) )
  79. //
  80. // Prototypes
  81. //
  82. NTSTATUS
  83. ArbpBuildAllocationStack(
  84. IN PARBITER_INSTANCE Arbiter,
  85. IN PLIST_ENTRY ArbitrationList,
  86. IN ULONG ArbitrationListCount
  87. );
  88. NTSTATUS
  89. ArbpGetRegistryValue(
  90. IN HANDLE KeyHandle,
  91. IN PWSTR ValueName,
  92. OUT PKEY_VALUE_FULL_INFORMATION *Information
  93. );
  94. NTSTATUS
  95. ArbpBuildAlternative(
  96. IN PARBITER_INSTANCE Arbiter,
  97. IN PIO_RESOURCE_DESCRIPTOR Requirement,
  98. OUT PARBITER_ALTERNATIVE Alternative
  99. );
  100. VOID
  101. ArbpUpdatePriority(
  102. PARBITER_INSTANCE Arbiter,
  103. PARBITER_ALTERNATIVE Alternative
  104. );
  105. BOOLEAN
  106. ArbpQueryConflictCallback(
  107. IN PVOID Context,
  108. IN PRTL_RANGE Range
  109. );
  110. BOOLEAN
  111. ArbShareDriverExclusive(
  112. IN PARBITER_INSTANCE Arbiter,
  113. IN PARBITER_ALLOCATION_STATE State
  114. );
  115. //
  116. // Make everything pageable
  117. //
  118. #ifdef ALLOC_PRAGMA
  119. VOID
  120. ArbDereferenceArbiterInstance(
  121. IN PARBITER_INSTANCE Arbiter
  122. );
  123. #pragma alloc_text(PAGE, ArbInitializeArbiterInstance)
  124. #pragma alloc_text(PAGE, ArbDereferenceArbiterInstance)
  125. #pragma alloc_text(PAGE, ArbDeleteArbiterInstance)
  126. #pragma alloc_text(PAGE, ArbTestAllocation)
  127. #pragma alloc_text(PAGE, ArbpBuildAlternative)
  128. #pragma alloc_text(PAGE, ArbpBuildAllocationStack)
  129. #pragma alloc_text(PAGE, ArbSortArbitrationList)
  130. #pragma alloc_text(PAGE, ArbCommitAllocation)
  131. #pragma alloc_text(PAGE, ArbRollbackAllocation)
  132. #pragma alloc_text(PAGE, ArbRetestAllocation)
  133. #pragma alloc_text(PAGE, ArbBootAllocation)
  134. #pragma alloc_text(PAGE, ArbArbiterHandler)
  135. #pragma alloc_text(PAGE, ArbBuildAssignmentOrdering)
  136. #pragma alloc_text(PAGE, ArbFindSuitableRange)
  137. #pragma alloc_text(PAGE, ArbAddAllocation)
  138. #pragma alloc_text(PAGE, ArbBacktrackAllocation)
  139. #pragma alloc_text(PAGE, ArbPreprocessEntry)
  140. #pragma alloc_text(PAGE, ArbAllocateEntry)
  141. #pragma alloc_text(PAGE, ArbGetNextAllocationRange)
  142. #pragma alloc_text(PAGE, ArbpGetRegistryValue)
  143. #pragma alloc_text(PAGE, ArbInitializeOrderingList)
  144. #pragma alloc_text(PAGE, ArbCopyOrderingList)
  145. #pragma alloc_text(PAGE, ArbAddOrdering)
  146. #pragma alloc_text(PAGE, ArbPruneOrdering)
  147. #pragma alloc_text(PAGE, ArbFreeOrderingList)
  148. #pragma alloc_text(PAGE, ArbOverrideConflict)
  149. #pragma alloc_text(PAGE, ArbpUpdatePriority)
  150. #pragma alloc_text(PAGE, ArbAddReserved)
  151. #pragma alloc_text(PAGE, ArbpQueryConflictCallback)
  152. #pragma alloc_text(PAGE, ArbQueryConflict)
  153. #pragma alloc_text(PAGE, ArbStartArbiter)
  154. #pragma alloc_text(PAGE, ArbShareDriverExclusive)
  155. #endif // ALLOC_PRAGMA
  156. //
  157. // Implementation
  158. //
  159. NTSTATUS
  160. ArbInitializeArbiterInstance(
  161. OUT PARBITER_INSTANCE Arbiter,
  162. IN PDEVICE_OBJECT BusDeviceObject,
  163. IN CM_RESOURCE_TYPE ResourceType,
  164. IN PWSTR Name,
  165. IN PWSTR OrderingName,
  166. IN PARBITER_TRANSLATE_ALLOCATION_ORDER TranslateOrdering OPTIONAL
  167. )
  168. /*++
  169. Routine Description:
  170. This routine initializes an arbiter instance and fills in any optional NULL
  171. dispatch table entries with system default functions.
  172. Parameters:
  173. Arbiter - A caller allocated arbiter instance structure.
  174. The UnpackRequirement, PackResource, UnpackResource and ScoreRequirement
  175. entries should be initialized with the appropriate routines as should
  176. any other entries if the default system routines are not sufficient.
  177. BusDeviceObject - The device object that exposes this arbiter - normally an
  178. FDO.
  179. ResourceType - The resource type this arbiter arbitrates.
  180. Name - A string used to identify the arbiter, used in debug messages and
  181. for registry storage
  182. OrderingName - The name of the preferred assignment ordering list under
  183. HKLM\System\CurrentControlSet\Control\SystemResources\AssignmentOrdering
  184. TranslateOrdering - Function that, if present, will be called to translate
  185. each descriptor from the ordering list
  186. Return Value:
  187. Status code that indicates whether or not the function was successful.
  188. Notes:
  189. --*/
  190. {
  191. NTSTATUS status;
  192. PAGED_CODE();
  193. ASSERT(Arbiter->UnpackRequirement);
  194. ASSERT(Arbiter->PackResource);
  195. ASSERT(Arbiter->UnpackResource);
  196. ARB_PRINT(2,("Initializing %S Arbiter...\n", Name));
  197. //
  198. // Initialize all pool allocation pointers to NULL so we can cleanup
  199. //
  200. ASSERT(Arbiter->MutexEvent == NULL
  201. && Arbiter->Allocation == NULL
  202. && Arbiter->PossibleAllocation == NULL
  203. && Arbiter->AllocationStack == NULL
  204. );
  205. //
  206. // We are an arbiter
  207. //
  208. Arbiter->Signature = ARBITER_INSTANCE_SIGNATURE;
  209. //
  210. // Remember the bus that produced us
  211. //
  212. Arbiter->BusDeviceObject = BusDeviceObject;
  213. //
  214. // Initialize state lock (KEVENT must be non-paged)
  215. //
  216. Arbiter->MutexEvent = ExAllocatePoolWithTag(NonPagedPool,
  217. sizeof(KEVENT),
  218. ARBITER_MISC_TAG
  219. );
  220. if (!Arbiter->MutexEvent) {
  221. status = STATUS_INSUFFICIENT_RESOURCES;
  222. goto cleanup;
  223. }
  224. KeInitializeEvent(Arbiter->MutexEvent, SynchronizationEvent, TRUE);
  225. //
  226. // Initialize the allocation stack to a reasonable size
  227. //
  228. Arbiter->AllocationStack = ExAllocatePoolWithTag(PagedPool,
  229. INITIAL_ALLOCATION_STATE_SIZE,
  230. ARBITER_ALLOCATION_STATE_TAG
  231. );
  232. if (!Arbiter->AllocationStack) {
  233. status = STATUS_INSUFFICIENT_RESOURCES;
  234. goto cleanup;
  235. }
  236. Arbiter->AllocationStackMaxSize = INITIAL_ALLOCATION_STATE_SIZE;
  237. //
  238. // Allocate buffers to hold the range lists
  239. //
  240. Arbiter->Allocation = ExAllocatePoolWithTag(PagedPool,
  241. sizeof(RTL_RANGE_LIST),
  242. ARBITER_RANGE_LIST_TAG
  243. );
  244. if (!Arbiter->Allocation) {
  245. status = STATUS_INSUFFICIENT_RESOURCES;
  246. goto cleanup;
  247. }
  248. Arbiter->PossibleAllocation = ExAllocatePoolWithTag(PagedPool,
  249. sizeof(RTL_RANGE_LIST),
  250. ARBITER_RANGE_LIST_TAG
  251. );
  252. if (!Arbiter->PossibleAllocation) {
  253. status = STATUS_INSUFFICIENT_RESOURCES;
  254. goto cleanup;
  255. }
  256. //
  257. // Initialize the range lists
  258. //
  259. RtlInitializeRangeList(Arbiter->Allocation);
  260. RtlInitializeRangeList(Arbiter->PossibleAllocation);
  261. //
  262. // Initialize the data fields
  263. //
  264. Arbiter->TransactionInProgress = FALSE;
  265. Arbiter->Name = Name;
  266. Arbiter->ResourceType = ResourceType;
  267. //
  268. // If the caller has not supplied the optional functions set them to the
  269. // defaults (If this were C++ we'd just inherit this loit but seeing as its
  270. // not we'll do it the old fashioned way...)
  271. //
  272. if (!Arbiter->TestAllocation) {
  273. Arbiter->TestAllocation = ArbTestAllocation;
  274. }
  275. if (!Arbiter->RetestAllocation) {
  276. Arbiter->RetestAllocation = ArbRetestAllocation;
  277. }
  278. if (!Arbiter->CommitAllocation) {
  279. Arbiter->CommitAllocation = ArbCommitAllocation;
  280. }
  281. if (!Arbiter->RollbackAllocation) {
  282. Arbiter->RollbackAllocation = ArbRollbackAllocation;
  283. }
  284. if (!Arbiter->AddReserved) {
  285. Arbiter->AddReserved = ArbAddReserved;
  286. }
  287. if (!Arbiter->PreprocessEntry) {
  288. Arbiter->PreprocessEntry = ArbPreprocessEntry;
  289. }
  290. if (!Arbiter->AllocateEntry) {
  291. Arbiter->AllocateEntry = ArbAllocateEntry;
  292. }
  293. if (!Arbiter->GetNextAllocationRange) {
  294. Arbiter->GetNextAllocationRange = ArbGetNextAllocationRange;
  295. }
  296. if (!Arbiter->FindSuitableRange) {
  297. Arbiter->FindSuitableRange = ArbFindSuitableRange;
  298. }
  299. if (!Arbiter->AddAllocation) {
  300. Arbiter->AddAllocation = ArbAddAllocation;
  301. }
  302. if (!Arbiter->BacktrackAllocation) {
  303. Arbiter->BacktrackAllocation = ArbBacktrackAllocation;
  304. }
  305. if (!Arbiter->OverrideConflict) {
  306. Arbiter->OverrideConflict = ArbOverrideConflict;
  307. }
  308. if (!Arbiter->BootAllocation) {
  309. Arbiter->BootAllocation = ArbBootAllocation;
  310. }
  311. if (!Arbiter->QueryConflict) {
  312. Arbiter->QueryConflict = ArbQueryConflict;
  313. }
  314. if (!Arbiter->StartArbiter) {
  315. Arbiter->StartArbiter = ArbStartArbiter;
  316. }
  317. //
  318. // Build the prefered assignment ordering - we assume that the reserved
  319. // ranges have the same name as the assignment ordering
  320. //
  321. status = ArbBuildAssignmentOrdering(Arbiter,
  322. OrderingName,
  323. OrderingName,
  324. TranslateOrdering
  325. );
  326. if (!NT_SUCCESS(status)) {
  327. goto cleanup;
  328. }
  329. return STATUS_SUCCESS;
  330. cleanup:
  331. if (Arbiter->MutexEvent) {
  332. ExFreePool(Arbiter->MutexEvent);
  333. }
  334. if (Arbiter->Allocation) {
  335. ExFreePool(Arbiter->Allocation);
  336. }
  337. if (Arbiter->PossibleAllocation) {
  338. ExFreePool(Arbiter->PossibleAllocation);
  339. }
  340. if (Arbiter->AllocationStack) {
  341. ExFreePool(Arbiter->AllocationStack);
  342. }
  343. return status;
  344. }
  345. VOID
  346. ArbReferenceArbiterInstance(
  347. IN PARBITER_INSTANCE Arbiter
  348. )
  349. {
  350. InterlockedIncrement(&Arbiter->ReferenceCount);
  351. }
  352. VOID
  353. ArbDereferenceArbiterInstance(
  354. IN PARBITER_INSTANCE Arbiter
  355. )
  356. {
  357. PAGED_CODE();
  358. InterlockedDecrement(&Arbiter->ReferenceCount);
  359. if (Arbiter->ReferenceCount == 0) {
  360. ArbDeleteArbiterInstance(Arbiter);
  361. }
  362. }
  363. VOID
  364. ArbDeleteArbiterInstance(
  365. IN PARBITER_INSTANCE Arbiter
  366. )
  367. {
  368. PAGED_CODE();
  369. if (Arbiter->MutexEvent) {
  370. ExFreePool(Arbiter->MutexEvent);
  371. }
  372. if (Arbiter->Allocation) {
  373. RtlFreeRangeList(Arbiter->Allocation);
  374. ExFreePool(Arbiter->Allocation);
  375. }
  376. if (Arbiter->PossibleAllocation) {
  377. RtlFreeRangeList(Arbiter->PossibleAllocation);
  378. ExFreePool(Arbiter->PossibleAllocation);
  379. }
  380. if (Arbiter->AllocationStack) {
  381. ExFreePool(Arbiter->AllocationStack);
  382. }
  383. ArbFreeOrderingList(&Arbiter->OrderingList);
  384. ArbFreeOrderingList(&Arbiter->ReservedList);
  385. #if ARB_DBG
  386. RtlFillMemory(Arbiter, sizeof(ARBITER_INSTANCE), 'A');
  387. #endif
  388. }
  389. NTSTATUS
  390. ArbTestAllocation(
  391. IN PARBITER_INSTANCE Arbiter,
  392. IN OUT PLIST_ENTRY ArbitrationList
  393. )
  394. /*++
  395. Routine Description:
  396. This is the default implementation of the arbiter Test Allocation action.
  397. It takes a list of requests for resources for particular devices and attempts
  398. to satisfy them.
  399. Parameters:
  400. Arbiter - The instance of the arbiter being called.
  401. ArbitrationList - A list of ARBITER_LIST_ENTRY entries which contain the
  402. requirements and associated devices.
  403. Return Value:
  404. Status code that indicates whether or not the function was successful.
  405. These include:
  406. STATUS_SUCCESSFUL - Arbitration suceeded and an allocation has been made for
  407. all the entries in the arbitration list.
  408. STATUS_UNSUCCESSFUL - Arbitration failed to find an allocation for all
  409. entries.
  410. STATUS_ARBITRATION_UNHANDLED - If returning this error the arbiter is
  411. partial (and therefore must have set the ARBITER_PARTIAL flag in its
  412. interface.) This status indicates that this arbiter doesn't handle the
  413. resources requested and the next arbiter towards the root of the device
  414. tree should be asked instead.
  415. --*/
  416. {
  417. NTSTATUS status;
  418. PARBITER_LIST_ENTRY current;
  419. PIO_RESOURCE_DESCRIPTOR alternative;
  420. ULONG count;
  421. PDEVICE_OBJECT previousOwner;
  422. PDEVICE_OBJECT currentOwner;
  423. LONG score;
  424. BOOLEAN performScoring;
  425. PAGED_CODE();
  426. ASSERT(Arbiter);
  427. //
  428. // Copy the current allocation
  429. //
  430. ARB_PRINT(3, ("Copy current allocation\n"));
  431. status = RtlCopyRangeList(Arbiter->PossibleAllocation, Arbiter->Allocation);
  432. if (!NT_SUCCESS(status)) {
  433. goto cleanup;
  434. }
  435. //
  436. // Free all the resources currently allocated to all the devices we
  437. // are arbitrating for
  438. //
  439. count = 0;
  440. previousOwner = NULL;
  441. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, current) {
  442. count++;
  443. currentOwner = current->PhysicalDeviceObject;
  444. if (previousOwner != currentOwner) {
  445. previousOwner = currentOwner;
  446. ARB_PRINT(3,
  447. ("Delete 0x%08x's resources\n",
  448. currentOwner
  449. ));
  450. status = RtlDeleteOwnersRanges(Arbiter->PossibleAllocation,
  451. (PVOID)currentOwner
  452. );
  453. if (!NT_SUCCESS(status)) {
  454. goto cleanup;
  455. }
  456. }
  457. //
  458. // Score the entries in the arbitration list if a scoring function was
  459. // provided and this is not a legacy request (which is guaranteed to be
  460. // made of all fixed requests so sorting is pointless)
  461. //
  462. performScoring = Arbiter->ScoreRequirement != NULL;
  463. //
  464. // ISSUE-2000/03/06-andrewth
  465. // Ensure that in the start and enum cleanup the RequestSource is correctly passed in
  466. // so we can safely skip the unnecesary scoring and sorting
  467. // && !LEGACY_REQUEST(current);
  468. //
  469. current->WorkSpace = 0;
  470. if (performScoring) {
  471. FOR_ALL_IN_ARRAY(current->Alternatives,
  472. current->AlternativeCount,
  473. alternative) {
  474. ARB_PRINT(3,
  475. ("Scoring entry %p\n",
  476. currentOwner
  477. ));
  478. score = Arbiter->ScoreRequirement(alternative);
  479. //
  480. // Ensure the score is valid
  481. //
  482. if (score < 0) {
  483. status = STATUS_DEVICE_CONFIGURATION_ERROR;
  484. goto cleanup;
  485. }
  486. current->WorkSpace += score;
  487. }
  488. }
  489. }
  490. status = ArbSortArbitrationList(ArbitrationList);
  491. if (!NT_SUCCESS(status)) {
  492. goto cleanup;
  493. }
  494. //
  495. // Build the arbitration stack
  496. //
  497. status = ArbpBuildAllocationStack(Arbiter,
  498. ArbitrationList,
  499. count
  500. );
  501. if (!NT_SUCCESS(status)) {
  502. goto cleanup;
  503. }
  504. //
  505. // Attempt allocation
  506. //
  507. status = Arbiter->AllocateEntry(Arbiter, Arbiter->AllocationStack);
  508. if (NT_SUCCESS(status)) {
  509. //
  510. // Success.
  511. //
  512. return status;
  513. }
  514. cleanup:
  515. //
  516. // We didn't succeed so empty the possible allocation list...
  517. //
  518. RtlFreeRangeList(Arbiter->PossibleAllocation);
  519. return status;
  520. }
  521. NTSTATUS
  522. ArbpBuildAlternative(
  523. IN PARBITER_INSTANCE Arbiter,
  524. IN PIO_RESOURCE_DESCRIPTOR Requirement,
  525. OUT PARBITER_ALTERNATIVE Alternative
  526. )
  527. /*++
  528. Routine Description:
  529. This routine initializes a arbiter alternative from a given resource
  530. requirement descriptor
  531. Parameters:
  532. Arbiter - The arbiter instance data where the allocation stack should be
  533. placed.
  534. Requirement - The requirement descriptor describing this requirement
  535. Alternative - The alternative to be initialized
  536. Return Value:
  537. Status code that indicates whether or not the function was successful.
  538. --*/
  539. {
  540. NTSTATUS status;
  541. PAGED_CODE();
  542. ASSERT(Alternative && Requirement);
  543. Alternative->Descriptor = Requirement;
  544. //
  545. // Unpack the requirement into the alternatives table
  546. //
  547. status = Arbiter->UnpackRequirement(Requirement,
  548. &Alternative->Minimum,
  549. &Alternative->Maximum,
  550. &Alternative->Length,
  551. &Alternative->Alignment
  552. );
  553. if (!NT_SUCCESS(status)) {
  554. goto cleanup;
  555. }
  556. //
  557. // Align the minimum if necessary
  558. //
  559. if (Alternative->Minimum % Alternative->Alignment != 0) {
  560. ALIGN_ADDRESS_UP(Alternative->Minimum,
  561. Alternative->Alignment
  562. );
  563. }
  564. Alternative->Flags = 0;
  565. //
  566. // Check if this alternative is shared
  567. //
  568. if(Requirement->ShareDisposition == CmResourceShareShared) {
  569. Alternative->Flags |= ARBITER_ALTERNATIVE_FLAG_SHARED;
  570. }
  571. //
  572. // Check if this alternative is fixed
  573. //
  574. if (Alternative->Maximum - Alternative->Minimum + 1 == Alternative->Length) {
  575. Alternative->Flags |= ARBITER_ALTERNATIVE_FLAG_FIXED;
  576. }
  577. //
  578. // Check for validity
  579. //
  580. if (Alternative->Maximum < Alternative->Minimum) {
  581. Alternative->Flags |= ARBITER_ALTERNATIVE_FLAG_INVALID;
  582. }
  583. return STATUS_SUCCESS;
  584. cleanup:
  585. return status;
  586. }
  587. NTSTATUS
  588. ArbpBuildAllocationStack(
  589. IN PARBITER_INSTANCE Arbiter,
  590. IN PLIST_ENTRY ArbitrationList,
  591. IN ULONG ArbitrationListCount
  592. )
  593. /*++
  594. Routine Description:
  595. This routine initializes the allocation stack for the requests in
  596. ArbitrationList. It overwrites any previous allocation stack and allocates
  597. additional memory if more is required. Arbiter->AllocationStack contains
  598. the initialized stack on success.
  599. Parameters:
  600. Arbiter - The arbiter instance data where the allocation stack should be
  601. placed.
  602. ArbitrationList - A list of ARBITER_LIST_ENTRY entries which contain the
  603. requirements and associated devices.
  604. ArbitrationListCount - The number of entries in the ArbitrationList
  605. Return Value:
  606. Status code that indicates whether or not the function was successful.
  607. --*/
  608. {
  609. NTSTATUS status;
  610. PARBITER_LIST_ENTRY currentEntry;
  611. PARBITER_ALLOCATION_STATE currentState;
  612. ULONG stackSize = 0, allocationCount = ArbitrationListCount + 1;
  613. PARBITER_ALTERNATIVE currentAlternative;
  614. PIO_RESOURCE_DESCRIPTOR currentDescriptor;
  615. PAGED_CODE();
  616. //
  617. // Calculate the size the stack needs to be and the
  618. //
  619. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, currentEntry) {
  620. if (currentEntry->AlternativeCount > 0) {
  621. stackSize += currentEntry->AlternativeCount
  622. * sizeof(ARBITER_ALTERNATIVE);
  623. } else {
  624. allocationCount--;
  625. }
  626. }
  627. stackSize += allocationCount * sizeof(ARBITER_ALLOCATION_STATE);
  628. //
  629. // Make sure the allocation stack is large enough
  630. //
  631. if (Arbiter->AllocationStackMaxSize < stackSize) {
  632. PARBITER_ALLOCATION_STATE temp;
  633. //
  634. // Enlarge the allocation stack
  635. //
  636. temp = ExAllocatePoolWithTag(PagedPool,
  637. stackSize,
  638. ARBITER_ALLOCATION_STATE_TAG
  639. );
  640. if (!temp) {
  641. return STATUS_INSUFFICIENT_RESOURCES;
  642. }
  643. ExFreePool(Arbiter->AllocationStack);
  644. Arbiter->AllocationStack = temp;
  645. }
  646. RtlZeroMemory(Arbiter->AllocationStack, stackSize);
  647. //
  648. // Fill in the locations
  649. //
  650. currentState = Arbiter->AllocationStack;
  651. currentAlternative = (PARBITER_ALTERNATIVE) (Arbiter->AllocationStack
  652. + ArbitrationListCount + 1);
  653. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, currentEntry) {
  654. //
  655. // Do we need to allocate anything for this entry?
  656. //
  657. if (currentEntry->AlternativeCount > 0) {
  658. //
  659. // Initialize the stack location
  660. //
  661. currentState->Entry = currentEntry;
  662. currentState->AlternativeCount = currentEntry->AlternativeCount;
  663. currentState->Alternatives = currentAlternative;
  664. //
  665. // Initialize the start and end values to an invalid range so
  666. // that we don't skip the range 0-0 every time...
  667. //
  668. currentState->Start = 1;
  669. ASSERT(currentState->End == 0); // From RtlZeroMemory
  670. //
  671. // Initialize the alternatives table
  672. //
  673. FOR_ALL_IN_ARRAY(currentEntry->Alternatives,
  674. currentEntry->AlternativeCount,
  675. currentDescriptor) {
  676. status = ArbpBuildAlternative(Arbiter,
  677. currentDescriptor,
  678. currentAlternative
  679. );
  680. if (!NT_SUCCESS(status)) {
  681. goto cleanup;
  682. }
  683. //
  684. // Initialize the priority
  685. //
  686. currentAlternative->Priority = ARBITER_PRIORITY_NULL;
  687. //
  688. // Advance to the next alternative
  689. //
  690. currentAlternative++;
  691. }
  692. }
  693. currentState++;
  694. }
  695. //
  696. // Terminate the stack with NULL entry
  697. //
  698. currentState->Entry = NULL;
  699. return STATUS_SUCCESS;
  700. cleanup:
  701. //
  702. // We don't need to free the buffer as it is attached to the arbiter and
  703. // will be used next time
  704. //
  705. return status;
  706. }
  707. NTSTATUS
  708. ArbSortArbitrationList(
  709. IN OUT PLIST_ENTRY ArbitrationList
  710. )
  711. /*++
  712. Routine Description:
  713. This routine sorts the arbitration list in order of each entry's
  714. WorkSpace value.
  715. Parameters:
  716. ArbitrationList - The list to be sorted.
  717. Return Value:
  718. Status code that indicates whether or not the function was successful.
  719. --*/
  720. {
  721. BOOLEAN sorted = FALSE;
  722. PARBITER_LIST_ENTRY current, next;
  723. PAGED_CODE();
  724. ARB_PRINT(3, ("IoSortArbiterList(%p)\n", ArbitrationList));
  725. while (!sorted) {
  726. sorted = TRUE;
  727. for (current=(PARBITER_LIST_ENTRY) ArbitrationList->Flink,
  728. next=(PARBITER_LIST_ENTRY) current->ListEntry.Flink;
  729. (PLIST_ENTRY) current != ArbitrationList
  730. && (PLIST_ENTRY) next != ArbitrationList;
  731. current = (PARBITER_LIST_ENTRY) current->ListEntry.Flink,
  732. next = (PARBITER_LIST_ENTRY)current->ListEntry.Flink) {
  733. if (current->WorkSpace > next->WorkSpace) {
  734. PLIST_ENTRY before = current->ListEntry.Blink;
  735. PLIST_ENTRY after = next->ListEntry.Flink;
  736. //
  737. // Swap the locations of current and next
  738. //
  739. before->Flink = (PLIST_ENTRY) next;
  740. after->Blink = (PLIST_ENTRY) current;
  741. current->ListEntry.Flink = after;
  742. current->ListEntry.Blink = (PLIST_ENTRY) next;
  743. next->ListEntry.Flink = (PLIST_ENTRY) current;
  744. next->ListEntry.Blink = before;
  745. sorted = FALSE;
  746. }
  747. }
  748. }
  749. return STATUS_SUCCESS;
  750. }
  751. NTSTATUS
  752. ArbCommitAllocation(
  753. PARBITER_INSTANCE Arbiter
  754. )
  755. /*++
  756. Routine Description:
  757. This provides the default implementation of the CommitAllocation action.
  758. It frees the old allocation and replaces it with the new allocation.
  759. Parameters:
  760. Arbiter - The arbiter instance data for the arbiter being called.
  761. Return Value:
  762. Status code that indicates whether or not the function was successful.
  763. --*/
  764. {
  765. PRTL_RANGE_LIST temp;
  766. PAGED_CODE();
  767. //
  768. // Free up the current allocation
  769. //
  770. RtlFreeRangeList(Arbiter->Allocation);
  771. //
  772. // Swap the allocated and duplicate lists
  773. //
  774. temp = Arbiter->Allocation;
  775. Arbiter->Allocation = Arbiter->PossibleAllocation;
  776. Arbiter->PossibleAllocation = temp;
  777. return STATUS_SUCCESS;
  778. }
  779. NTSTATUS
  780. ArbRollbackAllocation(
  781. IN PARBITER_INSTANCE Arbiter
  782. )
  783. /*++
  784. Routine Description:
  785. This provides the default implementation of the RollbackAllocation action.
  786. It frees the possible allocation the last TestAllocation provided.
  787. Parameters:
  788. Arbiter - The arbiter instance data for the arbiter being called.
  789. Return Value:
  790. Status code that indicates whether or not the function was successful.
  791. --*/
  792. {
  793. PAGED_CODE();
  794. //
  795. // Free up the possible allocation
  796. //
  797. RtlFreeRangeList(Arbiter->PossibleAllocation);
  798. return STATUS_SUCCESS;
  799. }
  800. NTSTATUS
  801. ArbRetestAllocation(
  802. IN PARBITER_INSTANCE Arbiter,
  803. IN OUT PLIST_ENTRY ArbitrationList
  804. )
  805. /*++
  806. Routine Description:
  807. This provides the default implementation of the RetestAllocation action.
  808. It walks the arbitration list and updates the possible allocation to reflect
  809. the allocation entries of the list. For these entries to be valid
  810. TestAllocation must have been performed on this arbitration list.
  811. Parameters:
  812. Arbiter - The arbiter instance data for the arbiter being called.
  813. ArbitrationList - A list of ARBITER_LIST_ENTRY entries which contain the
  814. requirements and associated devices. TestAllocation for this arbiter
  815. should have been called on this list.
  816. Return Value:
  817. Status code that indicates whether or not the function was successful.
  818. --*/
  819. {
  820. NTSTATUS status;
  821. PARBITER_LIST_ENTRY current;
  822. ARBITER_ALLOCATION_STATE state;
  823. ARBITER_ALTERNATIVE alternative;
  824. ULONG length;
  825. PAGED_CODE();
  826. //
  827. // Initialize the state
  828. //
  829. RtlZeroMemory(&state, sizeof(ARBITER_ALLOCATION_STATE));
  830. RtlZeroMemory(&alternative, sizeof(ARBITER_ALTERNATIVE));
  831. state.AlternativeCount = 1;
  832. state.Alternatives = &alternative;
  833. state.CurrentAlternative = &alternative;
  834. state.Flags = ARBITER_STATE_FLAG_RETEST;
  835. //
  836. // Copy the current allocation and reserved
  837. //
  838. ARB_PRINT(2, ("Retest: Copy current allocation\n"));
  839. status = RtlCopyRangeList(Arbiter->PossibleAllocation, Arbiter->Allocation);
  840. if (!NT_SUCCESS(status)) {
  841. goto cleanup;
  842. }
  843. //
  844. // Free all the resources currently allocated to all the devices we
  845. // are arbitrating for
  846. //
  847. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, current) {
  848. ARB_PRINT(3,
  849. ("Retest: Delete 0x%08x's resources\n",
  850. current->PhysicalDeviceObject
  851. ));
  852. status = RtlDeleteOwnersRanges(Arbiter->PossibleAllocation,
  853. (PVOID) current->PhysicalDeviceObject
  854. );
  855. if (!NT_SUCCESS(status)) {
  856. goto cleanup;
  857. }
  858. }
  859. //
  860. // Build an allocation state for the allocation and call AddAllocation to
  861. // update the range lists accordingly
  862. //
  863. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, current) {
  864. ASSERT(current->Assignment && current->SelectedAlternative);
  865. state.WorkSpace = 0;
  866. state.Entry = current;
  867. //
  868. // Initialize the alternative
  869. //
  870. status = ArbpBuildAlternative(Arbiter,
  871. current->SelectedAlternative,
  872. &alternative
  873. );
  874. ASSERT(NT_SUCCESS(status));
  875. //
  876. // Update it with our allocation
  877. //
  878. status = Arbiter->UnpackResource(current->Assignment,
  879. &state.Start,
  880. &length
  881. );
  882. ASSERT(NT_SUCCESS(status));
  883. state.End = state.Start + length - 1;
  884. //
  885. // Do any preprocessing that is required
  886. //
  887. status = Arbiter->PreprocessEntry(Arbiter,&state);
  888. if (!NT_SUCCESS(status)) {
  889. goto cleanup;
  890. }
  891. //
  892. // If we had a requirement for length 0 then don't attemp to add the
  893. // range - it will fail!
  894. //
  895. if (length != 0) {
  896. Arbiter->AddAllocation(Arbiter, &state);
  897. }
  898. }
  899. return status;
  900. cleanup:
  901. RtlFreeRangeList(Arbiter->PossibleAllocation);
  902. return status;
  903. }
  904. NTSTATUS
  905. ArbBootAllocation(
  906. IN PARBITER_INSTANCE Arbiter,
  907. IN OUT PLIST_ENTRY ArbitrationList
  908. )
  909. /*++
  910. Routine Description:
  911. This provides the default implementation of the BootAllocation action.
  912. It walks the arbitration list and updates the allocation to reflect the fact
  913. that the allocation entries in the list are in use.
  914. Parameters:
  915. Arbiter - The arbiter instance data for the arbiter being called.
  916. ArbitrationList - A list of ARBITER_LIST_ENTRY entries which contain the
  917. requirements and associated devices. Each device should have one and
  918. only one requirement reflecting the resources it is currently consuming.
  919. Return Value:
  920. Status code that indicates whether or not the function was successful.
  921. --*/
  922. {
  923. NTSTATUS status;
  924. PARBITER_LIST_ENTRY current;
  925. PRTL_RANGE_LIST temp;
  926. ARBITER_ALLOCATION_STATE state;
  927. ARBITER_ALTERNATIVE alternative;
  928. PAGED_CODE();
  929. //
  930. // Initialize the state
  931. //
  932. RtlZeroMemory(&state, sizeof(ARBITER_ALLOCATION_STATE));
  933. RtlZeroMemory(&alternative, sizeof(ARBITER_ALTERNATIVE));
  934. state.AlternativeCount = 1;
  935. state.Alternatives = &alternative;
  936. state.CurrentAlternative = &alternative;
  937. state.Flags = ARBITER_STATE_FLAG_BOOT;
  938. state.RangeAttributes = ARBITER_RANGE_BOOT_ALLOCATED;
  939. //
  940. // Work on the possible allocation list
  941. //
  942. status = RtlCopyRangeList(Arbiter->PossibleAllocation, Arbiter->Allocation);
  943. FOR_ALL_IN_LIST(ARBITER_LIST_ENTRY, ArbitrationList, current) {
  944. ASSERT(current->AlternativeCount == 1);
  945. ASSERT(current->PhysicalDeviceObject);
  946. //
  947. // Build an alternative and state structure for this allocation and
  948. // add it to the range list
  949. //
  950. state.Entry = current;
  951. //
  952. // Initialize the alternative
  953. //
  954. status = ArbpBuildAlternative(Arbiter,
  955. &current->Alternatives[0],
  956. &alternative
  957. );
  958. ASSERT(NT_SUCCESS(status));
  959. ASSERT(alternative.Flags &
  960. (ARBITER_ALTERNATIVE_FLAG_FIXED | ARBITER_ALTERNATIVE_FLAG_INVALID)
  961. );
  962. state.Start = alternative.Minimum;
  963. state.End = alternative.Maximum;
  964. //
  965. // Blow away the old workspace and masks
  966. //
  967. state.WorkSpace = 0;
  968. state.RangeAvailableAttributes = 0;
  969. //
  970. // Validate the requirement
  971. //
  972. if (alternative.Length == 0
  973. || alternative.Alignment == 0
  974. || state.End < state.Start
  975. || state.Start % alternative.Alignment != 0
  976. || LENGTH_OF(state.Start, state.End) != alternative.Length) {
  977. ARB_PRINT(1,
  978. ("Skipping invalid boot allocation 0x%I64x-0x%I64x L 0x%x A 0x%x for 0x%08x\n",
  979. state.Start,
  980. state.End,
  981. alternative.Length,
  982. alternative.Alignment,
  983. current->PhysicalDeviceObject
  984. ));
  985. continue;
  986. }
  987. #if PLUG_FEST_HACKS
  988. if (alternative.Flags & ARBITER_ALTERNATIVE_FLAG_SHARED) {
  989. ARB_PRINT(1,
  990. ("Skipping shared boot allocation 0x%I64x-0x%I64x L 0x%x A 0x%x for 0x%08x\n",
  991. state.Start,
  992. state.End,
  993. alternative.Length,
  994. alternative.Alignment,
  995. current->PhysicalDeviceObject
  996. ));
  997. continue;
  998. }
  999. #endif
  1000. //
  1001. // Do any preprocessing that is required
  1002. //
  1003. status = Arbiter->PreprocessEntry(Arbiter,&state);
  1004. if (!NT_SUCCESS(status)) {
  1005. goto cleanup;;
  1006. }
  1007. Arbiter->AddAllocation(Arbiter, &state);
  1008. }
  1009. //
  1010. // Everything went OK so make this our allocated range
  1011. //
  1012. RtlFreeRangeList(Arbiter->Allocation);
  1013. temp = Arbiter->Allocation;
  1014. Arbiter->Allocation = Arbiter->PossibleAllocation;
  1015. Arbiter->PossibleAllocation = temp;
  1016. return STATUS_SUCCESS;
  1017. cleanup:
  1018. RtlFreeRangeList(Arbiter->PossibleAllocation);
  1019. return status;
  1020. }
  1021. NTSTATUS
  1022. ArbArbiterHandler(
  1023. IN PVOID Context,
  1024. IN ARBITER_ACTION Action,
  1025. IN OUT PARBITER_PARAMETERS Params
  1026. )
  1027. /*++
  1028. Routine Description:
  1029. This provides the default entry point to an arbiter.
  1030. Parameters:
  1031. Context - The context provided in the interface where this function was
  1032. called from. This is converted to an ARBITER_INSTANCE using the
  1033. ARBITER_CONTEXT_TO_INSTANCE macro which should be defined.
  1034. Action - The action the arbiter should perform.
  1035. Params - The parameters for the action.
  1036. Return Value:
  1037. Status code that indicates whether or not the function was successful.
  1038. Note:
  1039. The routines which implement each action are determined from the dispatch
  1040. table in the arbiter instance.
  1041. --*/
  1042. {
  1043. NTSTATUS status;
  1044. PARBITER_INSTANCE arbiter = Context;
  1045. PAGED_CODE();
  1046. ASSERT(Context);
  1047. ASSERT(Action >= 0 && Action <= ArbiterActionBootAllocation);
  1048. ASSERT(arbiter->Signature == ARBITER_INSTANCE_SIGNATURE);
  1049. //
  1050. // Acquire the state lock
  1051. //
  1052. ArbAcquireArbiterLock(arbiter);
  1053. //
  1054. // Announce ourselves
  1055. //
  1056. ARB_PRINT(2,
  1057. ("%s %S\n",
  1058. ArbpActionStrings[Action],
  1059. arbiter->Name
  1060. ));
  1061. //
  1062. // Check the transaction flag
  1063. //
  1064. if (Action == ArbiterActionTestAllocation
  1065. || Action == ArbiterActionRetestAllocation
  1066. || Action == ArbiterActionBootAllocation) {
  1067. ASSERT(!arbiter->TransactionInProgress);
  1068. } else if (Action == ArbiterActionCommitAllocation
  1069. || Action == ArbiterActionRollbackAllocation) {
  1070. ASSERT(arbiter->TransactionInProgress);
  1071. }
  1072. #if ARB_DBG
  1073. replay:
  1074. #endif
  1075. //
  1076. // Do the appropriate thing
  1077. //
  1078. switch (Action) {
  1079. case ArbiterActionTestAllocation:
  1080. //
  1081. // NTRAID #95564-2000/02/31-andrewth
  1082. // Until we support rebalance we don't deal with AllocateFrom
  1083. //
  1084. ASSERT(Params->Parameters.TestAllocation.AllocateFromCount == 0);
  1085. ASSERT(Params->Parameters.TestAllocation.AllocateFrom == NULL);
  1086. status = arbiter->TestAllocation(
  1087. arbiter,
  1088. Params->Parameters.TestAllocation.ArbitrationList
  1089. );
  1090. break;
  1091. case ArbiterActionRetestAllocation:
  1092. ASSERT(Params->Parameters.TestAllocation.AllocateFromCount == 0);
  1093. ASSERT(Params->Parameters.TestAllocation.AllocateFrom == NULL);
  1094. status = arbiter->RetestAllocation(
  1095. arbiter,
  1096. Params->Parameters.TestAllocation.ArbitrationList
  1097. );
  1098. break;
  1099. case ArbiterActionCommitAllocation:
  1100. status = arbiter->CommitAllocation(arbiter);
  1101. break;
  1102. case ArbiterActionRollbackAllocation:
  1103. status = arbiter->RollbackAllocation(arbiter);
  1104. break;
  1105. case ArbiterActionBootAllocation:
  1106. status = arbiter->BootAllocation(
  1107. arbiter,
  1108. Params->Parameters.BootAllocation.ArbitrationList
  1109. );
  1110. break;
  1111. case ArbiterActionQueryConflict:
  1112. status = arbiter->QueryConflict(
  1113. arbiter,
  1114. Params->Parameters.QueryConflict.PhysicalDeviceObject,
  1115. Params->Parameters.QueryConflict.ConflictingResource,
  1116. Params->Parameters.QueryConflict.ConflictCount,
  1117. Params->Parameters.QueryConflict.Conflicts
  1118. );
  1119. break;
  1120. case ArbiterActionQueryArbitrate:
  1121. case ArbiterActionQueryAllocatedResources:
  1122. case ArbiterActionWriteReservedResources:
  1123. case ArbiterActionAddReserved:
  1124. status = STATUS_NOT_IMPLEMENTED;
  1125. break;
  1126. default:
  1127. status = STATUS_INVALID_PARAMETER;
  1128. break;
  1129. }
  1130. #if ARB_DBG
  1131. //
  1132. // Check if we failed and want to stop or replay on errors
  1133. //
  1134. if (!NT_SUCCESS(status)) {
  1135. ARB_PRINT(1,
  1136. ("*** %s for %S FAILED status = %08x\n",
  1137. ArbpActionStrings[Action],
  1138. arbiter->Name,
  1139. status
  1140. ));
  1141. if (ArbStopOnError) {
  1142. DbgBreakPoint();
  1143. }
  1144. if (ArbReplayOnError) {
  1145. goto replay;
  1146. }
  1147. }
  1148. #endif // ARB_DBG
  1149. if (NT_SUCCESS(status)) {
  1150. if (Action == ArbiterActionTestAllocation
  1151. || Action == ArbiterActionRetestAllocation) {
  1152. arbiter->TransactionInProgress = TRUE;
  1153. } else if (Action == ArbiterActionCommitAllocation
  1154. || Action == ArbiterActionRollbackAllocation) {
  1155. arbiter->TransactionInProgress = FALSE;
  1156. }
  1157. }
  1158. ArbReleaseArbiterLock(arbiter);
  1159. return status;
  1160. }
  1161. NTSTATUS
  1162. ArbBuildAssignmentOrdering(
  1163. IN OUT PARBITER_INSTANCE Arbiter,
  1164. IN PWSTR AllocationOrderName,
  1165. IN PWSTR ReservedResourcesName,
  1166. IN PARBITER_TRANSLATE_ALLOCATION_ORDER Translate OPTIONAL
  1167. )
  1168. /*++
  1169. Routine Description:
  1170. This is called as part of arbiter initialization and extracts the allocation
  1171. ordering and reserved information from the registry and combines them into
  1172. an ordering list. The reserved ranges are put in Arbiter->ReservedList
  1173. and the initial ordering in Arbiter->OrderingList.
  1174. Parameters:
  1175. Arbiter - The instance data of the arbiter to be initialized.
  1176. AllocationOrderName - The name of the key under HKLM\System\
  1177. CurrentControlSet\Control\Arbiters\AllocationOrder the ordering
  1178. information should be taken from.
  1179. ReservedResourcesName - The name of the key under HKLM\System\
  1180. CurrentControlSet\Control\Arbiters\ReservedResources the reserved ranges
  1181. information should be taken from.
  1182. Translate - A function to be called for each range that will perform system
  1183. dependant translations required for this system.
  1184. Return Value:
  1185. Status code that indicates whether or not the function was successful.
  1186. --*/
  1187. {
  1188. NTSTATUS status;
  1189. HANDLE arbitersHandle = NULL, tempHandle = NULL;
  1190. UNICODE_STRING unicodeString;
  1191. PKEY_VALUE_FULL_INFORMATION info = NULL;
  1192. ULONG dummy;
  1193. PIO_RESOURCE_LIST resourceList;
  1194. PIO_RESOURCE_DESCRIPTOR current;
  1195. ULONGLONG start, end;
  1196. OBJECT_ATTRIBUTES attributes;
  1197. IO_RESOURCE_DESCRIPTOR translated;
  1198. PAGED_CODE();
  1199. ArbAcquireArbiterLock(Arbiter);
  1200. //
  1201. // If we are reinitializing the orderings free the old ones
  1202. //
  1203. ArbFreeOrderingList(&Arbiter->OrderingList);
  1204. ArbFreeOrderingList(&Arbiter->ReservedList);
  1205. //
  1206. // Initialize the orderings
  1207. //
  1208. status = ArbInitializeOrderingList(&Arbiter->OrderingList);
  1209. if (!NT_SUCCESS(status)) {
  1210. goto cleanup;
  1211. }
  1212. status = ArbInitializeOrderingList(&Arbiter->ReservedList);
  1213. if (!NT_SUCCESS(status)) {
  1214. goto cleanup;
  1215. }
  1216. //
  1217. // Open HKLM\System\CurrentControlSet\Control\Arbiters
  1218. //
  1219. ArbpWstrToUnicodeString(&unicodeString, PATH_ARBITERS);
  1220. InitializeObjectAttributes(&attributes,
  1221. &unicodeString,
  1222. OBJ_CASE_INSENSITIVE,
  1223. NULL,
  1224. (PSECURITY_DESCRIPTOR) NULL
  1225. );
  1226. status = ZwOpenKey(&arbitersHandle,
  1227. KEY_READ,
  1228. &attributes
  1229. );
  1230. if (!NT_SUCCESS(status)) {
  1231. goto cleanup;
  1232. }
  1233. //
  1234. // Open AllocationOrder
  1235. //
  1236. ArbpWstrToUnicodeString(&unicodeString, KEY_ALLOCATIONORDER);
  1237. InitializeObjectAttributes(&attributes,
  1238. &unicodeString,
  1239. OBJ_CASE_INSENSITIVE,
  1240. arbitersHandle,
  1241. (PSECURITY_DESCRIPTOR) NULL
  1242. );
  1243. status = ZwOpenKey(&tempHandle,
  1244. KEY_READ,
  1245. &attributes
  1246. );
  1247. if (!NT_SUCCESS(status)) {
  1248. goto cleanup;
  1249. }
  1250. //
  1251. // Extract the value the user asked for
  1252. //
  1253. status = ArbpGetRegistryValue(tempHandle,
  1254. AllocationOrderName,
  1255. &info
  1256. );
  1257. if (!NT_SUCCESS(status)) {
  1258. goto cleanup;
  1259. }
  1260. //
  1261. // Check if the value we retrieved was a string and if so then it was a
  1262. // short cut to a value of that name - open it.
  1263. //
  1264. if (info->Type == REG_SZ) {
  1265. PKEY_VALUE_FULL_INFORMATION tempInfo;
  1266. PWSTR shortcut = (PWSTR) FULL_INFO_DATA(info);
  1267. //
  1268. // Check its NUL terminated
  1269. //
  1270. if (shortcut[(info->DataLength/sizeof(WCHAR))-1] != UNICODE_NULL) {
  1271. status = STATUS_INVALID_PARAMETER;
  1272. goto cleanup;
  1273. }
  1274. status = ArbpGetRegistryValue(tempHandle,
  1275. shortcut,
  1276. &tempInfo
  1277. );
  1278. if (!NT_SUCCESS(status)) {
  1279. goto cleanup;
  1280. }
  1281. ExFreePool(info);
  1282. info = tempInfo;
  1283. }
  1284. ZwClose(tempHandle);
  1285. //
  1286. // We only support one level of short cuts so this should be a
  1287. // REG_RESOURCE_REQUIREMENTS_LIST
  1288. //
  1289. if (info->Type != REG_RESOURCE_REQUIREMENTS_LIST) {
  1290. status = STATUS_INVALID_PARAMETER;
  1291. goto cleanup;
  1292. }
  1293. //
  1294. // Extract the resource list
  1295. //
  1296. ASSERT(((PIO_RESOURCE_REQUIREMENTS_LIST) FULL_INFO_DATA(info))
  1297. ->AlternativeLists == 1);
  1298. resourceList = (PIO_RESOURCE_LIST) &((PIO_RESOURCE_REQUIREMENTS_LIST)
  1299. FULL_INFO_DATA(info))->List[0];
  1300. //
  1301. // Convert the resource list into an ordering list
  1302. //
  1303. FOR_ALL_IN_ARRAY(resourceList->Descriptors,
  1304. resourceList->Count,
  1305. current) {
  1306. //
  1307. // Perform any translation that is necessary on the resources
  1308. //
  1309. if (ARGUMENT_PRESENT(Translate)) {
  1310. status = (Translate)(&translated, current);
  1311. if (!NT_SUCCESS(status)) {
  1312. goto cleanup;
  1313. }
  1314. } else {
  1315. translated = *current;
  1316. }
  1317. if (translated.Type == Arbiter->ResourceType) {
  1318. status = Arbiter->UnpackRequirement(&translated,
  1319. &start,
  1320. &end,
  1321. &dummy, //length
  1322. &dummy //alignment
  1323. );
  1324. if (!NT_SUCCESS(status)) {
  1325. goto cleanup;
  1326. }
  1327. status = ArbAddOrdering(&Arbiter->OrderingList,
  1328. start,
  1329. end
  1330. );
  1331. if (!NT_SUCCESS(status)) {
  1332. goto cleanup;
  1333. }
  1334. }
  1335. }
  1336. //
  1337. // We're finished with info...
  1338. //
  1339. ExFreePool(info);
  1340. info = NULL;
  1341. //
  1342. // Open ReservedResources
  1343. //
  1344. ArbpWstrToUnicodeString(&unicodeString, KEY_RESERVEDRESOURCES);
  1345. InitializeObjectAttributes(&attributes,
  1346. &unicodeString,
  1347. OBJ_CASE_INSENSITIVE,
  1348. arbitersHandle,
  1349. (PSECURITY_DESCRIPTOR) NULL
  1350. );
  1351. status = ZwCreateKey(&tempHandle,
  1352. KEY_READ,
  1353. &attributes,
  1354. 0,
  1355. (PUNICODE_STRING) NULL,
  1356. REG_OPTION_NON_VOLATILE,
  1357. NULL
  1358. );
  1359. if (!NT_SUCCESS(status)) {
  1360. goto cleanup;
  1361. }
  1362. //
  1363. // Extract the arbiter's reserved resources
  1364. //
  1365. status = ArbpGetRegistryValue(tempHandle,
  1366. ReservedResourcesName,
  1367. &info
  1368. );
  1369. if (!NT_SUCCESS(status)) {
  1370. goto cleanup;
  1371. }
  1372. //
  1373. // Check if the value we retrieved was a string and if so then it was a
  1374. // short cut to a value of that name - open it.
  1375. //
  1376. if (info->Type == REG_SZ) {
  1377. PKEY_VALUE_FULL_INFORMATION tempInfo;
  1378. PWSTR shortcut = (PWSTR) FULL_INFO_DATA(info);
  1379. //
  1380. // Check its NUL terminated
  1381. //
  1382. if (shortcut[(info->DataLength/sizeof(WCHAR))-1] != UNICODE_NULL) {
  1383. status = STATUS_INVALID_PARAMETER;
  1384. goto cleanup;
  1385. }
  1386. status = ArbpGetRegistryValue(tempHandle,
  1387. shortcut,
  1388. &tempInfo
  1389. );
  1390. if (!NT_SUCCESS(status)) {
  1391. goto cleanup;
  1392. }
  1393. ExFreePool(info);
  1394. info = tempInfo;
  1395. }
  1396. ZwClose(tempHandle);
  1397. if (NT_SUCCESS(status)) {
  1398. ASSERT(((PIO_RESOURCE_REQUIREMENTS_LIST) FULL_INFO_DATA(info))
  1399. ->AlternativeLists == 1);
  1400. resourceList = (PIO_RESOURCE_LIST) &((PIO_RESOURCE_REQUIREMENTS_LIST)
  1401. FULL_INFO_DATA(info))->List[0];
  1402. //
  1403. // Apply the reserved ranges to the ordering
  1404. //
  1405. FOR_ALL_IN_ARRAY(resourceList->Descriptors,
  1406. resourceList->Count,
  1407. current) {
  1408. //
  1409. // Perform any translation that is necessary on the resources
  1410. //
  1411. if (ARGUMENT_PRESENT(Translate)) {
  1412. status = (Translate)(&translated, current);
  1413. if (!NT_SUCCESS(status)) {
  1414. goto cleanup;
  1415. }
  1416. } else {
  1417. translated = *current;
  1418. }
  1419. if (translated.Type == Arbiter->ResourceType) {
  1420. status = Arbiter->UnpackRequirement(&translated,
  1421. &start,
  1422. &end,
  1423. &dummy, //length
  1424. &dummy //alignment
  1425. );
  1426. if (!NT_SUCCESS(status)) {
  1427. goto cleanup;
  1428. }
  1429. //
  1430. // Add the reserved range to the reserved ordering
  1431. //
  1432. status = ArbAddOrdering(&Arbiter->ReservedList, start, end);
  1433. if (!NT_SUCCESS(status)) {
  1434. goto cleanup;
  1435. }
  1436. //
  1437. // Prune the reserved range from the current ordering
  1438. //
  1439. status = ArbPruneOrdering(&Arbiter->OrderingList, start, end);
  1440. if (!NT_SUCCESS(status)) {
  1441. goto cleanup;
  1442. }
  1443. }
  1444. }
  1445. ExFreePool(info);
  1446. }
  1447. //
  1448. // All done!
  1449. //
  1450. ZwClose(arbitersHandle);
  1451. #if ARB_DBG
  1452. {
  1453. PARBITER_ORDERING current;
  1454. FOR_ALL_IN_ARRAY(Arbiter->OrderingList.Orderings,
  1455. Arbiter->OrderingList.Count,
  1456. current) {
  1457. ARB_PRINT(2,
  1458. ("Ordering: 0x%I64x-0x%I64x\n",
  1459. current->Start,
  1460. current->End
  1461. ));
  1462. }
  1463. ARB_PRINT(2, ("\n"));
  1464. FOR_ALL_IN_ARRAY(Arbiter->ReservedList.Orderings,
  1465. Arbiter->ReservedList.Count,
  1466. current) {
  1467. ARB_PRINT(2,
  1468. ("Reserved: 0x%I64x-0x%I64x\n",
  1469. current->Start,
  1470. current->End
  1471. ));
  1472. }
  1473. }
  1474. #endif
  1475. ArbReleaseArbiterLock(Arbiter);
  1476. return STATUS_SUCCESS;
  1477. cleanup:
  1478. if (arbitersHandle) {
  1479. ZwClose(arbitersHandle);
  1480. }
  1481. if (tempHandle) {
  1482. ZwClose(tempHandle);
  1483. }
  1484. if (info) {
  1485. ExFreePool(info);
  1486. }
  1487. if (Arbiter->OrderingList.Orderings) {
  1488. ExFreePool(Arbiter->OrderingList.Orderings);
  1489. Arbiter->OrderingList.Count = 0;
  1490. Arbiter->OrderingList.Maximum = 0;
  1491. }
  1492. if (Arbiter->ReservedList.Orderings) {
  1493. ExFreePool(Arbiter->ReservedList.Orderings);
  1494. Arbiter->ReservedList.Count = 0;
  1495. Arbiter->ReservedList.Maximum = 0;
  1496. }
  1497. ArbReleaseArbiterLock(Arbiter);
  1498. return status;
  1499. }
  1500. BOOLEAN
  1501. ArbFindSuitableRange(
  1502. PARBITER_INSTANCE Arbiter,
  1503. PARBITER_ALLOCATION_STATE State
  1504. )
  1505. /*++
  1506. Routine Description:
  1507. This routine is called from AllocateEntry once we have decided where we want
  1508. to allocate from. It tries to find a free range that matches the
  1509. requirements in State while restricting its possible solutions to the range
  1510. State->CurrentMinimum to State->CurrentMaximum. On success State->Start and
  1511. State->End represent this range.
  1512. Arguments:
  1513. Arbiter - The instance data of the arbiter who was called.
  1514. State - The state of the current arbitration.
  1515. Return Value:
  1516. TRUE if we found a range, FALSE otherwise.
  1517. --*/
  1518. {
  1519. NTSTATUS status;
  1520. ULONG findRangeFlags = 0;
  1521. PAGED_CODE();
  1522. ASSERT(State->CurrentAlternative);
  1523. //
  1524. // Catch the case where we backtrack and advance past the maximum
  1525. //
  1526. if (State->CurrentMinimum > State->CurrentMaximum) {
  1527. return FALSE;
  1528. }
  1529. //
  1530. // If we are asking for zero ports then trivially succeed with the minimum
  1531. // value and remember that backtracking this is a recipe for infinite loops
  1532. //
  1533. if (State->CurrentAlternative->Length == 0) {
  1534. State->End = State->Start = State->CurrentMinimum;
  1535. return TRUE;
  1536. }
  1537. //
  1538. // For legacy requests from IoAssignResources (directly or by way of
  1539. // HalAssignSlotResources) or IoReportResourceUsage we consider preallocated
  1540. // resources to be available for backward compatibility reasons.
  1541. //
  1542. // If we are allocating a devices boot config then we consider all other
  1543. // boot configs to be available.
  1544. //
  1545. if (State->Entry->RequestSource == ArbiterRequestLegacyReported
  1546. || State->Entry->RequestSource == ArbiterRequestLegacyAssigned) {
  1547. State->RangeAvailableAttributes |= ARBITER_RANGE_BOOT_ALLOCATED;
  1548. }
  1549. //
  1550. // Check if null conflicts are OK...
  1551. //
  1552. if (State->Flags & ARBITER_STATE_FLAG_NULL_CONFLICT_OK) {
  1553. findRangeFlags |= RTL_RANGE_LIST_NULL_CONFLICT_OK;
  1554. }
  1555. //
  1556. // ...or we are shareable...
  1557. //
  1558. if (State->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_SHARED) {
  1559. findRangeFlags |= RTL_RANGE_LIST_SHARED_OK;
  1560. }
  1561. //
  1562. // Select the first free alternative from the current alternative
  1563. //
  1564. status = RtlFindRange(
  1565. Arbiter->PossibleAllocation,
  1566. State->CurrentMinimum,
  1567. State->CurrentMaximum,
  1568. State->CurrentAlternative->Length,
  1569. State->CurrentAlternative->Alignment,
  1570. findRangeFlags,
  1571. State->RangeAvailableAttributes,
  1572. Arbiter->ConflictCallbackContext,
  1573. Arbiter->ConflictCallback,
  1574. &State->Start
  1575. );
  1576. if (NT_SUCCESS(status)) {
  1577. //
  1578. // We found a suitable range
  1579. //
  1580. State->End = State->Start + State->CurrentAlternative->Length - 1;
  1581. return TRUE;
  1582. } else {
  1583. if (ArbShareDriverExclusive(Arbiter, State) == FALSE) {
  1584. //
  1585. // We couldn't find any range so check if we will allow this conflict
  1586. // - if so don'd fail!
  1587. //
  1588. return Arbiter->OverrideConflict(Arbiter, State);
  1589. }
  1590. return TRUE;
  1591. }
  1592. }
  1593. VOID
  1594. ArbAddAllocation(
  1595. IN PARBITER_INSTANCE Arbiter,
  1596. IN PARBITER_ALLOCATION_STATE State
  1597. )
  1598. /*++
  1599. Routine Description:
  1600. This routine is called from AllocateEntry once we have found a possible
  1601. solution (State->Start - State->End). It adds the ranges that will not be
  1602. available if we commit to this solution to Arbiter->PossibleAllocation.
  1603. Arguments:
  1604. Arbiter - The instance data of the arbiter who was called.
  1605. State - The state of the current arbitration.
  1606. Return Value:
  1607. None.
  1608. --*/
  1609. {
  1610. NTSTATUS status;
  1611. PAGED_CODE();
  1612. status = RtlAddRange(
  1613. Arbiter->PossibleAllocation,
  1614. State->Start,
  1615. State->End,
  1616. State->RangeAttributes,
  1617. RTL_RANGE_LIST_ADD_IF_CONFLICT +
  1618. (State->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_SHARED
  1619. ? RTL_RANGE_LIST_ADD_SHARED : 0),
  1620. NULL,
  1621. State->Entry->PhysicalDeviceObject
  1622. );
  1623. ASSERT(NT_SUCCESS(status));
  1624. }
  1625. VOID
  1626. ArbBacktrackAllocation(
  1627. IN PARBITER_INSTANCE Arbiter,
  1628. IN PARBITER_ALLOCATION_STATE State
  1629. )
  1630. /*++
  1631. Routine Description:
  1632. This routine is called from AllocateEntry if the possible solution
  1633. (State->Start - State->End) does not allow us to allocate resources to
  1634. the rest of the devices being considered. It deletes the ranges that were
  1635. added to Arbiter->PossibleAllocation by AddAllocation.
  1636. Arguments:
  1637. Arbiter - The instance data of the arbiter who was called.
  1638. State - The state of the current arbitration.
  1639. Return Value:
  1640. None.
  1641. --*/
  1642. {
  1643. NTSTATUS status;
  1644. PAGED_CODE();
  1645. //
  1646. // We couldn't allocate for the rest of the ranges then
  1647. // backtrack
  1648. //
  1649. status = RtlDeleteRange(
  1650. Arbiter->PossibleAllocation,
  1651. State->Start,
  1652. State->End,
  1653. State->Entry->PhysicalDeviceObject
  1654. );
  1655. ASSERT(NT_SUCCESS(status));
  1656. ARB_PRINT(2,
  1657. ("\t\tBacktracking on 0x%I64x-0x%I64x for %p\n",
  1658. State->Start,
  1659. State->End,
  1660. State->Entry->PhysicalDeviceObject
  1661. ));
  1662. }
  1663. NTSTATUS
  1664. ArbPreprocessEntry(
  1665. IN PARBITER_INSTANCE Arbiter,
  1666. IN PARBITER_ALLOCATION_STATE State
  1667. )
  1668. /*++
  1669. Routine Description:
  1670. This routine is called from AllocateEntry to allow preprocessing of
  1671. entries
  1672. Arguments:
  1673. Arbiter - The instance data of the arbiter who was called.
  1674. State - The state of the current arbitration.
  1675. Return Value:
  1676. None.
  1677. --*/
  1678. {
  1679. PAGED_CODE();
  1680. return STATUS_SUCCESS;
  1681. }
  1682. NTSTATUS
  1683. ArbAllocateEntry(
  1684. IN PARBITER_INSTANCE Arbiter,
  1685. IN PARBITER_ALLOCATION_STATE State
  1686. )
  1687. /*++
  1688. Routine Description:
  1689. This is the core arbitration routine and is called from TestAllocation
  1690. to allocate resources for all of the entries in the allocation stack.
  1691. It calls off to various helper routines (described above) to perform this
  1692. task.
  1693. Arguments:
  1694. Arbiter - The instance data of the arbiter who was called.
  1695. State - The state of the current arbitration.
  1696. Return Value:
  1697. None.
  1698. --*/
  1699. {
  1700. NTSTATUS status;
  1701. PARBITER_ALLOCATION_STATE currentState = State;
  1702. BOOLEAN backtracking = FALSE;
  1703. PAGED_CODE();
  1704. //
  1705. // Have we reached the end of the list? If so then we have a working
  1706. // allocation.
  1707. //
  1708. tryAllocation:
  1709. while(currentState >= State && currentState->Entry != NULL) {
  1710. //
  1711. // Do any preprocessing that is required
  1712. //
  1713. status = Arbiter->PreprocessEntry(Arbiter,currentState);
  1714. if (!NT_SUCCESS(status)) {
  1715. return status;
  1716. }
  1717. //
  1718. // If we need to backtrack do so!
  1719. //
  1720. if (backtracking) {
  1721. ULONGLONG possibleCurrentMinimum;
  1722. backtracking = FALSE;
  1723. //
  1724. // Clear the CurrentAlternative of the *next* alternative - this will
  1725. // cause the priorities to be recalculated next time through so we
  1726. // will attempt to explore the search space again
  1727. //
  1728. // The currentState+1 is guaranteed to be safe because the only way
  1729. // we can get here is from where we currentState-- below.
  1730. //
  1731. (currentState + 1)->CurrentAlternative = NULL;
  1732. //
  1733. // We can't backtrack length 0 requests because there is nothing to
  1734. // backtrack so we would get stuck in an inifinite loop...
  1735. //
  1736. if (currentState->CurrentAlternative->Length == 0) {
  1737. goto failAllocation;
  1738. }
  1739. //
  1740. // Backtrack
  1741. //
  1742. Arbiter->BacktrackAllocation(Arbiter, currentState);
  1743. //
  1744. // Reduce allocation window to not include the range we backtracked
  1745. // and check that that doesn't underflow the minimum or wrap
  1746. //
  1747. possibleCurrentMinimum = currentState->Start - 1;
  1748. if (possibleCurrentMinimum > currentState->CurrentMinimum // wrapped
  1749. || possibleCurrentMinimum < currentState->CurrentAlternative->Minimum) {
  1750. //
  1751. // We have run out space in this alternative move on to the next
  1752. //
  1753. goto continueWithNextAllocationRange;
  1754. } else {
  1755. currentState->CurrentMaximum = possibleCurrentMinimum;
  1756. //
  1757. // Get back into arbitrating at the right point
  1758. //
  1759. goto continueWithNextSuitableRange;
  1760. }
  1761. }
  1762. //
  1763. // Try to allocate for this entry
  1764. //
  1765. continueWithNextAllocationRange:
  1766. while (Arbiter->GetNextAllocationRange(Arbiter, currentState)) {
  1767. ARB_INDENT(2, (ULONG)(currentState - State));
  1768. ARB_PRINT(2,
  1769. ("Testing 0x%I64x-0x%I64x %s\n",
  1770. currentState->CurrentMinimum,
  1771. currentState->CurrentMaximum,
  1772. currentState->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_SHARED ?
  1773. "shared" : "non-shared"
  1774. ));
  1775. continueWithNextSuitableRange:
  1776. while (Arbiter->FindSuitableRange(Arbiter, currentState)) {
  1777. //
  1778. // We found a possible solution
  1779. //
  1780. ARB_INDENT(2, (ULONG)(currentState - State));
  1781. if (currentState->CurrentAlternative->Length != 0) {
  1782. ARB_PRINT(2,
  1783. ("Possible solution for %p = 0x%I64x-0x%I64x, %s\n",
  1784. currentState->Entry->PhysicalDeviceObject,
  1785. currentState->Start,
  1786. currentState->End,
  1787. currentState->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_SHARED ?
  1788. "shared" : "non-shared"
  1789. ));
  1790. //
  1791. // Update the arbiter with the possible allocation
  1792. //
  1793. Arbiter->AddAllocation(Arbiter, currentState);
  1794. } else {
  1795. ARB_PRINT(2,
  1796. ("Zero length solution solution for %p = 0x%I64x-0x%I64x, %s\n",
  1797. currentState->Entry->PhysicalDeviceObject,
  1798. currentState->Start,
  1799. currentState->End,
  1800. currentState->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_SHARED ?
  1801. "shared" : "non-shared"
  1802. ));
  1803. //
  1804. // Set the result in the arbiter appropriatley so that we
  1805. // don't try and translate this zero requirement - it won't!
  1806. //
  1807. currentState->Entry->Result = ArbiterResultNullRequest;
  1808. }
  1809. //
  1810. // Move on to the next entry
  1811. //
  1812. currentState++;
  1813. goto tryAllocation;
  1814. }
  1815. }
  1816. failAllocation:
  1817. //
  1818. // We couldn't allocate for this device
  1819. //
  1820. if (currentState == State) {
  1821. //
  1822. // We are at the top of the allocation stack to we can't backtrack -
  1823. // *** GAME OVER ***
  1824. //
  1825. return STATUS_UNSUCCESSFUL;
  1826. } else {
  1827. //
  1828. // Backtrack and try again
  1829. //
  1830. ARB_INDENT(2, (ULONG)(currentState - State));
  1831. ARB_PRINT(2,
  1832. ("Allocation failed for %p - backtracking\n",
  1833. currentState->Entry->PhysicalDeviceObject
  1834. ));
  1835. backtracking = TRUE;
  1836. //
  1837. // Pop the last state off the stack and try a different path
  1838. //
  1839. currentState--;
  1840. goto tryAllocation;
  1841. }
  1842. }
  1843. //
  1844. // We have successfully allocated for all ranges so fill in the allocation
  1845. //
  1846. currentState = State;
  1847. while (currentState->Entry != NULL) {
  1848. status = Arbiter->PackResource(
  1849. currentState->CurrentAlternative->Descriptor,
  1850. currentState->Start,
  1851. currentState->Entry->Assignment
  1852. );
  1853. ASSERT(NT_SUCCESS(status));
  1854. //
  1855. // Remember the alternative we chose from so we can retrieve it during retest
  1856. //
  1857. currentState->Entry->SelectedAlternative
  1858. = currentState->CurrentAlternative->Descriptor;
  1859. ARB_PRINT(2,
  1860. ("Assigned - 0x%I64x-0x%I64x\n",
  1861. currentState->Start,
  1862. currentState->End
  1863. ));
  1864. currentState++;
  1865. }
  1866. return STATUS_SUCCESS;
  1867. }
  1868. BOOLEAN
  1869. ArbGetNextAllocationRange(
  1870. IN PARBITER_INSTANCE Arbiter,
  1871. IN OUT PARBITER_ALLOCATION_STATE State
  1872. )
  1873. /*++
  1874. Routine Description:
  1875. This routine attempts to find the next range where allocation should be
  1876. tried. It updates State->CurrentMinimum, State->CurrentMaximum and
  1877. State->CurrentAlternative to indicate this range.
  1878. Arguments:
  1879. Arbiter - The instance data of the arbiter
  1880. State - The state of the current arbitration
  1881. Return Value:
  1882. TRUE if a range to attemp allocation in is found, FALSE otherwise
  1883. --*/
  1884. {
  1885. PARBITER_ALTERNATIVE current, lowestAlternative;
  1886. ULONGLONG min, max;
  1887. PARBITER_ORDERING ordering;
  1888. for (;;) {
  1889. if (State->CurrentAlternative) {
  1890. //
  1891. // Update the priority of the alternative we selected last time
  1892. //
  1893. ArbpUpdatePriority(Arbiter, State->CurrentAlternative);
  1894. } else {
  1895. //
  1896. // This is the first time we are looking at this alternative or a
  1897. // backtrack - either way we need to update all the priorities
  1898. //
  1899. FOR_ALL_IN_ARRAY(State->Alternatives,
  1900. State->AlternativeCount,
  1901. current) {
  1902. current->Priority = ARBITER_PRIORITY_NULL;
  1903. ArbpUpdatePriority(Arbiter, current);
  1904. }
  1905. }
  1906. //
  1907. // Find the lowest priority of the alternatives
  1908. //
  1909. lowestAlternative = State->Alternatives;
  1910. FOR_ALL_IN_ARRAY(State->Alternatives + 1,
  1911. State->AlternativeCount - 1,
  1912. current) {
  1913. if (current->Priority < lowestAlternative->Priority) {
  1914. lowestAlternative = current;
  1915. }
  1916. }
  1917. ARB_INDENT(2, (ULONG)(State - Arbiter->AllocationStack));
  1918. //
  1919. // Check if we have run out of allocation ranges
  1920. //
  1921. if (lowestAlternative->Priority == ARBITER_PRIORITY_EXHAUSTED) {
  1922. if (lowestAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_FIXED) {
  1923. ARB_PRINT(2,("Fixed alternative exhausted\n"));
  1924. } else {
  1925. ARB_PRINT(2,("Alternative exhausted\n"));
  1926. }
  1927. return FALSE;
  1928. } else {
  1929. ARB_PRINT(2,(
  1930. "LowestAlternative: [%i] 0x%I64x-0x%I64x L=0x%08x A=0x%08x\n",
  1931. lowestAlternative->Priority,
  1932. lowestAlternative->Minimum,
  1933. lowestAlternative->Maximum,
  1934. lowestAlternative->Length,
  1935. lowestAlternative->Alignment
  1936. ));
  1937. }
  1938. //
  1939. // Check if we are now allowing reserved ranges
  1940. //
  1941. if (lowestAlternative->Priority == ARBITER_PRIORITY_RESERVED
  1942. || lowestAlternative->Priority == ARBITER_PRIORITY_PREFERRED_RESERVED) {
  1943. //
  1944. // Set min and max to be the Minimum and Maximum that the descriptor
  1945. // specified ignoring any reservations or orderings - this is our
  1946. // last chance
  1947. //
  1948. min = lowestAlternative->Minimum;
  1949. max = lowestAlternative->Maximum;
  1950. ARB_INDENT(2, (ULONG)(State - Arbiter->AllocationStack));
  1951. ARB_PRINT(2,("Allowing reserved ranges\n"));
  1952. } else {
  1953. ASSERT(ORDERING_INDEX_FROM_PRIORITY(lowestAlternative->Priority) <
  1954. Arbiter->OrderingList.Count);
  1955. //
  1956. // Locate the ordering we match
  1957. //
  1958. ordering = &Arbiter->OrderingList.Orderings
  1959. [ORDERING_INDEX_FROM_PRIORITY(lowestAlternative->Priority)];
  1960. //
  1961. // Make sure they overlap and are big enough - this is just paranoia
  1962. //
  1963. ASSERT(INTERSECT(lowestAlternative->Minimum,
  1964. lowestAlternative->Maximum,
  1965. ordering->Start,
  1966. ordering->End)
  1967. && INTERSECT_SIZE(lowestAlternative->Minimum,
  1968. lowestAlternative->Maximum,
  1969. ordering->Start,
  1970. ordering->End) >= lowestAlternative->Length);
  1971. //
  1972. // Calculate the allocation range
  1973. //
  1974. min = __max(lowestAlternative->Minimum, ordering->Start);
  1975. max = __min(lowestAlternative->Maximum, ordering->End);
  1976. }
  1977. //
  1978. // If this is a length 0 requirement then succeed now and avoid much
  1979. // trauma later
  1980. //
  1981. if (lowestAlternative->Length == 0) {
  1982. min = lowestAlternative->Minimum;
  1983. max = lowestAlternative->Maximum;
  1984. } else {
  1985. //
  1986. // Trim range to match alignment.
  1987. //
  1988. min += lowestAlternative->Alignment - 1;
  1989. min -= min % lowestAlternative->Alignment;
  1990. if ((lowestAlternative->Length - 1) > (max - min)) {
  1991. ARB_INDENT(3, (ULONG)(State - Arbiter->AllocationStack));
  1992. ARB_PRINT(3, ("Range cannot be aligned ... Skipping\n"));
  1993. //
  1994. // Set CurrentAlternative so we will update the priority of this
  1995. // alternative
  1996. //
  1997. State->CurrentAlternative = lowestAlternative;
  1998. continue;
  1999. }
  2000. max -= lowestAlternative->Length - 1;
  2001. max -= max % lowestAlternative->Alignment;
  2002. max += lowestAlternative->Length - 1;
  2003. }
  2004. //
  2005. // Check if we handed back the same range last time, for the same
  2006. // alternative, if so try to find another range
  2007. //
  2008. if (min == State->CurrentMinimum
  2009. && max == State->CurrentMaximum
  2010. && State->CurrentAlternative == lowestAlternative) {
  2011. ARB_INDENT(2, (ULONG)(State - Arbiter->AllocationStack));
  2012. ARB_PRINT(2,
  2013. ("Skipping identical allocation range\n"
  2014. ));
  2015. continue;
  2016. }
  2017. State->CurrentMinimum = min;
  2018. State->CurrentMaximum = max;
  2019. State->CurrentAlternative = lowestAlternative;
  2020. ARB_INDENT(2, (ULONG)(State - Arbiter->AllocationStack));
  2021. ARB_PRINT(1, ("AllocationRange: 0x%I64x-0x%I64x\n", min, max));
  2022. return TRUE;
  2023. }
  2024. }
  2025. NTSTATUS
  2026. ArbpGetRegistryValue(
  2027. IN HANDLE KeyHandle,
  2028. IN PWSTR ValueName,
  2029. OUT PKEY_VALUE_FULL_INFORMATION *Information
  2030. )
  2031. /*++
  2032. Routine Description:
  2033. This routine is invoked to retrieve the data for a registry key's value.
  2034. This is done by querying the value of the key with a zero-length buffer
  2035. to determine the size of the value, and then allocating a buffer and
  2036. actually querying the value into the buffer.
  2037. It is the responsibility of the caller to free the buffer.
  2038. Arguments:
  2039. KeyHandle - Supplies the key handle whose value is to be queried
  2040. ValueName - Supplies the null-terminated Unicode name of the value.
  2041. Information - Returns a pointer to the allocated data buffer.
  2042. Return Value:
  2043. The function value is the final status of the query operation.
  2044. Note:
  2045. The same as IopGetRegistryValue - it allows us to share the arbiter
  2046. code with pci.sys
  2047. --*/
  2048. {
  2049. UNICODE_STRING unicodeString;
  2050. NTSTATUS status;
  2051. PKEY_VALUE_FULL_INFORMATION infoBuffer;
  2052. ULONG keyValueLength;
  2053. PAGED_CODE();
  2054. RtlInitUnicodeString( &unicodeString, ValueName );
  2055. //
  2056. // Figure out how big the data value is so that a buffer of the
  2057. // appropriate size can be allocated.
  2058. //
  2059. status = ZwQueryValueKey( KeyHandle,
  2060. &unicodeString,
  2061. KeyValueFullInformationAlign64,
  2062. (PVOID) NULL,
  2063. 0,
  2064. &keyValueLength );
  2065. if (status != STATUS_BUFFER_OVERFLOW &&
  2066. status != STATUS_BUFFER_TOO_SMALL) {
  2067. return status;
  2068. }
  2069. //
  2070. // Allocate a buffer large enough to contain the entire key data value.
  2071. //
  2072. infoBuffer = ExAllocatePoolWithTag( PagedPool,
  2073. keyValueLength,
  2074. ARBITER_MISC_TAG
  2075. );
  2076. if (!infoBuffer) {
  2077. return STATUS_INSUFFICIENT_RESOURCES;
  2078. }
  2079. //
  2080. // Query the data for the key value.
  2081. //
  2082. status = ZwQueryValueKey( KeyHandle,
  2083. &unicodeString,
  2084. KeyValueFullInformationAlign64,
  2085. infoBuffer,
  2086. keyValueLength,
  2087. &keyValueLength );
  2088. if (!NT_SUCCESS( status )) {
  2089. ExFreePool( infoBuffer );
  2090. return status;
  2091. }
  2092. //
  2093. // Everything worked, so simply return the address of the allocated
  2094. // buffer to the caller, who is now responsible for freeing it.
  2095. //
  2096. *Information = infoBuffer;
  2097. return STATUS_SUCCESS;
  2098. }
  2099. #define ARBITER_ORDERING_LIST_INITIAL_SIZE 16
  2100. NTSTATUS
  2101. ArbInitializeOrderingList(
  2102. IN OUT PARBITER_ORDERING_LIST List
  2103. )
  2104. /*++
  2105. Routine Description:
  2106. This routine inititialize an arbiter ordering list.
  2107. Arguments:
  2108. List - The list to be initialized
  2109. Return Value:
  2110. Status code that indicates whether or not the function was successful.
  2111. --*/
  2112. {
  2113. PAGED_CODE();
  2114. ASSERT(List);
  2115. List->Orderings = ExAllocatePoolWithTag(PagedPool,
  2116. ARBITER_ORDERING_LIST_INITIAL_SIZE *
  2117. sizeof(ARBITER_ORDERING),
  2118. ARBITER_ORDERING_LIST_TAG
  2119. );
  2120. if (!List->Orderings) {
  2121. List->Maximum = 0;
  2122. List->Count = 0;
  2123. return STATUS_INSUFFICIENT_RESOURCES;
  2124. }
  2125. List->Count = 0;
  2126. List->Maximum = ARBITER_ORDERING_LIST_INITIAL_SIZE;
  2127. return STATUS_SUCCESS;
  2128. }
  2129. NTSTATUS
  2130. ArbCopyOrderingList(
  2131. OUT PARBITER_ORDERING_LIST Destination,
  2132. IN PARBITER_ORDERING_LIST Source
  2133. )
  2134. /*++
  2135. Routine Description:
  2136. This routine copies an arbiter ordering list.
  2137. Arguments:
  2138. Destination - An uninitialized arbiter ordering list where the data
  2139. should be copied from
  2140. Source - Arbiter ordering list to be copied
  2141. Return Value:
  2142. Status code that indicates whether or not the function was successful.
  2143. --*/
  2144. {
  2145. PAGED_CODE()
  2146. ASSERT(Source->Count <= Source->Maximum);
  2147. ASSERT(Source->Maximum > 0);
  2148. Destination->Orderings =
  2149. ExAllocatePoolWithTag(PagedPool,
  2150. Source->Maximum * sizeof(ARBITER_ORDERING),
  2151. ARBITER_ORDERING_LIST_TAG
  2152. );
  2153. if (Destination->Orderings == NULL) {
  2154. return STATUS_INSUFFICIENT_RESOURCES;
  2155. }
  2156. Destination->Count = Source->Count;
  2157. Destination->Maximum = Source->Maximum;
  2158. if (Source->Count > 0) {
  2159. RtlCopyMemory(Destination->Orderings,
  2160. Source->Orderings,
  2161. Source->Count * sizeof(ARBITER_ORDERING)
  2162. );
  2163. }
  2164. return STATUS_SUCCESS;
  2165. }
  2166. NTSTATUS
  2167. ArbAddOrdering(
  2168. OUT PARBITER_ORDERING_LIST List,
  2169. IN ULONGLONG Start,
  2170. IN ULONGLONG End
  2171. )
  2172. /*++
  2173. Routine Description:
  2174. This routine adds the range Start-End to the end of the ordering list. No
  2175. checking for overlaps or pruning is done (see ArbpPruneOrdering)
  2176. Arguments:
  2177. OrderingList - The list where the range should be added.
  2178. Start - The start of the range to be added.
  2179. End - The end of the range to be added.
  2180. Return Value:
  2181. Status code that indicates whether or not the function was successful.
  2182. --*/
  2183. {
  2184. PAGED_CODE()
  2185. //
  2186. // Validate parameters
  2187. //
  2188. if (End < Start) {
  2189. return STATUS_INVALID_PARAMETER;
  2190. }
  2191. //
  2192. // Check if the buffer is full
  2193. //
  2194. if (List->Count == List->Maximum) {
  2195. PARBITER_ORDERING temp;
  2196. //
  2197. // Out of space - grow the buffer
  2198. //
  2199. temp = ExAllocatePoolWithTag(PagedPool,
  2200. (List->Count + ARBITER_ORDERING_GROW_SIZE) *
  2201. sizeof(ARBITER_ORDERING),
  2202. ARBITER_ORDERING_LIST_TAG
  2203. );
  2204. if (!temp) {
  2205. return STATUS_INSUFFICIENT_RESOURCES;
  2206. }
  2207. //
  2208. // If we had any orderings copy them
  2209. //
  2210. if (List->Orderings) {
  2211. RtlCopyMemory(temp,
  2212. List->Orderings,
  2213. List->Count * sizeof(ARBITER_ORDERING)
  2214. );
  2215. ExFreePool(List->Orderings);
  2216. }
  2217. List->Maximum += ARBITER_ORDERING_GROW_SIZE;
  2218. List->Orderings = temp;
  2219. }
  2220. //
  2221. // Add the entry to the list
  2222. //
  2223. List->Orderings[List->Count].Start = Start;
  2224. List->Orderings[List->Count].End = End;
  2225. List->Count++;
  2226. ASSERT(List->Count <= List->Maximum);
  2227. return STATUS_SUCCESS;
  2228. }
  2229. NTSTATUS
  2230. ArbPruneOrdering(
  2231. IN OUT PARBITER_ORDERING_LIST OrderingList,
  2232. IN ULONGLONG Start,
  2233. IN ULONGLONG End
  2234. )
  2235. /*++
  2236. Routine Description:
  2237. This routine removes the range Start-End from all entries in the ordering
  2238. list, splitting ranges into two or deleting them as necessary.
  2239. Arguments:
  2240. OrderingList - The list to be pruned.
  2241. Start - The start of the range to be deleted.
  2242. End - The end of the range to be deleted.
  2243. Return Value:
  2244. Status code that indicates whether or not the function was successful.
  2245. Note:
  2246. In the comments below *** represents the range Start - End and --- the range
  2247. current->Start - current->End.
  2248. --*/
  2249. {
  2250. NTSTATUS status;
  2251. PARBITER_ORDERING current, currentInsert, newOrdering = NULL, temp = NULL;
  2252. USHORT count;
  2253. PAGED_CODE()
  2254. ASSERT(OrderingList);
  2255. ASSERT(OrderingList->Orderings);
  2256. //
  2257. // Validate parameters
  2258. //
  2259. if (End < Start) {
  2260. status = STATUS_INVALID_PARAMETER;
  2261. goto cleanup;
  2262. }
  2263. //
  2264. // Allocate a buffer big enough for all eventualities
  2265. //
  2266. newOrdering = ExAllocatePoolWithTag(PagedPool,
  2267. (OrderingList->Count * 2 + 1) *
  2268. sizeof(ARBITER_ORDERING),
  2269. ARBITER_ORDERING_LIST_TAG
  2270. );
  2271. if (!newOrdering) {
  2272. status = STATUS_INSUFFICIENT_RESOURCES;
  2273. goto cleanup;
  2274. }
  2275. currentInsert = newOrdering;
  2276. //
  2277. // Do we have a current ordering?
  2278. //
  2279. if (OrderingList->Count > 0) {
  2280. //
  2281. // Iterate through the current ordering and prune accordingly
  2282. //
  2283. FOR_ALL_IN_ARRAY(OrderingList->Orderings, OrderingList->Count, current) {
  2284. if (End < current->Start || Start > current->End) {
  2285. //
  2286. // **** or ****
  2287. // ---- ----
  2288. //
  2289. // We don't overlap so copy the range unchanged
  2290. //
  2291. *currentInsert++ = *current;
  2292. } else if (Start > current->Start) {
  2293. if (End < current->End) {
  2294. //
  2295. // ****
  2296. // --------
  2297. //
  2298. // Split the range into two
  2299. //
  2300. currentInsert->Start = End + 1;
  2301. currentInsert->End = current->End;
  2302. currentInsert++;
  2303. currentInsert->Start = current->Start;
  2304. currentInsert->End = Start - 1;
  2305. currentInsert++;
  2306. } else {
  2307. //
  2308. // **** or ****
  2309. // -------- --------
  2310. //
  2311. // Prune the end of the range
  2312. //
  2313. ASSERT(End >= current->End);
  2314. currentInsert->Start = current->Start;
  2315. currentInsert->End = Start - 1;
  2316. currentInsert++;
  2317. }
  2318. } else {
  2319. ASSERT(Start <= current->Start);
  2320. if (End < current->End) {
  2321. //
  2322. // **** or ****
  2323. // -------- --------
  2324. //
  2325. // Prune the start of the range
  2326. //
  2327. currentInsert->Start = End + 1;
  2328. currentInsert->End = current->End;
  2329. currentInsert++;
  2330. } else {
  2331. ASSERT(End >= current->End);
  2332. //
  2333. // ******** or ********
  2334. // ---- --------
  2335. //
  2336. // Don't copy the range (ie. Delete it)
  2337. //
  2338. }
  2339. }
  2340. }
  2341. }
  2342. ASSERT(currentInsert - newOrdering >= 0);
  2343. count = (USHORT)(currentInsert - newOrdering);
  2344. //
  2345. // Check if we have any orderings left
  2346. //
  2347. if (count > 0) {
  2348. if (count > OrderingList->Maximum) {
  2349. //
  2350. // There isn't enough space so allocate a new buffer
  2351. //
  2352. temp =
  2353. ExAllocatePoolWithTag(PagedPool,
  2354. count * sizeof(ARBITER_ORDERING),
  2355. ARBITER_ORDERING_LIST_TAG
  2356. );
  2357. if (!temp) {
  2358. status = STATUS_INSUFFICIENT_RESOURCES;
  2359. goto cleanup;
  2360. }
  2361. if (OrderingList->Orderings) {
  2362. ExFreePool(OrderingList->Orderings);
  2363. }
  2364. OrderingList->Orderings = temp;
  2365. OrderingList->Maximum = count;
  2366. }
  2367. //
  2368. // Copy the new ordering
  2369. //
  2370. RtlCopyMemory(OrderingList->Orderings,
  2371. newOrdering,
  2372. count * sizeof(ARBITER_ORDERING)
  2373. );
  2374. }
  2375. //
  2376. // Free our temporary buffer
  2377. //
  2378. ExFreePool(newOrdering);
  2379. OrderingList->Count = count;
  2380. return STATUS_SUCCESS;
  2381. cleanup:
  2382. if (newOrdering) {
  2383. ExFreePool(newOrdering);
  2384. }
  2385. if (temp) {
  2386. ExFreePool(temp);
  2387. }
  2388. return status;
  2389. }
  2390. VOID
  2391. ArbFreeOrderingList(
  2392. IN PARBITER_ORDERING_LIST List
  2393. )
  2394. /*++
  2395. Routine Description:
  2396. Frees storage associated with an ordering list.
  2397. Reverses ArbInitializeOrderingList.
  2398. Arguments:
  2399. List - The list to be fred
  2400. Return Value:
  2401. None
  2402. --*/
  2403. {
  2404. PAGED_CODE();
  2405. if (List->Orderings) {
  2406. ASSERT(List->Maximum);
  2407. ExFreePool(List->Orderings);
  2408. }
  2409. List->Count = 0;
  2410. List->Maximum = 0;
  2411. List->Orderings = NULL;
  2412. }
  2413. BOOLEAN
  2414. ArbOverrideConflict(
  2415. IN PARBITER_INSTANCE Arbiter,
  2416. IN PARBITER_ALLOCATION_STATE State
  2417. )
  2418. /*++
  2419. Routine Description:
  2420. This is the default implementation of override conflict which
  2421. Arguments:
  2422. Arbiter - The instance data of the arbiter who was called.
  2423. State - The state of the current arbitration.
  2424. Return Value:
  2425. TRUE if the conflict is allowable, false otherwise
  2426. --*/
  2427. {
  2428. PRTL_RANGE current;
  2429. RTL_RANGE_LIST_ITERATOR iterator;
  2430. BOOLEAN ok = FALSE;
  2431. PAGED_CODE();
  2432. if (!(State->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_FIXED)) {
  2433. return FALSE;
  2434. }
  2435. FOR_ALL_RANGES(Arbiter->PossibleAllocation, &iterator, current) {
  2436. //
  2437. // Only test the overlapping ones
  2438. //
  2439. if (INTERSECT(current->Start, current->End, State->CurrentMinimum, State->CurrentMaximum)) {
  2440. //
  2441. // Check if we should ignore the range because of its attributes
  2442. //
  2443. if (current->Attributes & State->RangeAvailableAttributes) {
  2444. //
  2445. // We DON'T set ok to true because we are just ignoring the range,
  2446. // as RtlFindRange would have and thus it can't be the cause of
  2447. // RtlFindRange failing, so ignoring it can't fix the conflict.
  2448. //
  2449. continue;
  2450. }
  2451. //
  2452. // Check if we are conflicting with ourselves AND the conflicting range
  2453. // is a fixed requirement
  2454. //
  2455. if (current->Owner == State->Entry->PhysicalDeviceObject
  2456. && State->CurrentAlternative->Flags & ARBITER_ALTERNATIVE_FLAG_FIXED) {
  2457. State->Start=State->CurrentMinimum;
  2458. State->End=State->CurrentMaximum;
  2459. ok = TRUE;
  2460. continue;
  2461. }
  2462. //
  2463. // The conflict is still valid
  2464. //
  2465. return FALSE;
  2466. }
  2467. }
  2468. return ok;
  2469. }
  2470. VOID
  2471. ArbpUpdatePriority(
  2472. PARBITER_INSTANCE Arbiter,
  2473. PARBITER_ALTERNATIVE Alternative
  2474. )
  2475. /*++
  2476. Routine Description:
  2477. This routine updates the priority of an arbiter alternative.
  2478. Arguments:
  2479. Arbiter - The arbiter we are operating on
  2480. Alternative - The alternative currently being considered
  2481. Return Value:
  2482. Status code that indicates whether or not the function was successful.
  2483. Note:
  2484. The priorities are a LONG values organised as:
  2485. <------Preferred priorities-----> <-----Ordinary Priorities----->
  2486. MINLONG--------------------------0-----------------------------MAXLONG
  2487. ^ ^ ^ ^
  2488. | | | |
  2489. NULL PREFERRED_RESERVED | |
  2490. RESERVED |
  2491. EXHAUSTED
  2492. An ordinary priority is calculated the (index + 1) of the next ordering it
  2493. intersects with (and has enough space for an allocation).
  2494. A preferred priority is the ordinary priority * - 1
  2495. In this way by examining each of the alternatives in priority order (lowest
  2496. first) we achieve the desired allocation order of:
  2497. (1) Preferred alternative with non-reserved resources
  2498. (2) Alternatives with non-reserved resources
  2499. (3) Preferred reserved resources
  2500. (4) Reserved Resources
  2501. MAXLONG the worst priority indicates that there are no more allocation ranges
  2502. left.
  2503. --*/
  2504. {
  2505. PARBITER_ORDERING ordering;
  2506. BOOLEAN preferred;
  2507. LONG priority;
  2508. PAGED_CODE();
  2509. priority = Alternative->Priority;
  2510. //
  2511. // If we have already tried the reserved resources then we are out of luck!
  2512. //
  2513. if (priority == ARBITER_PRIORITY_RESERVED
  2514. || priority == ARBITER_PRIORITY_PREFERRED_RESERVED) {
  2515. Alternative->Priority = ARBITER_PRIORITY_EXHAUSTED;
  2516. return;
  2517. }
  2518. //
  2519. // Check if this is a preferred value - we treat them specially
  2520. //
  2521. preferred = Alternative->Descriptor->Option & IO_RESOURCE_PREFERRED;
  2522. //
  2523. // If priority is NULL then we haven't started calculating one so we
  2524. // should start the search from the initial ordering
  2525. //
  2526. if (priority == ARBITER_PRIORITY_NULL) {
  2527. ordering = Arbiter->OrderingList.Orderings;
  2528. } else {
  2529. //
  2530. // If we are a fixed resource then there is no point
  2531. // in trying to find another range - it will be the
  2532. // same and thus still conflict. Mark this alternative as
  2533. // exhausted
  2534. //
  2535. if (Alternative->Flags & ARBITER_ALTERNATIVE_FLAG_FIXED) {
  2536. Alternative->Priority = ARBITER_PRIORITY_EXHAUSTED;
  2537. return;
  2538. }
  2539. ASSERT(ORDERING_INDEX_FROM_PRIORITY(Alternative->Priority) <
  2540. Arbiter->OrderingList.Count);
  2541. ordering = &Arbiter->OrderingList.Orderings
  2542. [ORDERING_INDEX_FROM_PRIORITY(Alternative->Priority) + 1];
  2543. }
  2544. //
  2545. // Now find the first member of the assignent ordering for this arbiter
  2546. // where we have an overlap big enough
  2547. //
  2548. FOR_REST_IN_ARRAY(Arbiter->OrderingList.Orderings,
  2549. Arbiter->OrderingList.Count,
  2550. ordering) {
  2551. //
  2552. // Is the ordering applicable?
  2553. //
  2554. if (INTERSECT(Alternative->Minimum, Alternative->Maximum,
  2555. ordering->Start, ordering->End)
  2556. && INTERSECT_SIZE(Alternative->Minimum, Alternative->Maximum,
  2557. ordering->Start,ordering->End) >= Alternative->Length) {
  2558. //
  2559. // This is out guy, calculate his priority
  2560. //
  2561. Alternative->Priority = (LONG)(ordering - Arbiter->OrderingList.Orderings + 1);
  2562. //
  2563. // Preferred priorities are -ve
  2564. //
  2565. if (preferred) {
  2566. Alternative->Priority *= -1;
  2567. }
  2568. return;
  2569. }
  2570. }
  2571. //
  2572. // We have runout of non-reserved resources so try the reserved ones
  2573. //
  2574. if (preferred) {
  2575. Alternative->Priority = ARBITER_PRIORITY_PREFERRED_RESERVED;
  2576. } else {
  2577. Alternative->Priority = ARBITER_PRIORITY_RESERVED;
  2578. }
  2579. }
  2580. NTSTATUS
  2581. ArbAddReserved(
  2582. IN PARBITER_INSTANCE Arbiter,
  2583. IN PIO_RESOURCE_DESCRIPTOR Requirement OPTIONAL,
  2584. IN PCM_PARTIAL_RESOURCE_DESCRIPTOR Resource OPTIONAL
  2585. )
  2586. {
  2587. PAGED_CODE();
  2588. return STATUS_NOT_SUPPORTED;
  2589. }
  2590. BOOLEAN
  2591. ArbpQueryConflictCallback(
  2592. IN PVOID Context,
  2593. IN PRTL_RANGE Range
  2594. )
  2595. /*++
  2596. Routine Description:
  2597. This call back is called from FindSuitableRange (via RtlFindRange) when we
  2598. encounter an conflicting range.
  2599. Arguments:
  2600. Context - Actually a PRTL_RANGE * where we store the range we conflicted
  2601. with.
  2602. Range - The range we conflict with.
  2603. Return Value:
  2604. FALSE
  2605. --*/
  2606. {
  2607. PRTL_RANGE *conflictingRange = (PRTL_RANGE*)Context;
  2608. PAGED_CODE();
  2609. ARB_PRINT(2,("Possible conflict: (%p) 0x%I64x-0x%I64x Owner: %p",
  2610. Range,
  2611. Range->Start,
  2612. Range->End,
  2613. Range->Owner
  2614. ));
  2615. //
  2616. // Remember the conflicting range
  2617. //
  2618. *conflictingRange = Range;
  2619. //
  2620. // We want to allow the rest of FindSuitableRange to determine if this really
  2621. // is a conflict.
  2622. //
  2623. return FALSE;
  2624. }
  2625. NTSTATUS
  2626. ArbQueryConflict(
  2627. IN PARBITER_INSTANCE Arbiter,
  2628. IN PDEVICE_OBJECT PhysicalDeviceObject,
  2629. IN PIO_RESOURCE_DESCRIPTOR ConflictingResource,
  2630. OUT PULONG ConflictCount,
  2631. OUT PARBITER_CONFLICT_INFO *Conflicts
  2632. )
  2633. /*++
  2634. Routine Description:
  2635. This routine examines the arbiter state and returns a list of devices that
  2636. conflict with ConflictingResource
  2637. Arguments:
  2638. Arbiter - The arbiter to examine conflicts in
  2639. ConflictingResource - The resource we want to know the conflicts with
  2640. ConflictCount - On success contains the number of conflicts detected
  2641. ConflictList - On success contains a pointer to an array of conflicting
  2642. devices
  2643. Return Value:
  2644. Status code that indicates whether or not the function was successful.
  2645. --*/
  2646. {
  2647. //
  2648. // NTRAID #98568 - 2000/03/31 - andrewth
  2649. // ArbQueryConflict needs to be redesigned
  2650. //
  2651. NTSTATUS status;
  2652. RTL_RANGE_LIST backupAllocation;
  2653. BOOLEAN backedUp = FALSE;
  2654. ARBITER_LIST_ENTRY entry;
  2655. ARBITER_ALLOCATION_STATE state;
  2656. ARBITER_ALTERNATIVE alternative;
  2657. ULONG count = 0, size = 10;
  2658. PRTL_RANGE conflictingRange;
  2659. PARBITER_CONFLICT_INFO conflictInfo = NULL;
  2660. PVOID savedContext;
  2661. PRTL_CONFLICT_RANGE_CALLBACK savedCallback;
  2662. ULONG sz;
  2663. PAGED_CODE();
  2664. ASSERT(PhysicalDeviceObject);
  2665. ASSERT(ConflictingResource);
  2666. ASSERT(ConflictCount);
  2667. ASSERT(Conflicts);
  2668. //
  2669. // Set up our conflict callback
  2670. //
  2671. savedCallback = Arbiter->ConflictCallback;
  2672. savedContext = Arbiter->ConflictCallbackContext;
  2673. Arbiter->ConflictCallback = ArbpQueryConflictCallback;
  2674. Arbiter->ConflictCallbackContext = &conflictingRange;
  2675. //
  2676. // If there is a transaction in progress then we need to backup the
  2677. // the possible allocation so we can restore it when we are done.
  2678. //
  2679. if (Arbiter->TransactionInProgress) {
  2680. RtlInitializeRangeList(&backupAllocation);
  2681. status = RtlCopyRangeList(&backupAllocation, Arbiter->PossibleAllocation);
  2682. if (!NT_SUCCESS(status)) {
  2683. goto cleanup;
  2684. }
  2685. RtlFreeRangeList(Arbiter->PossibleAllocation);
  2686. backedUp = TRUE;
  2687. }
  2688. //
  2689. // Fake up the allocation state
  2690. //
  2691. status = RtlCopyRangeList(Arbiter->PossibleAllocation, Arbiter->Allocation);
  2692. if (!NT_SUCCESS(status)) {
  2693. goto cleanup;
  2694. }
  2695. status = ArbpBuildAlternative(Arbiter, ConflictingResource, &alternative);
  2696. if (!NT_SUCCESS(status)) {
  2697. goto cleanup;
  2698. }
  2699. RtlZeroMemory(&state, sizeof(ARBITER_ALLOCATION_STATE));
  2700. state.Start = alternative.Minimum;
  2701. state.End = alternative.Maximum;
  2702. state.CurrentMinimum = state.Start;
  2703. state.CurrentMaximum = state.End;
  2704. state.CurrentAlternative = &alternative;
  2705. state.AlternativeCount = 1;
  2706. state.Alternatives = &alternative;
  2707. state.Flags = ARBITER_STATE_FLAG_CONFLICT;
  2708. state.Entry = &entry;
  2709. RtlZeroMemory(&entry, sizeof(ARBITER_LIST_ENTRY));
  2710. entry.RequestSource = ArbiterRequestPnpEnumerated;
  2711. entry.PhysicalDeviceObject = PhysicalDeviceObject;
  2712. if (!NT_SUCCESS(IoGetDeviceProperty(PhysicalDeviceObject,DevicePropertyLegacyBusType,sizeof(entry.InterfaceType),&entry.InterfaceType,&sz))) {
  2713. entry.InterfaceType = Isa; // not what I want to do! However this has the right effect - good enough for conflict detection
  2714. }
  2715. if (!NT_SUCCESS(IoGetDeviceProperty(PhysicalDeviceObject,DevicePropertyBusNumber,sizeof(entry.InterfaceType),&entry.BusNumber,&sz))) {
  2716. entry.BusNumber = 0; // not what I want to do! However this has the right effect - good enough for conflict detection
  2717. }
  2718. //
  2719. // Initialize the return buffers
  2720. //
  2721. conflictInfo = ExAllocatePoolWithTag(PagedPool,
  2722. size * sizeof(ARBITER_CONFLICT_INFO),
  2723. ARBITER_CONFLICT_INFO_TAG
  2724. );
  2725. if (!conflictInfo) {
  2726. status = STATUS_INSUFFICIENT_RESOURCES;
  2727. goto cleanup;
  2728. }
  2729. //
  2730. // Perform any necessary preprocessing
  2731. //
  2732. status = Arbiter->PreprocessEntry(Arbiter, &state);
  2733. if (!NT_SUCCESS(status)) {
  2734. goto cleanup;
  2735. }
  2736. //
  2737. // Remove self from list of possible allocations
  2738. // status may be set, but can be ignored
  2739. // we take ourself out of test completely, so that a user can
  2740. // pick new values in context of rest of the world
  2741. // if we decide to use RtlDeleteRange instead
  2742. // make sure we do it for every alias formed in PreprocessEntry
  2743. //
  2744. status = RtlDeleteOwnersRanges(Arbiter->PossibleAllocation,
  2745. state.Entry->PhysicalDeviceObject
  2746. );
  2747. //
  2748. // Keep trying to find a suitable range and each time we fail remember why.
  2749. //
  2750. conflictingRange = NULL;
  2751. state.CurrentMinimum = state.Start;
  2752. state.CurrentMaximum = state.End;
  2753. while (!Arbiter->FindSuitableRange(Arbiter, &state)) {
  2754. if (count == size) {
  2755. //
  2756. // We need to resize the return buffer
  2757. //
  2758. PARBITER_CONFLICT_INFO temp = conflictInfo;
  2759. size += 5;
  2760. conflictInfo =
  2761. ExAllocatePoolWithTag(PagedPool,
  2762. size * sizeof(ARBITER_CONFLICT_INFO),
  2763. ARBITER_CONFLICT_INFO_TAG
  2764. );
  2765. if (!conflictInfo) {
  2766. status = STATUS_INSUFFICIENT_RESOURCES;
  2767. conflictInfo = temp;
  2768. goto cleanup;
  2769. }
  2770. RtlCopyMemory(conflictInfo,
  2771. temp,
  2772. count * sizeof(ARBITER_CONFLICT_INFO)
  2773. );
  2774. ExFreePool(temp);
  2775. }
  2776. if (conflictingRange != NULL) {
  2777. conflictInfo[count].OwningObject = conflictingRange->Owner;
  2778. conflictInfo[count].Start = conflictingRange->Start;
  2779. conflictInfo[count].End = conflictingRange->End;
  2780. count++;
  2781. //
  2782. // Delete the range we conflicted with so we don't loop forever
  2783. //
  2784. #if 0
  2785. status = RtlDeleteRange(Arbiter->PossibleAllocation,
  2786. conflictingRange->Start,
  2787. conflictingRange->End,
  2788. conflictingRange->Owner
  2789. );
  2790. #endif
  2791. status = RtlDeleteOwnersRanges(Arbiter->PossibleAllocation,
  2792. conflictingRange->Owner
  2793. );
  2794. if (!NT_SUCCESS(status)) {
  2795. goto cleanup;
  2796. }
  2797. } else {
  2798. //
  2799. // someone isn't playing by the rules (such as ACPI!)
  2800. //
  2801. ARB_PRINT(0,("Conflict detected - but someone hasn't set conflicting info\n"));
  2802. conflictInfo[count].OwningObject = NULL;
  2803. conflictInfo[count].Start = (ULONGLONG)0;
  2804. conflictInfo[count].End = (ULONGLONG)(-1);
  2805. count++;
  2806. //
  2807. // we daren't continue at risk of looping forever
  2808. //
  2809. break;
  2810. }
  2811. //
  2812. // reset for next round
  2813. //
  2814. conflictingRange = NULL;
  2815. state.CurrentMinimum = state.Start;
  2816. state.CurrentMaximum = state.End;
  2817. }
  2818. RtlFreeRangeList(Arbiter->PossibleAllocation);
  2819. if (Arbiter->TransactionInProgress) {
  2820. status = RtlCopyRangeList(Arbiter->PossibleAllocation, &backupAllocation);
  2821. if (!NT_SUCCESS(status)) {
  2822. goto cleanup;
  2823. }
  2824. RtlFreeRangeList(&backupAllocation);
  2825. }
  2826. Arbiter->ConflictCallback = savedCallback;
  2827. Arbiter->ConflictCallbackContext = savedContext;
  2828. *Conflicts = conflictInfo;
  2829. *ConflictCount = count;
  2830. return STATUS_SUCCESS;
  2831. cleanup:
  2832. if (conflictInfo) {
  2833. ExFreePool(conflictInfo);
  2834. }
  2835. RtlFreeRangeList(Arbiter->PossibleAllocation);
  2836. if (Arbiter->TransactionInProgress && backedUp) {
  2837. status = RtlCopyRangeList(Arbiter->PossibleAllocation, &backupAllocation);
  2838. RtlFreeRangeList(&backupAllocation);
  2839. }
  2840. Arbiter->ConflictCallback = savedCallback;
  2841. Arbiter->ConflictCallbackContext = savedContext;
  2842. *Conflicts = NULL;
  2843. return status;
  2844. }
  2845. NTSTATUS
  2846. ArbStartArbiter(
  2847. IN PARBITER_INSTANCE Arbiter,
  2848. IN PCM_RESOURCE_LIST StartResources
  2849. )
  2850. /*++
  2851. Routine Description:
  2852. This function is called by the driver that implements the arbiter once
  2853. it has been started and knowns what resources it can allocate to its
  2854. children.
  2855. It will eventually initialize the range lists correctly but for
  2856. now it is just an overloadable place holder as that work is done elsewhere.
  2857. Parameters:
  2858. Arbiter - The instance of the arbiter being called.
  2859. Return Value:
  2860. Status code that indicates whether or not the function was successful.
  2861. --*/
  2862. {
  2863. PAGED_CODE();
  2864. return STATUS_SUCCESS;
  2865. }
  2866. BOOLEAN
  2867. ArbShareDriverExclusive(
  2868. IN PARBITER_INSTANCE Arbiter,
  2869. IN PARBITER_ALLOCATION_STATE State
  2870. )
  2871. /*++
  2872. Routine Description:
  2873. This routine implements support for CmResourceShareDriverExclusive disposition
  2874. by overriding conflict if the owner and request share at least one common
  2875. driver.
  2876. Arguments:
  2877. Arbiter - The instance data of the arbiter who was called.
  2878. State - The state of the current arbitration.
  2879. Return Value:
  2880. TRUE if the conflict is allowable, false otherwise
  2881. --*/
  2882. {
  2883. PRTL_RANGE current;
  2884. RTL_RANGE_LIST_ITERATOR iterator;
  2885. PDEVICE_OBJECT owner, other;
  2886. ULONG enumeratorNameLength;
  2887. WCHAR enumeratorName[sizeof(REGSTR_KEY_ROOTENUM) / sizeof(WCHAR)];
  2888. NTSTATUS status;
  2889. BOOLEAN isRootEnumerated;
  2890. PAGED_CODE();
  2891. isRootEnumerated = FALSE;
  2892. status = IoGetDeviceProperty(
  2893. State->Entry->PhysicalDeviceObject,
  2894. DevicePropertyEnumeratorName,
  2895. sizeof(enumeratorName),
  2896. enumeratorName,
  2897. &enumeratorNameLength);
  2898. if (NT_SUCCESS(status)) {
  2899. if (_wcsicmp(enumeratorName, REGSTR_KEY_ROOTENUM) == 0) {
  2900. isRootEnumerated = TRUE;
  2901. }
  2902. }
  2903. FOR_ALL_RANGES(Arbiter->PossibleAllocation, &iterator, current) {
  2904. //
  2905. // Only test the overlapping ones
  2906. //
  2907. if (INTERSECT(current->Start, current->End, State->CurrentMinimum, State->CurrentMaximum)) {
  2908. //
  2909. // Check if we should ignore the range because of its attributes
  2910. //
  2911. if (current->Attributes & State->RangeAvailableAttributes) {
  2912. //
  2913. // We DON'T set ok to true because we are just ignoring the range,
  2914. // as RtlFindRange would have and thus it can't be the cause of
  2915. // RtlFindRange failing, so ignoring it can't fix the conflict.
  2916. //
  2917. continue;
  2918. }
  2919. if (State->CurrentAlternative->Descriptor->ShareDisposition != CmResourceShareDriverExclusive &&
  2920. !(current->Attributes & ARBITER_RANGE_SHARE_DRIVER_EXCLUSIVE)) {
  2921. continue;
  2922. }
  2923. if (!current->Owner) {
  2924. continue;
  2925. }
  2926. //
  2927. // Special case ROOT enumerated devices.
  2928. //
  2929. if (isRootEnumerated) {
  2930. status = IoGetDeviceProperty(
  2931. current->Owner,
  2932. DevicePropertyEnumeratorName,
  2933. sizeof(enumeratorName),
  2934. enumeratorName,
  2935. &enumeratorNameLength);
  2936. if (NT_SUCCESS(status)) {
  2937. if (_wcsicmp(enumeratorName, REGSTR_KEY_ROOTENUM) != 0) {
  2938. isRootEnumerated = FALSE;
  2939. }
  2940. }
  2941. }
  2942. //
  2943. // If both devices are ROOT enumerated, override the conflict.
  2944. //
  2945. if (isRootEnumerated) {
  2946. ARB_PRINT(2,
  2947. ("Overriding conflict on IRQ %04x for driver %wZ\n",
  2948. (ULONG)State->Start,
  2949. &owner->DriverObject->DriverName
  2950. ));
  2951. State->Start=State->CurrentMinimum;
  2952. State->End=State->CurrentMaximum;
  2953. if (State->CurrentAlternative->Descriptor->ShareDisposition == CmResourceShareDriverExclusive) {
  2954. State->RangeAttributes |= ARBITER_RANGE_SHARE_DRIVER_EXCLUSIVE;
  2955. }
  2956. return TRUE;
  2957. }
  2958. //
  2959. // Check if there is a common driver in the two stacks ignoring the
  2960. // one for the PDO.
  2961. //
  2962. owner = ((PDEVICE_OBJECT)(current->Owner))->AttachedDevice;
  2963. while (owner) {
  2964. other = (PDEVICE_OBJECT)(State->Entry->PhysicalDeviceObject)->AttachedDevice;
  2965. while (other) {
  2966. if (owner->DriverObject == other->DriverObject) {
  2967. ARB_PRINT(2,
  2968. ("Overriding conflict on IRQ %04x for driver %wZ\n",
  2969. (ULONG)State->Start,
  2970. &owner->DriverObject->DriverName
  2971. ));
  2972. State->Start=State->CurrentMinimum;
  2973. State->End=State->CurrentMaximum;
  2974. if (State->CurrentAlternative->Descriptor->ShareDisposition == CmResourceShareDriverExclusive) {
  2975. State->RangeAttributes |= ARBITER_RANGE_SHARE_DRIVER_EXCLUSIVE;
  2976. }
  2977. return TRUE;
  2978. }
  2979. other = other->AttachedDevice;
  2980. }
  2981. owner = owner->AttachedDevice;
  2982. }
  2983. }
  2984. }
  2985. //
  2986. // The conflict is still valid
  2987. //
  2988. return FALSE;
  2989. }
  2990. #if DBG
  2991. VOID
  2992. ArbpIndent(
  2993. IN ULONG Count
  2994. )
  2995. {
  2996. UCHAR spaces[80];
  2997. ASSERT(Count <= 80);
  2998. RtlFillMemory(spaces, Count, '*');
  2999. spaces[Count] = 0;
  3000. DbgPrint("%s", spaces);
  3001. }
  3002. #endif