MultiIndexPool constructor

MultiIndexPool({
  1. required Logic clk,
  2. required Logic reset,
  3. required Logic quiesce,
  4. required List<Logic> allocate,
  5. required List<Logic> release,
  6. required List<Logic> releaseIndices,
  7. required Logic restore,
  8. required Logic restoreMask,
  9. required int capacity,
  10. List<int>? initiallyAvailableIndices,
  11. List<Logic>? allocationRequests,
  12. List<Logic>? allocationMasks,
  13. List<Logic>? allocationWithdraws,
  14. IndexAllocationGenerator allocationGenerator = lowestFreeIndexAllocationGenerator,
  15. String allocationPolicyName = 'lowestFree',
  16. IndexAllocationSelectionMode selectionMode = IndexAllocationSelectionMode.normalized,
  17. RegisterFileFunctor? storageImplementation,
  18. String name = 'multi_index_pool',
})

Creates a multi-lane index pool driven by explicit actions.

allocate has one bit per allocation lane. release has one bit per release lane, each with an indexWidth-bit entry of releaseIndices. restoreMask has one bit per index.

allocationGenerator is instantiated independently for each lane over a candidate bitmap with earlier offers removed. Its combinational grant must not depend on the supplied accepted signal; that signal is only for advancing policy state on a clock edge.

storageImplementation optionally backs ownership with a register file. Retained offers remain flops. The default is synthesizable flops; a model functor selects a simulation-only implementation.

Implementation

