SerializedCache<T extends Logic, M extends Logic, C extends Logic, R extends Logic> constructor

SerializedCache<T extends Logic, M extends Logic, C extends Logic, R extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required List<CacheTransactionPort<T, M, C, R>> ports,
  4. required int setCount,
  5. required int waysPerSet,
  6. required MemoryArrayFunctor<T> dataMemory,
  7. MemoryArrayFunctor<M>? metadataMemory,
  8. CacheReplacement replacement = CacheReplacement.roundRobin,
  9. AssociativeMemoryFunctor tagMemory = parallelAssociativeMemoryFunctor,
  10. CacheBackingPorts<T, M>? backing,
  11. MemoryConfiguration? memoryConfiguration,
  12. String name = 'serialized_cache',
})

Creates a cache with one outstanding operation and synchronous data reads.

Implementation

SerializedCache({
  required Logic clk,
  required Logic reset,
  required List<CacheTransactionPort<T, M, C, R>> ports,
  required this.setCount,
  required this.waysPerSet,
  required MemoryArrayFunctor<T> dataMemory,
  MemoryArrayFunctor<M>? metadataMemory,
  CacheReplacement replacement = CacheReplacement.roundRobin,
  AssociativeMemoryFunctor tagMemory = parallelAssociativeMemoryFunctor,
  this.backing,
  MemoryConfiguration? memoryConfiguration,
  super.name = 'serialized_cache',
})  : ports = List.unmodifiable(ports),
      capabilities = CacheTransactionCapabilities(
        operations: CacheTransactionOperation.values.toSet(),
        extensionOperations: backing == null
            ? const {}
            : {for (final op in CacheBackingOperation.values) op.code},
        maxOutstanding: 1,
        responseOrdering: CacheTransactionOrdering.inOrder,
        sameBlockOrdering: CacheSameBlockOrdering.acceptanceOrder,
        sameCycleOrdering: CacheSameCycleOrdering.lowerPortFirst,
        supportsMaskedUpdates: true,
        reportsInvalidations: true,
      ),
      super(
        definitionName: 'SerializedCache_S${setCount}_W${waysPerSet}_'
            'P${ports.length}_${dataMemory.identity}_${replacement.identity}_'
            '${tagMemory.identity}_L${dataMemory.capabilities.readLatency}_'
            '${_portShape(ports)}'
            '${_metadataSuffix(metadataMemory, memoryConfiguration)}'
            '${backing == null ? '' : '_B${backing.readLatency}'}',
      ) {
  if (ports.isEmpty ||
      clk.width != 1 ||
      reset.width != 1 ||
      setCount < 1 ||
      (setCount & (setCount - 1)) != 0 ||
      waysPerSet < 1 ||
      dataMemory.capabilities.readLatency < 1 ||
      (metadataMemory != null &&
          metadataMemory.capabilities.readLatency != 0) ||
      replacement.buildWithCommits == null) {
    throw ArgumentError('Invalid serialized cache geometry, data latency, '
        'or replacement factory.');
  }
  final requestSchema = ports.first.requests.data;
  final responseSchema = ports.first.responses.data;
  final evictionSchema = ports.first.evictions.data;
  final addressWidth = requestSchema.address.width;
  final setBits = (setCount - 1).bitLength;
  if (addressWidth < max(1, setBits) ||
      ports.any((port) =>
          !sameRohdPayloadShape(requestSchema, port.requests.data) ||
          !sameRohdPayloadShape(responseSchema, port.responses.data) ||
          !sameRohdPayloadShape(evictionSchema, port.evictions.data))) {
    throw ArgumentError('Cache transaction ports must have matching shapes '
        'and addresses must represent every set.');
  }
  if (backing != null &&
      (backing!.read.addrWidth != addressWidth ||
          backing!.write.addrWidth != addressWidth ||
          !sameRohdPayloadShape(
              backing!.read.data.data, requestSchema.data) ||
          !sameRohdPayloadShape(
              backing!.read.data.lineMetadata, requestSchema.lineMetadata) ||
          !sameRohdPayloadShape(backing!.write.data, backing!.read.data))) {
    throw ArgumentError('Backing ports must match the request address, data '
        'and line metadata.');
  }
  ports.forEach(capabilities.validatePort);
  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localPorts = [
    for (final (i, port) in ports.indexed)
      addInterfacePorts(port,
          inputTags: [PairDirection.fromProvider],
          outputTags: [PairDirection.fromConsumer],
          uniquify: (signal) => 'port_${i}_$signal')
  ];
  final requests = [for (final port in localPorts) port.requests];
  final responses = [for (final port in localPorts) port.responses];
  final evictions = [for (final port in localPorts) port.evictions];
  final backingPorts = backing;
  final backingRead = backingPorts == null
      ? null
      : addInterfacePorts(backingPorts.read,
          inputTags: {DataPortGroup.data},
          outputTags: {DataPortGroup.control},
          uniquify: (signal) => 'backing_read_$signal');
  final backingWrite = backingPorts == null
      ? null
      : addInterfacePorts(backingPorts.write,
          outputTags: {DataPortGroup.control, DataPortGroup.data},
          uniquify: (signal) => 'backing_write_$signal');

  Logic combine(List<Logic> values) =>
      values.reduce((left, right) => left | right);
  final stateWidth = max(1, (_CacheState.values.length - 1).bitLength);
  Logic stateValue(_CacheState value) =>
      Const(value.index, width: stateWidth);
  final state = Logic(name: 'state', width: stateWidth);
  Logic inState(_CacheState value) => state.eq(stateValue(value));
  final idle = inState(_CacheState.idle);
  final probe = inState(_CacheState.probe);
  final waitData = inState(_CacheState.waitData);
  final evict = inState(_CacheState.evict);
  final fetch = inState(_CacheState.fetch);
  final write = inState(_CacheState.write);
  final respond = inState(_CacheState.respond);
  final ownerWidth = max(1, (ports.length - 1).bitLength);
  final owner = Logic(name: 'owner', width: ownerWidth);
  final savedRequest = requestSchema.cloneTyped(name: 'saved_request');
  final accepted = <Logic>[];
  Logic earlierValid = Const(0);
  for (var i = 0; i < ports.length; i++) {
    requests[i].ready <= ~localReset & idle & ~earlierValid;
    accepted.add(requests[i].valid & requests[i].ready);
    earlierValid = earlierValid | requests[i].valid;
    final conflict = ~localReset &
        ~idle &
        owner.eq(i) &
        requests[i].valid &
        requests[i].data.token.eq(savedRequest.token);
    localPorts[i].tokenConflict <= conflict;
  }
  final accept = combine(accepted);
  var incoming = requestSchema.cloneTyped()
    ..gets(Const(0, width: requestSchema.width));
  Logic incomingOwner = Const(0, width: ownerWidth);
  for (var i = ports.length - 1; i >= 0; i--) {
    incoming = mux<CacheTransactionRequest<T, M, C>>(
        accepted[i], requests[i].data, incoming);
    incomingOwner =
        mux(accepted[i], Const(i, width: ownerWidth), incomingOwner);
  }
  savedRequest <=
      flop<CacheTransactionRequest<T, M, C>>(
          localClk,
          mux<CacheTransactionRequest<T, M, C>>(
              accept, incoming, savedRequest),
          reset: localReset);
  owner <=
      flop(localClk, mux(accept, incomingOwner, owner), reset: localReset);

  final isLookup =
      savedRequest.operation.eq(CacheTransactionOperation.lookup.code);
  final isFill =
      savedRequest.operation.eq(CacheTransactionOperation.fill.code);
  final isUpdate =
      savedRequest.operation.eq(CacheTransactionOperation.update.code);
  final isInvalidate =
      savedRequest.operation.eq(CacheTransactionOperation.invalidate.code);
  final isReadThrough = backing == null
      ? Const(0)
      : savedRequest.operation.eq(CacheBackingOperation.readThrough.code);
  final isWriteAllocate = backing == null
      ? Const(0)
      : savedRequest.operation.eq(CacheBackingOperation.writeAllocate.code);
  // Operations that allocate a way on a miss.
  final allocates = isFill | isReadThrough | isWriteAllocate;
  // Operations that read the hit way and respond with it.
  final readsHit = isLookup | isReadThrough;
  // Operations that merge the request into the hit or fetched block.
  final merges = isUpdate | isWriteAllocate;
  final supported = isLookup |
      isFill |
      isUpdate |
      isInvalidate |
      isReadThrough |
      isWriteAllocate;
  final wayWidth = max(1, (waysPerSet - 1).bitLength);
  final savedWay = Logic(name: 'saved_way', width: wayWidth);
  final savedVictimAddress = Logic(name: 'saved_victim', width: addressWidth);
  final oldData = Logic(name: 'old_data', width: requestSchema.data.width);
  final oldMetadata =
      Logic(name: 'old_metadata', width: requestSchema.lineMetadata.width);
  final status = Logic(name: 'status', width: 2);
  final fillMiss = Logic(name: 'fill_miss');

  Logic selects(int set) => setBits == 0
      ? Const(1)
      : storedIndexMatches(savedRequest.address.getRange(0, setBits), set);
  final hits = <Logic>[];
  final allocationValid = <Logic>[];
  final allocationEvict = <Logic>[];
  final chosenWays = <Logic>[];
  final victimAddresses = <Logic>[];
  final readData = <Logic>[];
  final readMetadata = <Logic>[];
  final writeUnitWidth =
      requestSchema.data.width ~/ requestSchema.writeMask.width;
  final updatedData = [
    for (var unit = 0; unit < requestSchema.writeMask.width; unit++)
      mux(
        savedRequest.writeMask[unit],
        savedRequest.data
            .getRange(unit * writeUnitWidth, (unit + 1) * writeUnitWidth),
        oldData.getRange(unit * writeUnitWidth, (unit + 1) * writeUnitWidth),
      )
  ].rconcat();
  final writeData = normalizeStoredLogic(mux(
      merges, updatedData, mux(isReadThrough, oldData, savedRequest.data)));

  for (var set = 0; set < setCount; set++) {
    final selected = selects(set);
    final tagUpdate = TypedAssociativeUpdatePortInterface(
        Logic(width: addressWidth),
        indexWidth: wayWidth);
    final tagLookup = TypedAssociativeLookupPortInterface(
        Logic(width: addressWidth),
        indexWidth: wayWidth);
    final side = AssociativeIndexedSideReadRequest(indexWidth: wayWidth);
    final access = ReplacementAccessInterface(waysPerSet);
    final allocation = ReplacementAllocationInterface(waysPerSet);
    final commit = ReplacementCommitInterface(waysPerSet);
    tagLookup.en <= ~localReset & probe & selected & supported;
    tagLookup.key <= savedRequest.address;
    allocation.en <= tagLookup.en & allocates & ~tagLookup.hit;
    allocation.commit <= Const(0);
    side.index <= allocation.index;
    access.en <= tagLookup.hit;
    access.index <= tagLookup.index;
    commit.en <= ~localReset & write & selected & allocates & fillMiss;
    commit.index <= savedWay;
    tagUpdate.en <=
        ~localReset & write & selected & (allocates | isInvalidate);
    tagUpdate.index <= savedWay;
    tagUpdate.key <= savedRequest.address;
    tagUpdate.entryValid <= ~isInvalidate;
    final binding = tagMemory(
      clk: localClk,
      reset: localReset,
      updatePorts: [tagUpdate],
      lookupPorts: [tagLookup],
      entryCount: waysPerSet,
      sideReadRequest: side,
      requiresValidityMask: true,
      lookupLatency: 0,
      duplicateKeyPolicy: AssociativeDuplicateKeyPolicy.allow,
      matchSelection: AssociativeMatchSelection.lowestIndex,
      resultShape: AssociativeResultShape.selectedIndex,
      lookupUpdatePolicy: AssociativeLookupUpdatePolicy.lookupAfterUpdate,
      updateCollisionPolicy: AssociativeUpdateCollisionPolicy.highestPortWins,
      requiredResetBehavior: AssociativeMemoryResetBehavior.clearValidity,
      name: 'tags_$set',
    );
    final tags = binding.memory!;
    final mask = (tags as AssociativeValidityMaskProvider).validMask!;
    final sideResponse =
        (tags as AssociativeIndexedSideReadProvider).sideReadResponse!;
    final policy = replacement.buildWithCommits!(
      clk: localClk,
      reset: localReset,
      validMask: mask,
      eligibleMask:
          Const((BigInt.one << waysPerSet) - BigInt.one, width: waysPerSet),
      accesses: [access],
      allocations: [allocation],
      commits: [commit],
      entryCount: waysPerSet,
      name: 'replacement_$set',
    );
    if (policy.entryCount != waysPerSet) {
      throw StateError('Replacement factory returned incompatible geometry.');
    }

    final way = mux(tagLookup.hit, tagLookup.index, allocation.index);
    final needsRead = ((readsHit | merges | isInvalidate) & tagLookup.hit) |
        (allocates & ~tagLookup.hit & allocation.valid & allocation.evict);
    final dataRead = DataPortInterface<T>.typed(requestSchema.data, wayWidth);
    final dataWrite =
        DataPortInterface<T>.typed(requestSchema.data, wayWidth);
    dataRead.en <= ~localReset & probe & selected & needsRead;
    dataRead.addr <= way;
    dataWrite.en <= ~localReset & write & selected & (allocates | merges);
    dataWrite.addr <= savedWay;
    dataWrite.data <= writeData;
    dataMemory(
      clk: localClk,
      reset: localReset,
      writePorts: [dataWrite],
      readPorts: [dataRead],
      entryCount: waysPerSet,
      readLatency: dataMemory.capabilities.readLatency,
      maxConcurrentReads: 1,
      maxConcurrentWrites: 1,
      maxConcurrentAccesses: 1,
      name: 'data_$set',
    );
    final metaRead =
        DataPortInterface<M>.typed(requestSchema.lineMetadata, wayWidth);
    final metaWrite =
        DataPortInterface<M>.typed(requestSchema.lineMetadata, wayWidth);
    metaRead.en <= ~localReset & probe & selected & needsRead;
    metaRead.addr <= way;
    metaWrite.en <= dataWrite.en;
    metaWrite.addr <= savedWay;
    metaWrite.data <=
        normalizeStoredLogic(
            mux(isReadThrough, oldMetadata, savedRequest.lineMetadata));
    (metadataMemory ??
        _metadataArray<M>(memoryConfiguration) ??
        registerFileArray<M>())(
      clk: localClk,
      reset: localReset,
      writePorts: [metaWrite],
      readPorts: [metaRead],
      entryCount: waysPerSet,
      readLatency: 0,
      maxConcurrentReads: 1,
      maxConcurrentWrites: 1,
      maxConcurrentAccesses: 1,
      requiredReadCollision: MemoryArrayReadCollision.combinational,
      name: 'metadata_$set',
    );
    hits.add(selected & tagLookup.hit);
    allocationValid.add(selected & allocation.valid);
    allocationEvict.add(selected & allocation.evict);
    chosenWays.add(mux(selected, way, Const(0, width: wayWidth)));
    victimAddresses
        .add(mux(selected, sideResponse.key, Const(0, width: addressWidth)));
    readData.add(mux(
        selected, dataRead.data, Const(0, width: requestSchema.data.width)));
    readMetadata.add(mux(selected, metaRead.data,
        Const(0, width: requestSchema.lineMetadata.width)));
  }
  final hit = combine(hits);
  final allocationOk = combine(allocationValid);
  final victim = combine(allocationEvict);
  final needsRead = ((readsHit | merges | isInvalidate) & hit) |
      (allocates & ~hit & allocationOk & victim);
  final canFill = isFill & (hit | allocationOk);
  final canFetch = (isReadThrough | isWriteAllocate) & ~hit & allocationOk;
  savedWay <=
      flop(localClk, mux(probe, combine(chosenWays), savedWay),
          reset: localReset);
  savedVictimAddress <=
      flop(localClk, mux(probe, combine(victimAddresses), savedVictimAddress),
          reset: localReset);
  fillMiss <=
      flop(localClk, mux(probe, allocates & ~hit, fillMiss),
          reset: localReset);

  // A backing read is held for the whole fetch state; its line is sampled
  // readLatency cycles after the state is entered.
  final fetchLatency = backing?.readLatency ?? 0;
  final fetchCountWidth = max(1, fetchLatency.bitLength);
  final fetchCount = Logic(name: 'fetch_count', width: fetchCountWidth);
  final fetchComplete = fetch & fetchCount.eq(fetchLatency);
  fetchCount <=
      flop(
          localClk,
          mux(
              fetch & ~fetchComplete,
              fetchCount + Const(1, width: fetchCountWidth),
              Const(0, width: fetchCountWidth)),
          reset: localReset);
  final fetchedData = backingRead?.data.data.packed ??
      Const(0, width: requestSchema.data.width);
  final fetchedMetadata = backingRead?.data.lineMetadata.packed ??
      Const(0, width: requestSchema.lineMetadata.width);
  if (backingRead != null) {
    backingRead.en <= ~localReset & fetch;
    backingRead.addr <= savedRequest.address;
  }
  oldMetadata <=
      flop(
          localClk,
          mux(probe & needsRead, combine(readMetadata),
              mux(fetchComplete, fetchedMetadata, oldMetadata)),
          reset: localReset);

  final latency = dataMemory.capabilities.readLatency;
  final countWidth = max(1, (latency - 1).bitLength);
  final count = Logic(name: 'read_count', width: countWidth);
  final readComplete = waitData & count.eq(0);
  count <=
      flop(
          localClk,
          mux(
              probe & needsRead,
              Const(latency - 1, width: countWidth),
              mux(waitData & ~count.eq(0),
                  count - Const(1, width: countWidth), count)),
          reset: localReset);
  oldData <=
      flop(
          localClk,
          mux(readComplete, combine(readData),
              mux(fetchComplete, fetchedData, oldData)),
          reset: localReset);

  Logic statusValue(CacheTransactionStatus value) =>
      Const(value.code, width: 2);
  final noReadStatus = mux(
      canFill,
      statusValue(CacheTransactionStatus.completed),
      mux(supported & ~isFill, statusValue(CacheTransactionStatus.miss),
          statusValue(CacheTransactionStatus.error)));
  status <=
      flop(
          localClk,
          mux(
            probe & ~needsRead,
            noReadStatus,
            mux(
                readComplete,
                mux(
                    isFill,
                    statusValue(CacheTransactionStatus.completed),
                    mux(fillMiss, statusValue(CacheTransactionStatus.miss),
                        statusValue(CacheTransactionStatus.hit))),
                status),
          ),
          reset: localReset);

  // A backing-store miss responds with the fetched block.
  final respondsWithData = status.eq(CacheTransactionStatus.hit.code) |
      (status.eq(CacheTransactionStatus.miss.code) &
          (isReadThrough | isWriteAllocate));
  final responseDone = <Logic>[];
  final evictionDone = <Logic>[];
  for (var i = 0; i < ports.length; i++) {
    final owned = owner.eq(i);
    responses[i].valid <= ~localReset & respond & owned;
    responses[i].data.token <= savedRequest.token;
    responses[i].data.status <= status;
    responses[i].data.data <=
        mux(respondsWithData, oldData, Const(0, width: oldData.width));
    responses[i].data.lineMetadata <=
        mux(respondsWithData, oldMetadata,
            Const(0, width: oldMetadata.width));
    responses[i].data.context <= savedRequest.context;
    responses[i].data.result <=
        Const(0, width: responses[i].data.result.width);
    evictions[i].valid <= ~localReset & evict & owned;
    evictions[i].data.token <= savedRequest.token;
    evictions[i].data.cause <=
        mux(
            isInvalidate,
            Const(CacheTransactionEvictionCause.invalidation.code,
                width: evictions[i].data.cause.width),
            Const(CacheTransactionEvictionCause.replacement.code,
                width: evictions[i].data.cause.width));
    evictions[i].data.address <=
        mux(isInvalidate, savedRequest.address, savedVictimAddress);
    evictions[i].data.data <= oldData;
    evictions[i].data.lineMetadata <= oldMetadata;
    evictions[i].data.context <= savedRequest.context;
    responseDone.add(responses[i].valid & responses[i].ready);
    evictionDone.add(evictions[i].valid & evictions[i].ready);
  }
  if (backingWrite != null) {
    backingWrite.en <= ~localReset & combine(evictionDone);
    backingWrite.addr <=
        mux(isInvalidate, savedRequest.address, savedVictimAddress);
    backingWrite.data.data <= oldData;
    backingWrite.data.lineMetadata <= oldMetadata;
  }
  var nextState = state;
  nextState = mux(accept, stateValue(_CacheState.probe), nextState);
  nextState =
      mux(probe & needsRead, stateValue(_CacheState.waitData), nextState);
  nextState = mux(
      probe & ~needsRead,
      mux(
          canFill,
          stateValue(_CacheState.write),
          mux(canFetch, stateValue(_CacheState.fetch),
              stateValue(_CacheState.respond))),
      nextState);
  // After a victim read, a backing-store miss evicts before it fetches.
  nextState = mux(
      readComplete,
      mux(
          readsHit & ~fillMiss,
          stateValue(_CacheState.respond),
          mux(merges & ~fillMiss, stateValue(_CacheState.write),
              stateValue(_CacheState.evict))),
      nextState);
  nextState = mux(
      combine(evictionDone),
      mux(fillMiss & ~isFill, stateValue(_CacheState.fetch),
          stateValue(_CacheState.write)),
      nextState);
  nextState = mux(fetchComplete, stateValue(_CacheState.write), nextState);
  nextState = mux(write, stateValue(_CacheState.respond), nextState);
  nextState =
      mux(combine(responseDone), stateValue(_CacheState.idle), nextState);
  state <= flop(localClk, nextState, reset: localReset);
}