ReadyValidSynchronousPrefetchedCountedQueue<LogicType extends Logic> constructor

ReadyValidSynchronousPrefetchedCountedQueue<LogicType extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required ReadyValidInterface<CompactedLanes<LogicType>> upstream,
  4. required ReadyValidInterface<CompactedLanes<LogicType>> downstream,
  5. required Logic dequeueCount,
  6. required int capacity,
  7. required CountedQueueBankingTopology bankingTopology,
  8. SynchronousMemoryFunctor? memoryFunctor,
  9. MemoryConfiguration? memoryConfiguration,
  10. int memoryReadLatency = 1,
  11. SynchronousRamReadUnderWrite readUnderWrite = SynchronousRamReadUnderWrite.readFirst,
  12. int? prefetchDepth,
  13. int? almostFullThreshold,
  14. int? almostEmptyThreshold,
  15. Logic? flush,
  16. String name = 'ready_valid_synchronous_prefetched_counted_queue',
})

Creates a banked synchronous-memory counted queue.

Implementation

ReadyValidSynchronousPrefetchedCountedQueue({
  required Logic clk,
  required Logic reset,
  required ReadyValidInterface<CompactedLanes<LogicType>> upstream,
  required ReadyValidInterface<CompactedLanes<LogicType>> downstream,
  required Logic dequeueCount,
  required this.capacity,
  required this.bankingTopology,
  SynchronousMemoryFunctor? memoryFunctor,
  MemoryConfiguration? memoryConfiguration,
  this.memoryReadLatency = 1,
  this.readUnderWrite = SynchronousRamReadUnderWrite.readFirst,
  int? prefetchDepth,
  int? almostFullThreshold,
  int? almostEmptyThreshold,
  Logic? flush,
  super.name = 'ready_valid_synchronous_prefetched_counted_queue',
})  : laneCount = upstream.data.laneCount,
      prefetchDepth = _resolvedPrefetchDepth(
        prefetchDepth,
        capacity,
        upstream.data.laneCount,
        memoryReadLatency,
      ),
      almostFullThreshold = almostFullThreshold ?? capacity,
      almostEmptyThreshold = almostEmptyThreshold ?? 0,
      super(
        definitionName: 'ReadyValidSynchronousPrefetchedCountedQueue_'
            'L${upstream.data.laneCount}_C${capacity}_'
            'P${_resolvedPrefetchDepth(
          prefetchDepth,
          capacity,
          upstream.data.laneCount,
          memoryReadLatency,
        )}_'
            'M${memoryReadLatency}_${bankingTopology.identity}_'
            'U${readUnderWrite.name}_${_prefetchedQueueMemoryIdentity(
          memoryFunctor,
          memoryConfiguration,
          dataWidth: upstream.data.lanes.elementWidth,
          depth: bankingTopology.layout.bankEntryCount(0),
          readLatency: memoryReadLatency,
          readUnderWrite: readUnderWrite,
        )}_'
            'W${upstream.data.lanes.elementWidth}_'
            'D${dequeueCount.width}_'
            'AF${almostFullThreshold ?? capacity}_'
            'AE${almostEmptyThreshold ?? 0}_'
            '${flush == null ? 'NoFlush' : 'Flush'}_'
            '${payloadShapesIdentity([upstream.data, downstream.data])}',
      ) {
  this.memoryFunctor = memoryFunctor ??
      _selectPrefetchedQueueMemoryFunctor(
        memoryConfiguration,
        dataWidth: upstream.data.lanes.elementWidth,
        depth: bankingTopology.layout.bankEntryCount(0),
        readLatency: memoryReadLatency,
        readUnderWrite: readUnderWrite,
      );
  if (capacity < 1 || memoryReadLatency < 1) {
    throw ArgumentError('Capacity and memory read latency must be positive.');
  }
  if (bankingTopology.capacity != capacity ||
      bankingTopology.laneCount != laneCount) {
    throw ArgumentError(
        'Banking topology capacity and lane count must match the queue.');
  }
  bankingTopology.requireCompatible();
  final maximumTransferCount = min(capacity, laneCount);
  if (this.prefetchDepth < maximumTransferCount ||
      this.prefetchDepth > capacity) {
    throw ArgumentError('Prefetch depth must be between '
        '$maximumTransferCount and $capacity.');
  }
  if (downstream.data.laneCount != laneCount ||
      downstream.data.lanes.elementWidth !=
          upstream.data.lanes.elementWidth ||
      downstream.data.countWidth != upstream.data.countWidth) {
    throw ArgumentError('Input and output counted-lane shapes must match.');
  }
  final inputs = upstream.data.lanes.arrayElements;
  if (!rohdPayloadsCompatible(inputs, ignoreConstantNames: true) ||
      inputs.any((input) => downstream.data.lanes.arrayElements.any(
          (output) => !rohdPayloadsCompatible([input, output],
              ignoreConstantNames: true)))) {
    throw ArgumentError('Routed lane payloads must be compatible.');
  }
  if (dequeueCount.width < upstream.data.countWidth) {
    throw ArgumentError(
        'dequeueCount must represent every offered lane count.');
  }
  if (this.almostFullThreshold < 0 ||
      this.almostFullThreshold > capacity ||
      this.almostEmptyThreshold < 0 ||
      this.almostEmptyThreshold > capacity) {
    throw ArgumentError(
        'Queue thresholds must be between zero and capacity inclusive.');
  }
  upstream.requireProviderComposableWith(ReadyValidContract.readyAndValid,
      consumerName: name);
  downstream.requireConsumerComposableWith(ReadyValidContract.irrevocable,
      providerName: name);

  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localFlush = flush == null ? Const(0) : addInput('flush', flush);
  this.upstream = addPairInterface(
    upstream,
    PairRole.consumer,
    uniquify: (original) => 'upstream_$original',
  );
  this.downstream = addPairInterfaceFrom(
    IrrevocableReadyValidInterface<CompactedLanes<LogicType>>(
      downstream.data.cloneTyped(),
    ),
    downstream,
    PairRole.provider,
    uniquify: (original) => 'downstream_$original',
  );
  final localDequeueCount =
      addInput('dequeueCount', dequeueCount, width: dequeueCount.width);
  final storageReset =
      (localReset | localFlush).named('${name}_storage_reset');

  final occupancyWidth = max(1, (capacity + 1).log2Ceil);
  final cacheCountWidth = max(1, (this.prefetchDepth + 1).log2Ceil);
  final pointerWidth = max(1, capacity.log2Ceil);
  final arithmeticWidth = [
        occupancyWidth,
        cacheCountWidth,
        pointerWidth,
        this.upstream.data.validCount.width,
        localDequeueCount.width,
      ].reduce(max) +
      1;
  addOutput('occupancy', width: occupancyWidth);
  addOutput('availableCount', width: occupancyWidth);
  addOutput('empty');
  addOutput('full');
  addOutput('almostFull');
  addOutput('almostEmpty');
  addOutput('acceptedEnqueueCount',
      width: this.upstream.data.validCount.width);
  addOutput('acceptedDequeueCount',
      width: this.downstream.data.validCount.width);
  addOutput('invalidEnqueueCount');
  addOutput('invalidDequeueCount');
  addOutput('cachedCount', width: cacheCountWidth);
  addOutput('prefetchPendingCount', width: cacheCountWidth);
  addOutput('headRefillPending');
  addOutput('mismatchedMemoryResponse');
  addOutput('unexpectedMemoryResponse');
  addOutput('staleResponse');
  addOutput('responseOverflow');

  final currentOccupancy =
      Logic(name: '${name}_occupancy', width: occupancyWidth);
  final writePointer =
      Logic(name: '${name}_write_pointer', width: pointerWidth);
  final prefetchPointer =
      Logic(name: '${name}_prefetch_pointer', width: pointerWidth);
  final outstandingCount =
      Logic(name: '${name}_outstanding_count', width: cacheCountWidth);

  final cacheInput = ReadyAndValidInterface(
    this.upstream.data.cloneTyped(name: '${name}_cache_input'),
  );
  final cacheOutput = ReadyAndValidInterface(
    this.downstream.data.cloneTyped(name: '${name}_cache_output'),
  );
  final cache = ReadyValidCountedQueue<LogicType>(
    clk: localClk,
    reset: storageReset,
    upstream: cacheInput,
    downstream: cacheOutput,
    dequeueCount: localDequeueCount,
    capacity: this.prefetchDepth,
    name: '${name}_head_cache',
  );

  this.downstream.valid <= cacheOutput.valid;
  this.downstream.data.validCount <= cacheOutput.data.validCount;
  this.downstream.data.consumedMask <= cacheOutput.data.consumedMask;
  for (var lane = 0; lane < laneCount; lane++) {
    this.downstream.data.lanes.arrayElements[lane] <=
        cacheOutput.data.lanes.arrayElements[lane];
  }
  cacheOutput.ready <= this.downstream.ready;

  final current = currentOccupancy.zeroExtend(arithmeticWidth);
  final inputCount =
      this.upstream.data.validCount.zeroExtend(arithmeticWidth);
  final inputCountValid = inputCount.neq(0) &
      inputCount.lte(Const(maximumTransferCount, width: arithmeticWidth));
  final consumedCount =
      cache.acceptedDequeueCount.zeroExtend(arithmeticWidth);
  final availableAfterDequeue =
      Const(capacity, width: arithmeticWidth) - current + consumedCount;
  this.upstream.ready <=
      ~storageReset &
          mux(
            inputCountValid,
            inputCount.lte(availableAfterDequeue),
            Const(1),
          );
  final enqueueAccepted =
      this.upstream.accepted.named('${name}_enqueue_accepted');
  final enqueuedCount = mux(
    enqueueAccepted & inputCountValid,
    inputCount,
    Const(0, width: arithmeticWidth),
  );

  occupancy <= currentOccupancy;
  availableCount <= Const(capacity, width: occupancyWidth) - currentOccupancy;
  empty <= currentOccupancy.eq(0);
  full <= currentOccupancy.eq(capacity);
  almostFull <=
      ~currentOccupancy
          .lt(Const(this.almostFullThreshold, width: occupancyWidth));
  almostEmpty <=
      currentOccupancy
          .lte(Const(this.almostEmptyThreshold, width: occupancyWidth));
  acceptedEnqueueCount <=
      enqueuedCount.getRange(
        0,
        acceptedEnqueueCount.width,
      );
  acceptedDequeueCount <= cache.acceptedDequeueCount;
  invalidEnqueueCount <= enqueueAccepted & ~inputCountValid;
  invalidDequeueCount <= cache.invalidDequeueCount;
  cachedCount <= cache.occupancy;
  prefetchPendingCount <= outstandingCount;
  headRefillPending <= currentOccupancy.neq(0) & cache.occupancy.eq(0);

  final cacheOccupancy = cache.occupancy.zeroExtend(arithmeticWidth);
  final outstanding = outstandingCount.zeroExtend(arithmeticWidth);
  final reservedAfterDequeue = cacheOccupancy + outstanding - consumedCount;
  final availableReservation =
      Const(this.prefetchDepth, width: arithmeticWidth) -
          reservedAfterDequeue;
  final unprefetched = current - cacheOccupancy - outstanding;
  final issueCountWide = _minimum(
    _minimum(
      unprefetched,
      availableReservation,
      arithmeticWidth,
    ),
    Const(maximumTransferCount, width: arithmeticWidth),
    arithmeticWidth,
  );
  final issueCount = issueCountWide.getRange(
    0,
    this.upstream.data.validCount.width,
  );
  final issueValid = issueCountWide.neq(0) & ~storageReset;

  final bankWrites = <DataPortInterface>[];
  final bankReads = <SynchronousReadDataPortInterface>[];
  for (var bank = 0; bank < bankingTopology.bankCount; bank++) {
    final bankDepth = bankingTopology.layout.bankEntryCount(bank);
    final addressWidth = max(1, bankDepth.log2Ceil);
    bankWrites.add(DataPortInterface(
      this.upstream.data.lanes.elementWidth,
      addressWidth,
    ));
    bankReads.add(SynchronousReadDataPortInterface(
      this.upstream.data.lanes.elementWidth,
      addressWidth,
    ));
  }

  for (var bank = 0; bank < bankingTopology.bankCount; bank++) {
    final write = bankWrites[bank];
    final read = bankReads[bank];
    final addressWidth = write.addrWidth;
    Logic writeEnable = Const(0);
    Logic writeAddress = Const(0, width: addressWidth);
    Logic writeData = this.upstream.data.lanes.arrayElements.first;
    Logic readEnable = Const(0);
    Logic readAddress = Const(0, width: addressWidth);
    for (var base = 0; base < capacity; base++) {
      for (var lane = 0; lane < maximumTransferCount; lane++) {
        final slot = (base + lane) % capacity;
        final coordinate = bankingTopology.layout.coordinateOf(slot);
        if (coordinate.bank != bank) {
          continue;
        }
        final writeSelected = enqueueAccepted &
            inputCountValid &
            Const(lane, width: arithmeticWidth).lt(inputCount) &
            writePointer.eq(base);
        writeEnable = writeEnable | writeSelected;
        writeAddress = mux(
          writeSelected,
          Const(coordinate.row, width: addressWidth),
          writeAddress,
        );
        writeData = mux(
          writeSelected,
          this.upstream.data.lanes.arrayElements[lane],
          writeData,
        );
        final readSelected = issueValid &
            Const(lane, width: arithmeticWidth).lt(issueCountWide) &
            prefetchPointer.eq(base);
        readEnable = readEnable | readSelected;
        readAddress = mux(
          readSelected,
          Const(coordinate.row, width: addressWidth),
          readAddress,
        );
      }
    }
    write.en <= writeEnable;
    write.addr <= writeAddress;
    write.data <= writeData;
    read.en <= readEnable;
    read.addr <= readAddress;
  }

  final bindings = <SynchronousMemoryBinding>[];
  for (var bank = 0; bank < bankingTopology.bankCount; bank++) {
    bindings.add(this.memoryFunctor(
      clk: localClk,
      reset: localReset,
      writePorts: [bankWrites[bank]],
      readPorts: [bankReads[bank]],
      entryCount: bankingTopology.layout.bankEntryCount(bank),
      readLatency: memoryReadLatency,
      readUnderWrite: readUnderWrite,
      name: '${name}_bank_$bank',
    ));
  }
  memoryBindings = List.unmodifiable(bindings);

  final responseTagValid = List.generate(
    memoryReadLatency,
    (stage) => Logic(name: '${name}_response_tag_valid_$stage'),
  );
  final responseTagBase = List.generate(
    memoryReadLatency,
    (stage) => Logic(
      name: '${name}_response_tag_base_$stage',
      width: pointerWidth,
    ),
  );
  final responseTagCount = List.generate(
    memoryReadLatency,
    (stage) => Logic(
      name: '${name}_response_tag_count_$stage',
      width: this.upstream.data.validCount.width,
    ),
  );
  final scheduledResponse = responseTagValid.last;
  final responseBase = responseTagBase.last;
  final responseCount = responseTagCount.last;
  final responseCountWide = responseCount.zeroExtend(arithmeticWidth);

  final expectedBanks = <Logic>[];
  for (var bank = 0; bank < bankingTopology.bankCount; bank++) {
    Logic expected = Const(0);
    for (var base = 0; base < capacity; base++) {
      for (var lane = 0; lane < maximumTransferCount; lane++) {
        final slot = (base + lane) % capacity;
        if (bankingTopology.layout.coordinateOf(slot).bank != bank) {
          continue;
        }
        expected = expected |
            (responseBase.eq(base) &
                Const(lane, width: arithmeticWidth).lt(responseCountWide));
      }
    }
    expectedBanks.add(expected);
  }
  final allExpectedValid = [
    for (var bank = 0; bank < bankingTopology.bankCount; bank++)
      ~expectedBanks[bank] | bankReads[bank].valid,
  ].rconcat().and();
  final anyUnexpected = [
    for (var bank = 0; bank < bankingTopology.bankCount; bank++)
      bankReads[bank].valid & ~expectedBanks[bank],
  ].rconcat().or();
  final anyMemoryResponse = bankReads
      .map((read) => read.valid)
      .toList(growable: false)
      .rconcat()
      .or();
  final completeResponse =
      scheduledResponse & allExpectedValid & ~anyUnexpected;

  cacheInput.valid <= completeResponse & ~localReset & ~localFlush;
  cacheInput.data.validCount <= responseCount;
  cacheInput.data.consumedMask <=
      [
        for (var lane = 0; lane < laneCount; lane++)
          Const(lane, width: arithmeticWidth).lt(responseCountWide),
      ].reversed.toList(growable: false).concat();
  for (var lane = 0; lane < laneCount; lane++) {
    Logic selected = Const(
      0,
      width: cacheInput.data.lanes.arrayElements[lane].width,
    );
    for (var base = capacity - 1; base >= 0; base--) {
      final slot = (base + lane) % capacity;
      final bank = bankingTopology.layout.coordinateOf(slot).bank;
      selected = mux(responseBase.eq(base), bankReads[bank].data, selected);
    }
    cacheInput.data.lanes.arrayElements[lane] <=
        mux(
          Const(lane, width: arithmeticWidth).lt(responseCountWide),
          selected,
          Const(0, width: selected.width),
        );
  }
  mismatchedMemoryResponse <= scheduledResponse & ~allExpectedValid;
  unexpectedMemoryResponse <= scheduledResponse & anyUnexpected;
  staleResponse <=
      anyMemoryResponse & (~scheduledResponse | localReset | localFlush);
  responseOverflow <= cacheInput.valid & ~cacheInput.ready;

  final scheduledResponseCount = mux(
    scheduledResponse,
    responseCountWide,
    Const(0, width: arithmeticWidth),
  );
  final nextOccupancy = current - consumedCount + enqueuedCount;
  final nextOutstanding =
      outstanding + issueCountWide - scheduledResponseCount;
  Sequential(localClk, reset: storageReset, resetValues: {
    currentOccupancy: 0,
    writePointer: 0,
    prefetchPointer: 0,
    outstandingCount: 0,
    for (final valid in responseTagValid) valid: 0,
    for (final base in responseTagBase) base: 0,
    for (final count in responseTagCount) count: 0,
  }, [
    currentOccupancy < nextOccupancy.getRange(0, occupancyWidth),
    writePointer <
        _advancePointer(
          writePointer,
          enqueuedCount,
          capacity,
          pointerWidth,
        ),
    prefetchPointer <
        _advancePointer(
          prefetchPointer,
          issueCountWide,
          capacity,
          pointerWidth,
        ),
    outstandingCount < nextOutstanding.getRange(0, outstandingCount.width),
    responseTagValid.first < issueValid,
    responseTagBase.first < prefetchPointer,
    responseTagCount.first < issueCount,
    for (var stage = 1; stage < memoryReadLatency; stage++) ...[
      responseTagValid[stage] < responseTagValid[stage - 1],
      responseTagBase[stage] < responseTagBase[stage - 1],
      responseTagCount[stage] < responseTagCount[stage - 1],
    ],
  ]);
}