MultiIndexPool(
    {required Logic clk,
    required Logic reset,
    required Logic quiesce,
    required List<Logic> allocate,
    required List<Logic> release,
    required List<Logic> releaseIndices,
    required Logic restore,
    required Logic restoreMask,
    required this.capacity,
    List<int>? initiallyAvailableIndices,
    List<Logic>? allocationRequests,
    List<Logic>? allocationMasks,
    List<Logic>? allocationWithdraws,
    IndexAllocationGenerator allocationGenerator =
        lowestFreeIndexAllocationGenerator,
    this.allocationPolicyName = 'lowestFree',
    this.selectionMode = IndexAllocationSelectionMode.normalized,
    RegisterFileFunctor? storageImplementation,
    super.name = 'multi_index_pool'})
    : indexWidth = max(1, capacity.log2Ceil),
      allocationLaneCount = allocate.length,
      releaseLaneCount = release.length,
      super(
          definitionName: _multiIndexPoolCoreDefinitionName(
              capacity,
              allocate.length,
              release.length,
              initiallyAvailableIndices,
              allocationPolicyName,
              allocationRequests != null,
              allocationMasks != null,
              allocationWithdraws != null,
              selectionMode,
              storageImplementation?.identity)) {
  if (capacity < 1 || allocationLaneCount < 1 || releaseLaneCount < 1) {
    throw ArgumentError(
        'Capacity and allocation and release lane counts must be positive.');
  }
  if (selectionMode == IndexAllocationSelectionMode.scalarCompatibility &&
      (allocationLaneCount != 1 ||
          releaseLaneCount != 1 ||
          allocationRequests != null ||
          allocationMasks != null ||
          allocationWithdraws != null)) {
    throw ArgumentError(
        'Scalar selection compatibility requires one allocation and release '
        'lane without request, mask, or withdrawal sidebands.');
  }
  if (!RegExp(r'^[A-Za-z][A-Za-z0-9_]*$').hasMatch(allocationPolicyName)) {
    throw ArgumentError.value(allocationPolicyName, 'allocationPolicyName',
        'Must be a valid SystemVerilog identifier fragment.');
  }
  if (!identical(allocationGenerator, lowestFreeIndexAllocationGenerator) &&
      allocationPolicyName == 'lowestFree') {
    throw ArgumentError.value(allocationPolicyName, 'allocationPolicyName',
        'A custom allocation generator requires a distinct policy name.');
  }
  final initialAvailability = initiallyAvailableIndices ??
      List<int>.generate(capacity, (index) => index);
  if (initialAvailability.toSet().length != initialAvailability.length ||
      initialAvailability.any((index) => index < 0 || index >= capacity)) {
    throw ArgumentError.value(
        initiallyAvailableIndices,
        'initiallyAvailableIndices',
        'Must contain unique indices in the configured capacity.');
  }
  if (releaseIndices.length != releaseLaneCount ||
      releaseIndices.any((index) => index.width != indexWidth) ||
      restoreMask.width != capacity) {
    throw ArgumentError(
        'Each release lane requires an index that represents every index, '
        'and the restore mask must contain one bit per index.');
  }
  if (allocationRequests != null &&
      (allocationRequests.length != allocationLaneCount ||
          allocationRequests.any((request) => request.width != 1))) {
    throw ArgumentError(
        'allocationRequests must contain one bit per allocation lane.');
  }
  if (allocationMasks != null &&
      (allocationMasks.length != allocationLaneCount ||
          allocationMasks.any((mask) => mask.width != capacity))) {
    throw ArgumentError(
        'allocationMasks must contain one capacity-wide mask per lane.');
  }
  if (allocationWithdraws != null &&
      (allocationWithdraws.length != allocationLaneCount ||
          allocationWithdraws.any((withdraw) => withdraw.width != 1))) {
    throw ArgumentError(
        'allocationWithdraws must contain one bit per allocation lane.');
  }

  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localQuiesce = addInput('quiesce', quiesce);
  final localRequests = allocationRequests == null
      ? null
      : [
          for (var lane = 0; lane < allocationLaneCount; lane++)
            addInput('allocationRequest$lane', allocationRequests[lane]),
        ];
  final localMasks = allocationMasks == null
      ? null
      : [
          for (var lane = 0; lane < allocationLaneCount; lane++)
            addInput('allocationMask$lane', allocationMasks[lane],
                width: capacity),
        ];
  final localWithdraws = allocationWithdraws == null
      ? null
      : [
          for (var lane = 0; lane < allocationLaneCount; lane++)
            addInput('allocationWithdraw$lane', allocationWithdraws[lane]),
        ];
  final localAllocate = [
    for (var lane = 0; lane < allocationLaneCount; lane++)
      addInput('allocate$lane', allocate[lane]),
  ];
  final localRelease = [
    for (var lane = 0; lane < releaseLaneCount; lane++)
      addInput('release$lane', release[lane]),
  ];
  final localReleaseIndices = [
    for (var lane = 0; lane < releaseLaneCount; lane++)
      addInput('releaseIndex$lane', releaseIndices[lane], width: indexWidth),
  ];
  final localRestore = addInput('restore', restore);
  final localRestoreMask =
      addInput('restoreMask', restoreMask, width: capacity);

  allocationValid = [
    for (var lane = 0; lane < allocationLaneCount; lane++)
      addOutput('allocationValid$lane'),
  ];
  allocationIndices = [
    for (var lane = 0; lane < allocationLaneCount; lane++)
      addOutput('allocationIndex$lane', width: indexWidth),
  ];
  addOutput('canRestore');
  final countWidth = max(1, (capacity + 1).log2Ceil);
  addOutput('allocatedMask', width: capacity);
  addOutput('allocatedCount', width: countWidth);
  addOutput('availableCount', width: countWidth);
  addOutput('exhausted');
  addOutput('quiesced');
  addOutput('retainedAllocationLanes', width: allocationLaneCount);
  addOutput('invalidReleases', width: releaseLaneCount);
  addOutput('doubleReleases', width: releaseLaneCount);
  addOutput('invalidAllocationSelections', width: allocationLaneCount);
  allocatedMasksAfterAllocationPrefixes = [
    for (var prefix = 0; prefix <= allocationLaneCount; prefix++)
      addOutput('allocatedMaskAfterAllocationPrefix$prefix', width: capacity)
  ];

  final allocationTaken = [
    for (var lane = 0; lane < allocationLaneCount; lane++)
      (localAllocate[lane] & allocationValid[lane])
          .named('${name}_allocation_${lane}_taken'),
  ];
  final allocated = List.generate(
      capacity, (index) => Logic(name: '${name}_allocated_$index'));
  final offerRetained = List.generate(allocationLaneCount,
      (lane) => Logic(name: '${name}_offer_${lane}_retained'));
  final retainedIndex = List.generate(
      allocationLaneCount,
      (lane) =>
          Logic(name: '${name}_retained_index_$lane', width: indexWidth));
  final retainedActive = [
    for (var lane = 0; lane < allocationLaneCount; lane++)
      (offerRetained[lane] & ~(localWithdraws?[lane] ?? Const(0)))
          .named('${name}_offer_${lane}_active'),
  ];

  final capacityFillsIndexSpace = capacity == (1 << indexWidth);
  var ownershipAfterReleases = List<Logic>.of(allocated);
  final invalidReleaseLanes = <Logic>[];
  final doubleReleaseLanes = <Logic>[];
  for (var lane = 0; lane < releaseLaneCount; lane++) {
    final offered = localRelease[lane];
    final releaseIndex = localReleaseIndices[lane];
    final inRange = capacityFillsIndexSpace
        ? Const(1)
        : releaseIndex
            .lt(Const(capacity, width: indexWidth))
            .named('${name}_release_${lane}_in_range');
    Logic wasAllocated = Const(0);
    for (var index = capacity - 1; index >= 0; index--) {
      wasAllocated = mux(releaseIndex.eq(index),
          ownershipAfterReleases[index], wasAllocated);
    }
    final valid = (offered & inRange & wasAllocated)
        .named('${name}_release_${lane}_valid');
    invalidReleaseLanes.add(offered & ~inRange);
    doubleReleaseLanes.add(offered & inRange & ~wasAllocated);
    ownershipAfterReleases = [
      for (var index = 0; index < capacity; index++)
        (ownershipAfterReleases[index] & ~(valid & releaseIndex.eq(index)))
            .named('${name}_owned_${index}_after_release_$lane')
    ];
  }

  var candidates = [
    for (var index = 0; index < capacity; index++)
      (~ownershipAfterReleases[index])
          .named('${name}_candidate_after_releases_$index')
  ];
  for (var lane = 0;
      selectionMode == IndexAllocationSelectionMode.normalized &&
          lane < allocationLaneCount;
      lane++) {
    candidates = [
      for (var index = 0; index < capacity; index++)
        (candidates[index] &
                ~(retainedActive[lane] & retainedIndex[lane].eq(index)))
            .named('${name}_candidate_${index}_without_retained_$lane')
    ];
  }

  final invalidSelections = <Logic>[];
  for (var lane = 0; lane < allocationLaneCount; lane++) {
    final laneRequested = localRequests?[lane] ?? Const(1);
    final eligibleCandidates = [
      for (var index = 0; index < capacity; index++)
        (candidates[index] & (localMasks?[lane][index] ?? Const(1)))
            .named('${name}_lane_${lane}_eligible_$index'),
    ];
    final generated = allocationGenerator(
        available: eligibleCandidates,
        accepted: allocationTaken[lane],
        clk: localClk,
        reset: localReset,
        name: '${name}_allocation_${lane}_grant');
    if (generated.length != capacity ||
        generated.any((grant) => grant.width != 1)) {
      throw ArgumentError.value(allocationGenerator, 'allocationGenerator',
          'Must return one one-bit grant per managed index.');
    }

    Logic found = Const(0);
    Logic selected = Const(0, width: indexWidth);
    Logic multiple = Const(0);
    Logic unavailable = Const(0);
    for (var index = 0; index < capacity; index++) {
      final validGrant =
          selectionMode == IndexAllocationSelectionMode.scalarCompatibility
              ? generated[index]
              : generated[index] & eligibleCandidates[index];
      final choose = validGrant & ~found;
      selected = mux(choose, Const(index, width: indexWidth), selected)
          .named('${name}_allocation_${lane}_selected_through_$index');
      multiple = (multiple | (found & validGrant))
          .named('${name}_allocation_${lane}_multiple_through_$index');
      unavailable =
          (unavailable | (generated[index] & ~eligibleCandidates[index]))
              .named('${name}_allocation_${lane}_unavailable_through_$index');
      found = (found | validGrant)
          .named('${name}_allocation_${lane}_found_through_$index');
    }
    final candidatesExist = eligibleCandidates
        .rconcat()
        .or()
        .named('${name}_lane_${lane}_has_candidate');
    final selectionAvailable =
        selectionMode == IndexAllocationSelectionMode.scalarCompatibility
            ? candidatesExist
            : found;
    final freshValid = (~localQuiesce &
            ~offerRetained[lane] &
            laneRequested &
            selectionAvailable)
        .named('${name}_allocation_${lane}_fresh_valid');
    allocationValid[lane] <= retainedActive[lane] | freshValid;
    allocationIndices[lane] <=
        mux(offerRetained[lane], retainedIndex[lane], selected);
    invalidSelections.add(~offerRetained[lane] &
        laneRequested &
        (multiple | unavailable | (candidatesExist & ~found)));
    candidates = [
      for (var index = 0; index < capacity; index++)
        (candidates[index] & ~(freshValid & selected.eq(index)))
            .named('${name}_candidate_${index}_after_offer_$lane')
    ];
  }

  final takenAllocations = [
    for (var index = 0; index < capacity; index++)
      [
        for (var lane = 0; lane < allocationLaneCount; lane++)
          allocationTaken[lane] & allocationIndices[lane].eq(index)
      ]
          .fold<Logic>(Const(0), (taken, lane) => taken | lane)
          .named('${name}_index_${index}_accepted')
  ];
  final retainedMask = retainedActive.rconcat();
  final isQuiesced =
      (localQuiesce & ~retainedMask.or()).named('${name}_quiesced');
  final releaseOffered = localRelease
      .reduce((left, right) => left | right)
      .named('${name}_release_offered');
  canRestore <= isQuiesced & ~releaseOffered;
  final restoreTaken =
      (localRestore & canRestore).named('${name}_restore_taken');
  var ownershipPrefix = ownershipAfterReleases;
  allocatedMasksAfterAllocationPrefixes[0] <=
      mux(restoreTaken, localRestoreMask, ownershipPrefix.rconcat());
  for (var lane = 0; lane < allocationLaneCount; lane++) {
    ownershipPrefix = [
      for (var index = 0; index < capacity; index++)
        (ownershipPrefix[index] |
                (allocationTaken[lane] & allocationIndices[lane].eq(index)))
            .named('${name}_owned_${index}_after_allocation_$lane')
    ];
    allocatedMasksAfterAllocationPrefixes[lane + 1] <=
        mux(restoreTaken, localRestoreMask, ownershipPrefix.rconcat());
  }
  final allocatedSum = allocated
      .map((entry) => entry.zeroExtend(countWidth))
      .reduce((left, right) => left + right)
      .named('${name}_allocated_sum');
  allocatedMask <= allocated.rconcat();
  allocatedCount <= allocatedSum;
  availableCount <= Const(capacity, width: countWidth) - allocatedCount;
  exhausted <= allocatedCount.eq(capacity);
  quiesced <= isQuiesced;
  retainedAllocationLanes <= retainedMask;
  invalidReleases <= invalidReleaseLanes.rconcat();
  doubleReleases <= doubleReleaseLanes.rconcat();
  invalidAllocationSelections <= invalidSelections.rconcat();

  Sequential(localClk, reset: localReset, resetValues: {
    if (storageImplementation == null)
      for (var index = 0; index < capacity; index++)
        allocated[index]: initialAvailability.contains(index) ? 0 : 1,
    for (final retained in offerRetained) retained: 0,
    for (final index in retainedIndex) index: 0
  }, [
    for (var lane = 0; lane < allocationLaneCount; lane++) ...[
      If(
          offerRetained[lane] &
              ((localWithdraws?[lane] ?? Const(0)) | allocationTaken[lane]),
          then: [
            offerRetained[lane] < 0,
          ],
          orElse: [
            If(
                ~offerRetained[lane] &
                    allocationValid[lane] &
                    ~localAllocate[lane],
                then: [
                  offerRetained[lane] < 1,
                  retainedIndex[lane] < allocationIndices[lane],
                ]),
          ])
    ],
    if (storageImplementation == null)
      for (var index = 0; index < capacity; index++)
        If(restoreTaken, then: [
          allocated[index] < localRestoreMask[index],
        ], orElse: [
          allocated[index] <
              ownershipAfterReleases[index] | takenAllocations[index],
        ])
  ]);
  if (storageImplementation != null) {
    final current = Logic(name: '${name}_stored_ownership', width: capacity);
    for (var index = 0; index < capacity; index++) {
      allocated[index] <= current[index];
    }
    final next = Logic(name: '${name}_next_ownership', width: capacity);
    Combinational([
      If(restoreTaken, then: [
        next < localRestoreMask,
      ], orElse: [
        next <
            [
              for (var index = 0; index < capacity; index++)
                ownershipAfterReleases[index] | takenAllocations[index]
            ].rconcat(),
      ])
    ]);
    connectRegisterFileBank(
      clk: localClk,
      reset: localReset,
      current: [current],
      next: [next],
      resetValues: [
        [
          for (var index = 0; index < capacity; index++)
            if (initialAvailability.contains(index))
              LogicValue.zero
            else
              LogicValue.one
        ].rconcat()
      ],
      implementation: storageImplementation,
      name: '${name}_ownership_storage',
    );
  }
}