Chisel3: How to create a register without reset signal in RawModule? - chisel

I want to create a RegNext in a RawModule, with the help of withClock. However, it can't work while the error information shows that missing implicit reset. So I have to write it like this:
class Test extends RawModule {
...
val nothing = Wire(Bool())
nothing := DontCare
val a = withClockAndReset(io.ui_clk, nothing) {
RegNext(~io.in)
}
...
}
Is there any better solution?

You can shorten it a little bit by using
withClockAndReset(io.ui_clk, false.B)
but I can't figure out a way to do it otherwise. withClock uses withClockAndReset internally and that's what cases the error. Maybe someone else has a better answer.

Related

How to soft reset Chisel Counter

I'm using a Chisel Counter in my logic, and want to be able to reset it also on clear input signal.
how can i do that ?
I was thinking of something like that:
withReset(reset || io.clr) {val (count,wrap) = Counter(io.valid,512)}
My Issue with this (apart from being ugly) is that the val names are not available out of the scope of the withReset.
Is there a better way to do so ?
How about trying to assign 0.U the inner value of the Counter , how can i do that ?
withReset returns the last expression in the block, so you can just write:
val (count, wrap) = withReset(reset.asBool || io.clr)(Counter(io.valid,512))
Note that I added .asBool to reset because in import chisel3._, val reset has the abstract type Reset. See the Chisel website docs on Reset for more information.
I think the above is the best way to do it, but you can also use the #chiselName macro to allow Chisel to name vals inside scopes:
import chisel3.experimental.chiselName
#chiselName
class MyModule extends Module {
...
withReset(reset || io.clr) {val (count,wrap) = Counter(io.valid,512)}
// ^ these ^ will now get named
}
Note that we're trying to get a better version of #chiselName into the 3.4.0 release in the coming weeks, but #chiselName works for the time being.

Chisel : When-otherwise clause not working in function definition

I am trying to develop a simple circuit using Chisel 3 to generate the factorial for a number n. Here's my implementation :
class Factorial extends Module{
val io = IO(new Bundle{
val input = Input(UInt(8.W))
val output = Output(UInt(16.W))
})
def factorial(n: UInt): UInt = {
when (n === 0.U) {1.U}
.otherwise {n*factorial(n-1.U)}
}
io.out := factorial(io.in)
}
However, when I try to run it, I get the following error :
cmd26.sc:9: type mismatch;
found : Unit
required: chisel3.UInt
.otherwise {n*factorial(n-1.U)}
^Compilation Failed
Is there any particular reason for this? How do I solve this issue?
Also, I realize that an easy solution is to just have the number n to be of type Int, and have an if-else clause instead. Is there any way to type cast the parameter being passed during function call (i.e. from chisel3.UInt to Int)?
The Chisel when,elsewhen, and otherwise statement do not return a value.
Your design seems to be an attempt to compute the factorial value for an input in a single cycle. This is only going be practical for small input values and would probably be easier to implement via a lookup table.
I think what you are looking for (which would be a good learning exercise) is to build a circuit that given an input will return the factorial value after some number of cycles. This is very very similar to the way the GCD example works, GCD is included as an example in the chisel-template repo as an example. To do this you will need registers and ready and valid ports.
I suggest you figure out how that works and you should have a much easier time making your factorial. Good luck. And as suggested by #FabienM you will need a very large output port to contain the answer for even modest input values.
I thinks you can't do that. when(){}.otherwise{} is an hardware construction that don't return any value (Unit) as we can see in code.
With this construct you want to generate hardware «on the fly», which is impossible.
I think you have generate all solutions directly like it:
class Factorial extends Module{
val io = IO(new Bundle{
val input = Input(UInt(8.W))
val output = Output(UInt(1676.W))
})
def factorial(n: BigInt): BigInt = {
if(n == 0){
1
}else{
n*factorial(n-1)
}
}
io.output := 0.U
for(i <- 0 to 0xFF) {
when(io.input === i.U){
io.output := factorial(i).U
}
}
}
You can keep your recursive scala fonction but just for hardware generation step.
Note that 255! is a really big number you will need more than 16 bits UInt to output the value ;)

How to writing a accumulator by using ScalaBlackBox?

