1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20package vta.core
21
22import chisel3._
23import chisel3.util._
24
25/** Semaphore.
26  *
27  * This semaphore is used instead of push/pop fifo, used in the initial
28  * version of VTA. This semaphore is incremented (spost) or decremented (swait)
29  * depending on the push and pop fields on instructions to prevent RAW and WAR
30  * hazards.
31  */
32class Semaphore(counterBits: Int = 1, counterInitValue: Int = 1)
33    extends Module {
34  val io = IO(new Bundle {
35    val spost = Input(Bool())
36    val swait = Input(Bool())
37    val sready = Output(Bool())
38  })
39  val cnt = RegInit(counterInitValue.U(counterBits.W))
40  when(io.spost && !io.swait && cnt =/= ((1 << counterBits) - 1).asUInt) {
41    cnt := cnt + 1.U
42  }
43  when(!io.spost && io.swait && cnt =/= 0.U) { cnt := cnt - 1.U }
44  io.sready := cnt =/= 0.U
45}
46