I want to create some new number types that like DspReal for dsptools, such as DspPosit and DspQuire. DspPosit bases on posit which I have some Java code, and DspQuire bases on quire which is a kind of accumulator for posit. Because I just want to simulation now, so I have write many ScalaBlackBox for their operation like DspReal. However, I found that ScalaBlackBox can't construct sequential logic. For example, current output of the quire accumulator depends on it's input and last output. But ScalaBlackBox can't get the value of the output. In addition, step(n) also influences the output. Because accumulator will read its input per clock cycle.
I found some system problems of treadle. First, the function of ScalaBlackBox, twoOp and oneOp and so on, will be called many times. I don't know why. Second, step(n) is the function of PeekPokeTester, which can't be access by ScalaBlackBox. Third, I try to read current output but system gives errors.
trait DspBlackBlackBoxImpl extends BlackBoxImplementation with ScalaBlackBox
abstract class DspQuireAccumulator extends DspBlackBlackBoxImpl {
lazy val accValue = Quire32() // initial value
/**
* sub-classes must implement this two argument function
*
* #param posit accumulate element
* #return quire operation result
*/
def accOp(posit: Posit32): Unit
def outputDependencies(outputName: String): Seq[(String)] = {
outputName match {
case "out" => Seq("in") // Seq("out", "in") gives errors
case _ => Seq.empty
}
}
def cycle(): Unit = {}
def execute(inputValues: Seq[Concrete], tpe: Type, outputName: String): Concrete = {
val arg1 :: _ = inputValues
val positArg = Posit32(arg1.value)
accOp(positArg)
val result = quire32ToBigInt(accValue)
ConcreteSInt(result, DspQuire.underlyingWidth, arg1.poisoned).asUInt
}
def getOutput(inputValues: Seq[BigInt], tpe: Type, outputName: String): BigInt = {
val arg1 :: _ = inputValues
val positArg = Posit32(arg1)
accOp(positArg)
quire32ToBigInt(accValue)
}
}
class DspQuireAddAcc(val name: String) extends DspQuireAccumulator {
def accOp(posit: Posit32): Unit = accValue += posit
}
class QuireBlackboxAccOperand extends BlackBox {
val io = IO(new Bundle() {
val in = Input(UInt(DspPosit.underlyingWidth.W))
val out = Output(UInt(DspQuire.underlyingWidth.W))
})
}
class BBQAddAcc extends QuireBlackboxAccOperand
class TreadleDspQuireFactory extends ScalaBlackBoxFactory {
def createInstance(instanceName: String, blackBoxName: String): Option[ScalaBlackBox] = {
blackBoxName match {
case "BBQAddAcc" => Some(add(new DspQuireAddAcc(instanceName)))
...
accOp will be called many times. So, if I want to accumulate List(1, 2, 3), the result maybe 0 + 1 + 1 + 2 + 2 + ...
And peek function will call accOp one time again, this makes me confused also.
I believe most of your problems at this point are caused by mixing two different approaches. I think you should not be using BlackBoxImplmentation because it is an older scheme used in with the firrtl-interpreter. Just use the ScalaBlackBox and implement the methods as described in the wiki page Black Boxes and Treadle and shown in the TreadleTest BlackBoxWithState.
Don't use outputDependencies, and instead specify any dependencies between inputs and outputs with with getDependencies. inputChanged will be called whenever an input IO is changed. So in that method you want to record or update the internal state of your black box. clockChange will be called whenever a clock is changed and will provide the transition information so you can decide what happens then. Treadle will call getOutput whenever it needs that output of your black box, since you will not have used outputDependencies you can ignore the inputs and just provide the output value depending on your internal state.
I am still trying to reproduce a running version of your code here but it will be a little time for me to put it together, if you can try my suggestions above and let me know how it goes that would be helpful. I am interested in making this feature of Treadle better and easier to use so all feedback is appreciated.

How to add a sbus master to rocket-chip periphery

I'm trying to implement a DMA like periphery to the rocket chip.
Meaning a module that is hooked to the pbus, and controlled by registers.
it also has a master hooked to the sbus.
I followed the sifive format to attach registers controlled peripheries without any problems.
My question is how do I add the sbus master ?, the bellow is what I've tried before getting to dead end.
To the attach parameters class I've added the sbus:
case class dmaAttachParams(
dma : dmaParams,
controlBus: TLBusWrapper,
masterBus : TLBusWrapper, // <-- my addition
....
) (implicit val p: Parameters)
Then I modified the attach method in the factory object:
def attach(params: dmaAttachParams): TLdma = {
implicit val p = params.p
val name = s"dma_${nextId()}"
val cbus = params.controlBus
val mbus = params.masterBus // <- my addition
val dma = LazyModule(new TLdma(params.dma))
dma.suggestName(name)
cbus.coupleTo(s"slave_named_name") {
dma.controlXing(params.controlXType) := TLFragmenter(cbus.beatBytes, cbus.blockBytes) := _
}
InModuleBody { dma.module.clock := params.mclock.map(_.getWrappedValue).getOrElse(cbus.module.clock) }
InModuleBody { dma.module.reset := params.mreset.map(_.getWrappedValue).getOrElse(cbus.module.reset) }
// this section is my problem // <-- this section is my addition
mbus.from(s"master_named_name") {
mbus.inwardNode := TLBuffer() := dma.mnode // <- what should i do here ???
}
dma
}
The mndoe is a node I have add to the dma class like this:
val mnode = TLClientNode(Seq(TLClientPortParameters(Seq(TLClientParameters(name = "dmaSbusMaster")))))
what should be the body of the mbus.from() method that will do the work?
trying to build this code gives this error:
Caused by: java.lang.IllegalArgumentException: requirement failed: buffer.node (A adapter node with parent buffer inside coupler_from_master_named_name) has 1 inputs and 0 outputs; they must match (Buffer.scala:69:28)
Any help will appreciated, in the rocket chip github issue forum, they no longer answer support questions. So if someone from there can answer here it will be great, as I am really stuck here.
P.S. just adding the way the attach method is invoked:
trait HasPeripheryDma { this: BaseSubsystem =>
val dmaNodes = p(PeripheryDmaKey).map { ps =>
dma.attach(dmaAttachParams(ps, pbus, sbus))
}
}
Update:
Implementing the body of the mbus.from() method as below:
mbus.from(s"master_named_name") {
mbus.inwardNode := TLBuffer(BufferParams.default) := dma.mnode
}
Does create a coupler from the dma on the SBUS , but it is not connected to the dma periphery. Any Ideas ?
I don't understand what is going wrong in your "Update", but this should work:
mbus.coupleFrom("master_named_dma") {
_ := TLBuffer(BufferParams.default) := dma.mnode
}
I have managed to attach the SBUS by reverse engineering of the way the slave is attached.
If someone can/wants to elaborate more feel free to do so.
I have added a "TLOutwardCrossingHelper" field to the DMA periphery like this:
class TLdma(params : dmaParams) (implicit p: Parameters) extends dma(params) with HasTLControlRegMap {
val controlXingMaster : TLOutwardCrossingHelper = this.crossOut(mnode)
}
please note that equivalent "TLInwardCrossingHelper" is defined in the "HasTLControlRegMap " trait that we extending.
Then,In the attach method, the next line did the work:
_ := TLBuffer(BufferParams.default) := dma.controlXingMaster(params.controlXType)
In this way I was able to also hook the periphery to the coupler on the sbus.
I assume the crossing object does something to the node , but I don't know what.

Fetch the response from sql, store it in a object and use conditions?

I have two sql statements to be executed with a validity check. My need is that I execute the 1st query and store the response in one object and check the object is empty or not and execute the second query if it is not empty.
So, I have tried something like
In rolerepository.scala=>
override val allQuery = s"""
select UserRoles.* from
(select CASE rbac.roleTypeID
ELSE rbac.name JOIN dirNetworkInfo ni
ON UserRoles.PersonID = ni.PersonID
where ni.Loginname = {loginName}
and UserRoles.roleName in ( 'Business User ','Administrator')"""
(This is just some sample of the query - it is not fully written here.)
Then I map it to an object with model class written outside
override def map2Object(implicit map: Map[String, Any]):
HierarchyEntryBillingRoleCheck = {
HierarchyEntryBillingRoleCheck(str("roleName"), oint("PersonID")) }
Then I have written the getall method to execute the query
override def getAll(implicit loginName: String):
Future[Seq[HierarchyEntryBillingRoleCheck]] = {
doQueryIgnoreRowErrors(allQuery, "loginName" -> loginName) }
Then I have written the method to check whether the response from the 1st sql is empty or not. This is were I'm stuck and not able to proceed further.
def method1()= {
val getallresponse = HierarchyEntryBillingRoleCheck
getallresponse.toString
if (getallresponse != " ")
billingMonthCheckRepository.getrepo()
}
I am getting an error (type mismatch) in last closing brace and I don't know what other logic can be used here.
Can any one of you please explain and give me some solution for this?
And i also tried to use for loop in controller but not getting how to do that.
i tried ->
def getAll(implicit queryParams: QueryParams,
billingMonthmodel:Seq[HierarchyEntryBillingRoleCheck]):
Action[AnyContent] = securityService.authenticate() { implicit request
=> withErrorRecovery { req =>
toJson {
repository.getAll(request.user.loginName)
for {
rolenamecheck <- billingMonthmodel
}yield rolenamecheck
}}}}
You don't say which db access method you are using. (I'm assuming anorm). One way of approaching this is:
Create a case class matching your table
Create a parser matching your case class
use Option (or Either) to return a row for a specific set of parameters
For example, perhaps you have:
case class UserRole (id:Int, loginName:String, roleName:String)
And then
object UserRole {
val sqlFields = "ur.id, ur.loginName, ur.roleName"
val userRoleParser = {
get[Int]("id") ~
get[String]("loginName") ~
get[String]("roleName") map {
case id ~ loginName ~ roleName => {
UserRole(id, loginName, roleName)
}
}
}
...
The parser maps the row to your case class. The next step is creating either single row methods like findById or findByLoginName and multi-row methods, perhaps allForRoleName or other generic filter methods. In your case there might (assuming a single role per loginName) be something like:
def findByLoginName(loginName:String):Option[UserRole) = DB.withConnection { implicit c =>
SQL(s"select $sqlFields from userRoles ur ...")
.on('loginName -> loginName)
.as(userRoleParser.singleOpt)
}
The .as(parser... is key. Typically, you'll need at least:
as(parser.singleOpt) which returns an Option of your case class
as(parser *) which returns a List of your case class (you'll need this if multiple roles could exist for a login
as(scalar[Long].singleOpt) which returns an Option[Long] and which is handy for returning counts or exists values
Then, to eventually return to your question a little more directly, you can call your find method, and if it returns something, continue with the second method call, perhaps like this:
val userRole = findByLoginName(loginName)
if (userRole.isDefined)
billingMonthCheckRepository.getrepo()
or, a little more idiomatically
findByLoginName(loginName).map { userRole =>
billingMonthCheckRepository.getrepo()
...
I've shown the find method returning an Option, but in reality we find it more useful to return an Either[String,(your case class)], and then the string contains the reason for failure. Either is cool.
On my version of play (2.3.x), the imports for the above are:
import play.api.db._
import play.api.Play.current
import anorm._
import anorm.SqlParser._
You're going to be doing this sort of thing a lot so worth finding a set of patterns that works for you.
WOW I don't know what's happening with the formatting here, I am really attempting to use the code formatter on the toolbar but I don't know why it won't format it, even when pressed multiple times. I invite the community to edit my code formatting because I can't figure it out. Apologies to OP.
Because I find Play's documentation to be very tough to trudge through if you're unfamiliar with it, I won't just leave a link to it only.
You have to inject an instance of your database into your controller. This will then give it to you as a global variable:
#Singleton
class LoginRegController #Inject()(**myDB: Database**, cc: ControllerComponents ) {
// do stuff
}
But, it's bad practice to actually use this connection within the controller, because the JDBC is a blocking operation, so you need to create a Model which takes the db as a parameter to a method. Don't set the constructor of the object to take the DB and store it as a field. For some reason this creates connection leaks and the connections won't release when they are done with your query. Not sure why, but that's how it is.
Create a Model object that you will use to execute your query. Instead of passing the DB through the object's constructor, pass it through the method you will create:
object DBChecker {
def attemptLogin(db:Database, password:String): String = {
}}
In your method, use the method .withConnection { conn => to access your JDBC connection. So, something like this:
object DBChecker {
def attemptLogin(db:Database, password:String):String = {
var username: String = ""
db.withConnection{ conn =>
val query:String = s"SELECT uploaded_by, date_added FROM tableName where PASSWORD = $password ;"
val stmt = conn.createStatement()
val qryResult:ResultSet = stmt.executeQuery(query)
// then iterate over your ResultSet to get the results from the query
if (qryResult.next()) {
userName = qryResult.getString("uploaded_by")
}
}
}
return username
}
// but note, please look into the use of PreparedStatement objects, doing it this way leaves you vulnerable to SQL injection.
In your Controller, as long as you import the object, you can then call that object's methods from your controller you made in Step 1.
import com.path.to.object.DBChecker
#Singleton
class LoginRegController #Inject()(myDB: Database, cc: ControllerComponents ) { def attemptLogin(pass:String) = Action {
implicit request: Request[AnyContent] => {
val result:String = DbChecker.attemptLogin(pass)
// do your work with the results here
}