Design and Implementation of a Cosimulation Environment ...

120
Diplomarbeit Design and Implementation of a Cosimulation Environment for Heterogeneous Microelectronic Systems Ingo Hans Pill ————————————– Institut f¨ ur Technische Informatik Technische Universit¨ at Graz Vorstand: O. Univ.-Prof. Dipl.-Ing. Dr. techn. Reinhold Weiß Begutachter: O. Univ.-Prof. Dipl.-Ing. Dr. techn. Reinhold Weiß Betreuer: Ass.-Prof Dipl.-Ing. Dr. techn. Christian Steger Graz, im Oktober 2003

Transcript of Design and Implementation of a Cosimulation Environment ...

Page 1: Design and Implementation of a Cosimulation Environment ...

Diplomarbeit

Design and Implementation of aCosimulation Environment for

Heterogeneous Microelectronic Systems

Ingo Hans Pill

————————————–

Institut fur Technische Informatik

Technische Universitat Graz

Vorstand: O.Univ.-Prof.Dipl.-Ing.Dr. techn.Reinhold Weiß

Begutachter: O.Univ.-Prof.Dipl.-Ing.Dr. techn.Reinhold Weiß

Betreuer: Ass.-Prof Dipl.-Ing.Dr. techn.Christian Steger

Graz, im Oktober 2003

Page 2: Design and Implementation of a Cosimulation Environment ...

Kurzfassung

In den letzten Jahren wurden Entwicklungsmethoden und -prozesse einer standigen Wei-terentwicklung unterzogen. Die steigende Komplexitat der zu entwickelnden Produkte, dieNotwendigkeit, die Entwicklungszeit so kurz wie moglich zu halten, aber auch die Verei-nigung verschiedenster Designgebiete wie Elektronik, Mechanik, oder Software in einemProdukt, verlangten eine standige Weiterverbesserung vorhandener Entwicklungsumge-bungen, Werkzeuge und Designmethoden.

Der Einsatz von Simulationsmethoden ist heute Standard in fast jedem Entwicklungspro-zess. Simulationen, die unterschiedliche Entwicklungsstadien einzelner Teilsysteme kom-binieren, ermoglichen es, wahrend des gesamten Prozesses die Konsistenz des Entwurfshinsichtlich seiner Spezifikation zu validieren und die einzelnen Entwicklungsschritte zuverifizieren. Dadurch ist es moglich Design-Fehler, Fehlinterpretationen von Schnittstel-len, oder die Folgen von Mißverstandnissen zwischen einzelnen Entwicklungsteams, wieabgelaufene Spezifikationen oder schlecht dokumentierte Anderungen, so fruh als moglichaufzudecken.

Die Heterogenitat von Systembeschreibungen stellt hier eine besondere Herausforderungdar. Die speziellen Eigenschaften einzelner Beschreibungssprachen, das Vorhandensein ein-zelner gut getesteter Systemteile, wertvolles Know-how von Ingenieuren bezuglich einzel-ner Sprachen und Werkzeuge, oder auch der Zukauf von Losungen fuhren oft zu einermehrsprachigen Systembeschreibung. Es existieren kaum Simulatoren, die standardmaßigmehrere Beschreibungssprachen oder -methoden unterstutzen. Simulatorkopplungen ver-suchen durch die Verbindung von geeigneten Simulatoren uber spezielle Schnittstellen eineCosimulation heterogener Systembeschreibungen zu ermoglichen. Derartige Schnittstellenermoglichen ebenfalls die Einbindung realer Hardware oder Emulatoren zur Beschleuni-gung einer Simulation.Hierzu gibt es verschiedenste Ansatze, die Teilaspekte wie die Synchronisation der einzel-nen Simulatoren, oder die Kommunikationsmechanismen der Schnittstellen unterschiedlichimplementieren.

In dieser Arbeit wird eine Cosimulationsumgebung fur die Werkzeuge Simulink, Model-sim und SystemC entwickelt. Dabei werden netzwerkfahige Verbindungen zwischen denSimulatorschnittstellen dazu benutzt, die Simulatoren datengetrieben und zyklusbasiertzu synchronisieren.

1

Page 3: Design and Implementation of a Cosimulation Environment ...

Abstract

In recent years existing development methods have undergone a progressive advancement.Rising design complexity, the need to reduce time-to-market, and the integration of het-erogeneous fields like electronics, mechanics, and software into a single product have beendemanding a steadily enhancement of existing design environments, tools, and methods.

Today simulation is a standard technology featured by almost every design process.Simulations incorporating different design stages of single parts of the system enable thevalidation of the design in respect of its specification during the entire design process, aswell as the verification of single development steps.Therefore it is possible to detect design flaws, misinterpretations of interfaces and theresults of error-prone design team communication like out-of-date specifications and poorlycommunicated model changes as early as possible.

Heterogeneity of system descriptions poses a severe challenge to simulation. How-ever distinctive features of single design languages, the availability of well tested designsolutions, valuable experience of engineers in special languages and tools, or even the in-tegration of foreign solutions may result in a heterogeneous system description.Simulators featuring multiple design languages and methods are scarcely available. There-fore simulator couplings try to provide solutions for the simulation of heterogeneous systemthrough a combination of appropriate simulators via special interfaces. Similar interfacesenable the integration of real hardware or emulators into the simulation, to accomplish asimulation speedup.For the realization of a cosimulation various approaches are available, implementing singleaspects like the synchronization of the single simulators in different ways.

In this work a cosimulation environment for design processes using Simulink, Modelsimand SystemC is developed. To achieve a cosimulation, network connections are used tosynchronize the single simulators data-driven and cycle-based.

2

Page 4: Design and Implementation of a Cosimulation Environment ...

Danksagung

Bedanken mochte ich mich bei jenen Mitarbeitern des Instituts fur Technische Infor-matik, die direkt oder indirekt zum Gelingen dieser Diplomarbeit beigetragen haben. ImBesonderen bei O.Univ.-Prof. Dr. Reinhold Weiss fur die Moglichkeit, diese Arbeit an die-sem Institut durchfuhren zu konnen und deren Begutachtung. Besonders hervorzuheben istauch Ass.-Prof. Dr. Christian Steger, der mich bei der Durchfuhrung dieser Arbeit betreuthat und durch seine Anregungen, Verbesserungen und Korrekturen einen sehr wertvollenBeitrag zu der vorliegenden Diplomarbeit geleistet hat.

Mein Dank gilt auch Dr. Markus Pistauer, Managing Director der Firma CISC Se-miconductor Design+Consulting, der in Kooperation mit dem Institut fur Technische In-formatik diese Diplomarbeit ermoglichte. Hervorzuheben sind hier auch seine MitarbeiterSimone Reale und Dipl.-Ing. Suad Kajtazovic, die meine Arbeit mit ihren Vorschlagen undihrem zur Verfugung gestellten Erfahrungsschatz bereichert haben.

Daruberhinaus mochte ich mich bei meinen Eltern bedanken, die mir den Weg zumStudium geebnet und mich auf meinem ganzen bisherigen Weg unterstutzend begleitethaben.

Herzlichen Dank auch an meine Freunde, die meine Studienzeit berreichert und michauch bei meiner Diplomarbeit durch Korrekturlesen und aufmunternde Gesprache un-terstutzt haben.

Besonderer Dank gilt meiner Freundin Romana, deren Nerven ich in den letzten Jahrenoft bis hart an die Grenzen strapaziert habe. Sie hat endlose Geduld mit mir bewiesenund mich auch in schlechten Zeiten nicht die schonen Dinge im Leben vergessen lassen.

Graz, im Oktober 2003 Ingo Hans Pill

3

Page 5: Design and Implementation of a Cosimulation Environment ...

Contents

1 Introduction and Motivation 91.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.2 Document Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Background and Related Work 132.1 Design, Validation and Verification . . . . . . . . . . . . . . . . . . . . . . . 132.2 Verification and Validation via Testbenches . . . . . . . . . . . . . . . . . . 152.3 Heterogeneity in System Design . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.1 Multiple Levels of Abstraction . . . . . . . . . . . . . . . . . . . . . 172.3.2 Inter-Domain Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.3.3 Module Reuse and Integration of Foreign IP cores . . . . . . . . . . 20

2.4 Simulation of Heterogeneous Systems . . . . . . . . . . . . . . . . . . . . . . 212.4.1 Homogeneous Simulation . . . . . . . . . . . . . . . . . . . . . . . . 212.4.2 Heterogeneous Simulation . . . . . . . . . . . . . . . . . . . . . . . . 24

2.5 Simulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.5.1 Models of Computation . . . . . . . . . . . . . . . . . . . . . . . . . 332.5.2 Simulator Connections . . . . . . . . . . . . . . . . . . . . . . . . . . 36

2.6 IP Core Business . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

3 Design of the Cosimulation Environment 453.1 Development Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.2 A brief Overview of Simulink, Modelsim, and SystemC . . . . . . . . . . . . 46

3.2.1 Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463.2.2 Modelsim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.2.3 SystemC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.3 Considerations for a Model of Computation for the Cosimulation . . . . . . 533.3.1 Time and Synchronization . . . . . . . . . . . . . . . . . . . . . . . . 533.3.2 Cosimulation Control and Communication . . . . . . . . . . . . . . . 56

3.4 The global cosimulation concept . . . . . . . . . . . . . . . . . . . . . . . . 583.5 Interfaces for Simulink, Modelsim and SystemC . . . . . . . . . . . . . . . . 60

3.5.1 MATLAB/Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4

Page 6: Design and Implementation of a Cosimulation Environment ...

3.5.2 Modelsim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643.5.3 SystemC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4 Implementation of the Cosimulation Environment 704.1 Communication Mechanisms using Sockets . . . . . . . . . . . . . . . . . . . 70

4.1.1 Stream Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714.1.2 Programming Stream Sockets . . . . . . . . . . . . . . . . . . . . . . 724.1.3 Implementation of the Cosimulation Communication . . . . . . . . . 76

4.2 Simulink Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804.2.1 Real-Time Workshop Code Creation Process . . . . . . . . . . . . . 814.2.2 Simulink Wrapper Concept . . . . . . . . . . . . . . . . . . . . . . . 854.2.3 Simulink Wrapper Realization . . . . . . . . . . . . . . . . . . . . . . 87

4.3 Modelsim Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 924.3.1 General Modelsim Wrapper Concept . . . . . . . . . . . . . . . . . . 924.3.2 Creation of a Foreign Architecture . . . . . . . . . . . . . . . . . . . 944.3.3 Modelsim Wrapper Realization . . . . . . . . . . . . . . . . . . . . . 954.3.4 Summarized Modelsim Wrapper Implementation Concept . . . . . . 99

4.4 A Wrapper for SystemC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1014.4.1 Building a SystemC Entity for a Foreign Module . . . . . . . . . . . 102

4.5 Cosimulation Setup and Results . . . . . . . . . . . . . . . . . . . . . . . . . 104

5 Conclusion and Perspectives 111

A List of Acronyms 113

B Examples 114B.1 Example Stream Socket Server & Client . . . . . . . . . . . . . . . . . . . . 114

B.1.1 An example server program . . . . . . . . . . . . . . . . . . . . . . . 114B.1.2 An example client program . . . . . . . . . . . . . . . . . . . . . . . 115

Bibliography 116

5

Page 7: Design and Implementation of a Cosimulation Environment ...

List of Figures

1.1 Abstraction vs. complexity during IC-design . . . . . . . . . . . . . . . . . . 10

2.1 The strategy of a testbench . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.2 Y-diagram according to Gajski and Kuhn . . . . . . . . . . . . . . . . . . . 182.3 Module verification at different abstraction levels . . . . . . . . . . . . . . . 192.4 Decomposition, modularization, and module reuse in a design process . . . 212.5 Illustrating the expressible models for two languages: The general situation 222.6 Illustrating the expressible models for two languages: A special case . . . . 222.7 Introducing a third language . . . . . . . . . . . . . . . . . . . . . . . . . . 232.8 A schematic principle of a backplane . . . . . . . . . . . . . . . . . . . . . . 252.9 Three rule sets for a backplane protocol implementation. . . . . . . . . . . . 262.10 Automated interface generation for a SystemC based backplane . . . . . . . 272.11 A cosimulation of an optical cross connect using a SystemC backplane . . . 282.12 A backplane communication interface for a VHDL model . . . . . . . . . . 292.13 The entities of the introduced VHDL interface . . . . . . . . . . . . . . . . 302.14 A hybrid system containing a discrete controller and a continuous plant . . 312.15 An UML diagram for an object-oriented interface for Simulink models . . . 322.16 The effect of simultaneous events in discrete event computational models . . 342.17 Dataflow networks: (a) a directed graph (b) a corresponding single-processor

static schedule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362.18 Backtracking within a simulation . . . . . . . . . . . . . . . . . . . . . . . . 372.19 Nested remote procedure calls . . . . . . . . . . . . . . . . . . . . . . . . . . 40

3.1 A typical hardware design flow: a) standard and b) with SystemC . . . . . 533.2 Cosimulation synchronization illustration . . . . . . . . . . . . . . . . . . . 583.3 General cosimulation concept . . . . . . . . . . . . . . . . . . . . . . . . . . 593.4 Real-Time Workshop rapid prototyping execution flow chart . . . . . . . . . 64

4.1 Problematic connection establishment sequences . . . . . . . . . . . . . . . 774.2 Real-Time Workshop code creation process . . . . . . . . . . . . . . . . . . 814.3 A simple Simulink model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824.4 Simulink simulation parameters tablet . . . . . . . . . . . . . . . . . . . . . 834.5 Real-Time Workshop parameters. . . . . . . . . . . . . . . . . . . . . . . . . 83

6

Page 8: Design and Implementation of a Cosimulation Environment ...

4.6 Real-Time Workshop target selection. . . . . . . . . . . . . . . . . . . . . . 844.7 Simulation concept of the Simulink wrapper . . . . . . . . . . . . . . . . . . 874.8 Integration of the Modelsim wrapper into a VHDL simulation . . . . . . . . 934.9 An example system based on an ASIC and a test-bench . . . . . . . . . . . 1044.10 Time-diagram of signal ”A” determined at a Simulink simulation . . . . . . 1084.11 Time-diagram of signal ”A” determined at a Simulink cosimulation . . . . . 1094.12 Time-diagram of signal ”A” determined at a Simulink - Modelsim cosimulation1094.13 Time-diagram of signal ”A” determined at a SystemC based Simulink cosim-

ulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

7

Page 9: Design and Implementation of a Cosimulation Environment ...

List of Tables

3.1 Features supported by several Real-Time Workshop targets . . . . . . . . . 48

8

Page 10: Design and Implementation of a Cosimulation Environment ...

Chapter 1

Introduction and Motivation

In recent years existing development methods have undergone a progressive advancement.Rising design complexity, the need to reduce time-to-market, the integration of heteroge-neous fields like electronics, mechanics, and software into a single product, or the evolve-ment of SOC1-designs have been demanding a steadily enhancement of the entire designprocess; additionally all involved environments, tools, and methods had to be improvedtoo.

As an example for interdomain design the development of a car can be taken, which en-compasses the development of mechanical and electronic parts as well as some controlsoftware, not to forget the aerodynamics of the coachwork. An ideal design process shouldenable the possibility to work in all these areas concurrently to minimize time-to-market,as well as the facility to perform integral tests of the entire product at every design stage.To cope with this request of first magnitude new industry branches specialized in inter-domain-design, like Mechatronic, have occurred in the industrial landscape, as applicationareas for inter-domain design could be found in almost every product used in everydaylife.

Heterogeneity in a system design is not only a reason of the product area, but for exam-ple may also result from different design environments used throughout the developmentprocess.To reduce time-to-market and therefore reduce costs for instance, it is necessary to dividethe problem or task or product into several parts to be conquered by multiple designteams. Using this divide-and-conquer principle makes it necessary to validate completesystem interaction throughout the entire design process. Due to this it is possible to detectdesign flaws, misinterpretations of interfaces, and the results of error-prone design teamcommunication, like out-of-date specifications and poorly communicated model changes,as early as possible.

1System On a Chip

9

Page 11: Design and Implementation of a Cosimulation Environment ...

CHAPTER 1. INTRODUCTION AND MOTIVATION 10

These validation and verification steps might be faced with a heterogeneous system. Thiscan result from the use of several specialized tools for the different system parts, or theverification of parts in different design phases. A common example for the verification ofmodules at different design phases and detail levels would be the verification of an algo-rithmic description of a test module in combination with a transistor representation of anIC2.

The prior mentioned design phases represent an approach to deal with the increasingcomplexity of systems. Several levels of abstraction are introduced, in a way that dif-ferent aspects of model design are dealt with at different stages of the design process.For example a product’s functional design is done at an early stage without dealing withimplementation problems at transistor level or even thinking about C-MOS3 process tech-nologies. Figure 1.1 shows the typical abstraction levels (or layers) found in an IC designprocess and their responding detail levels illustrated by the amount of components (designelements) the designers are faced.

1E0

1E1

1E2

1E3

1E4

1E5

1E6

1E7

Algorithm

RTL

System

Gate

Transistor

Abs

trac

tion

Com

plex

ity, A

ccur

acy

Level of Abstraction

Complexity − Number of Components

Figure 1.1: Abstraction vs. complexity during IC-design [DG00]

As a consequence of the prior mentioned divide-and-conquer principle, the utilizedpartitioning and modularization processes have evolved in a way that the reuse of singlemodules became possible. Figure 2.4 at page 21 illustrates this concept. Such a modulereuse may be considered to be either within the design itself, or in a way that standardcells shall be designed which may then be reused in other products as well. The creation oflibraries containing standard modules, as well as the development of design environments

2Integrated Circuit3Complementary Metal Oxide Semiconductor

Page 12: Design and Implementation of a Cosimulation Environment ...

CHAPTER 1. INTRODUCTION AND MOTIVATION 11

supporting the concept of model reuse have been gaining such importance that a newbusiness branch called IP-Core4 business has emerged. IP-Core business demands technicalsolutions to provide such libraries to customers without publishing the intellectual propertyitself, but with a maximum usability and interconnectivity to a customer’s design.

After considering the above mentioned general aspects and problems of a design pro-cess, they shall be reconsidered with a practical aspect of product design in mind: simu-lation.Today simulation is one of the major concepts of design environments. Simulation is usedto verify the different steps made during a design process and therefore is a major tool toensure that a design lives up to the product requirements. Simulating a design beginningat the very first development stage and abstraction layer offers the ability to show thebehavior and reveal errors or design flaws as early as possible. Also when transitioningfrom one level of abstraction to a deeper one during a design process, a cosimulation ofsingle modules at the deeper level with the rest of the system represented in the alreadyverified higher level is a powerful method to verify those level transitions. Inter-domainco-simulation would be a desired tool in a design process as well.

Simulation has many other advantages such as minimizing the need of prototypes, orthe fact that in several areas like nuclear and other elementary research areas develop-ment of products would be much more time-consuming and expensive or sometimes evenimpossible.

Summarizing, design environments and tools had and still have to be developed whichmake it possible to provide concise models of systems with multiple domains and at dif-ferent abstraction layers in conjunction with methods to ”test” the design at every designstage [PKPS03]. Single component simulation should be featured as well as the simulationof the entire system, at every single and between different levels of detail. Furthermorethe tools should support module-reuse as well as the integration of foreign modules anddesigns. These requirements are quite challenging and there exist numerous different ap-proaches, methods and tools trying to cope with at least parts of these expectations.

This task also represents the motivation for this diploma thesis. The aim of the thesisis to develop a methodology for a heterogeneous cosimulation of different modules designedwith MATLAB/Simulink, Modelsim(VHDL), and SystemC. These design tools and envi-ronments have distinctive features, aim on different detail levels, and are commonly usedin the development of systems using electronic and mechanical parts. The above discussedaspects of design environments will be considered during the design of this cosimulationmethodology to offer an efficient, feature rich, and thus powerful approach.

4Intellectual Property Core

Page 13: Design and Implementation of a Cosimulation Environment ...

CHAPTER 1. INTRODUCTION AND MOTIVATION 12

1.1 Objectives

MATLAB/Simulink, Modelsim(VHDL) and SystemC are powerful tools utilizing differentlanguages offering their distinctive features and application areas. The aim of this workis to investigate methods to combine their power by providing a cosimulation method forthese tools.This masters thesis results of a joint venture of the Institute for Technical Informatics atthe Technical University Graz, and CISC Semiconductor Design+Consulting, Klagenfurt.At the beginning of this project the following topics were considered to be investigated indetail:

• Exploration of generated C-code from the Simulink Real-Time Workshop for thepossibility to be included into a VHDL simulation.

• Simulation of a system containing components designed with Simulink and VHDL,using above mentioned C-code generation.

• Investigation of the possibility to include this simulation into a SystemC simulation.

For a verification of the developed methodologies a typical automotive or telecommu-nication application shall be used to ensure usability in industry.

1.2 Document Structure

The structure of this document is straight forward. The document starts with a shortintroduction discussing the motivation and objectives of this masters thesis. The intro-duction is followed by a chapter discussing the background basics considering differentdesign and simulation aspects, and briefing several state of the art implementations andapproaches. Afterward a simulation network will be designed in accordance to the desiredproject objectives, whose implementation is then presented in the implementation chapter.The document is completed by a discussion of the approach.

Page 14: Design and Implementation of a Cosimulation Environment ...

Chapter 2

Background and Related Work

In recent years existing development methods have undergone a progressive advancement.Design processes and tools have been enchanced in many ways to handle rising designcomplexity and inter-domain designs as well as to minimize time-to-market.In this section several aspects of design processes will be discussed to provide the basicsfor the design of a heterogeneous cosimulation scheme. Furthermore related work will beaddressed and projects implementing the mentioned technologies presented.

2.1 Design, Validation and Verification

Design processes may differ in many aspects from each other; in respect of the used strate-gies like bottom-up or top-down approaches (as illustrated on page 18), or special usedtechniques like extreme programming [Bec99], used tools, or simply organizational aspects.Despite this diversity, there is one common requirement present with every single designprocess; The need to validate the design and to ensure the consistency of accomplishedwork during single development steps.This includes validation of an initial specification, the verification of a single decisionmade done during a development process, as well as the ”real world” testing of the re-sult at the end. In literature different distinctive terms for these ”testing” steps haveemerged [Zim03]:

• Validation is used to answer the key question whether a product will live up to theexpectations. This starts with a validation of the specification and may be donethroughout the complete development process.

• Verification considers design steps. Verication steps are intended to ensure a design’sconsistency during one or more actions carried out within a design process. Theremay be small changes in a design, but the requirements always have to be met.Therefore verification has a tight relationship to validation. Verification may considerthe entire system or single parts of it.

13

Page 15: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 14

• Testing is done when the development process is completed and the product is readyfor production. Therefore it is intended to unveil errors in the production processand is furthermore a means of quality assurance.

Summarized ”validation” and ”verification” are used to unveil errors and flaws during adesign process. Afterward prototypes are ”tested” to detect production errors. Althoughthe intentions aim on different aspects, in practice the steps carried out may not bededicated precisely, as these tasks are tightly bound by their intention.

For illustration consider the following: Testbenches may be used for both verificationand validation. Semantically testbenches are a means of validation, as testbenches try toanswer ”does it fulfill the expectations?”. Comparing testbench results before and after adesign step is a means of verification, as the intention is to investigate design consistencyover a design step.Furthermore there may still be design errors and flaws in the finished design, just uncov-ered at the testing of the ready-to-market product.There exist formal techniques like equivalence-checking or model-checking for validationand verification [Zim03, ELESV97]. However these formal methods are very hard to per-form especially with increasing complexity, and depend on special description formalisms,constructs and languages to be used within model descriptions.

In contrary to formal approaches, there exist several practical approaches as well,which utilize the idea of testbenches and will be discussed in more detail on page 15.These practical approaches like simulation and emulation have however a severe drawbackwhich is caused by its internal strategy. These methods implement testbenches, whereasthe considered item is fed with distinctive inputs to observe the output. The output willthen be interpreted to determine whether the item operates as intended.

The problem with this scheme is, that it does not fully live up to the expectation ofproviding a general correct testimony whether the item is operating correct or not, butthe conclusion is only correct for the used test scenarios.A consideration of a typical state-of-the-art microprocessor like AMD’s Athlon 64 shallunveil the arising problem. A single 64 bit addition would result in 2128 different inputcombinations to be considered. With a given simulation time of one microsecond per inputcombination, it would still take about 1025 years to consider every single possible inputcombination. Taken the complexity of the entire processor with all its units and states,it becomes even more obvious that testing the entire processor with all its possible inputcombinations and states to detect side effects is absolutely infeasible. So engineers haveto construct test cases covering as many eventualities as possible. However they are notable to ensure testing every single eventuality using testbenches.

Providing correct methods for verification and validation is a difficult task, as is eventhe establishment of a ”high quality specification” to rely on.There exist many more aspects to consider with both formal and testbench methods,however only a short introduction is intended to be given at this point. As the testbench

Page 16: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 15

approach will be featured within this work as it perfectly refers to a cosimulation approachit will be discussed in regard of practical aspects in the next section.

2.2 Verification and Validation via Testbenches

As mentioned in the prior section, the strategy of using testbenches serves to consider asystem’s behavior. The considered target receives well considered input scenarios (testcases), whereas its reaction to this stimuli is evaluated to predict the target’s behavior.Figure 2.1 illustrates this behavior.

Feedback

possible

SzenariosEvaluation

Inpu

tD

ata

Out

put

Dat

a

DUT

DUT .... Device Under Test

Figure 2.1: The strategy of a testbench: Possible scenarios provide the input data for aDUT. The output data can be evaluated for validation purposes and might influence thenext input data set

Methods to determine system behavior within a testbench include entire software so-lutions and approaches utilizing at least the (partial) inclusion of hardware for gaining aspeedup [Zim03, Rei98].

Simulation is an approach completely based on software, with all pros and cons en-tailed. So if a simulator is available for the used system description formalism, a simulationcan be performed with a minimum of overhead and costs. Parameters like granularity ofthe results or time resolution can be changed easily. This enables a very flexible reconsid-eration of single design steps, and simple design errors can be easily managed by iterativesimulation and model alteration cycles.In dangerous application areas like nuclear power plants or other areas where testing pro-totypes could cause severe damage, simulation is a mandatory technology. There existmany advantages with simulation due to its flexibility, minimized costs and wide applica-tion area. However there are several drawbacks as well.

First of all a successful simulation is no guarantee for the functionality of a product.Besides of the impact of limited test cases as discussed in the prior section (page 14),a simulator is a piece of software which is (in most cases) not formal proven and maycontain errors. In practice simulators are not very flexible, as in most cases they imple-ment one single language with limited expressiveness featuring only a subset of possibledesigns. Simulator internal interfaces for interconnection with third party software and

Page 17: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 16

other simulators to enhance the amount of possible designs are limited and proprietary ifeven present. Last but not least simulation becomes very slow with increasing complexityof a system, as the calculation time rises as well as the minimum amount of test scenariosneeded for a valid behavior assumption.

Emulation is one of the possible solutions for this problem. During the design of an IC1

for instance FPGA2s and automatic synthesis tools may be used to map the description ofa design onto hardware to create a virtual chip. This virtual chip may then be connectedto the actual testbench. Although the speed of this chip might be much slower than thefinished product, it will be still much faster than simulation. A drawback to emulationare its high costs, as well as the fact that the hardware would have to be replaced quitefrequently, due to the fast increasing complexity.

[Rei98] uses real hardware integrated into a simulator for a speed-up. So real parts ofthe system, for instance an already developed IC, may be integrated into a simulation aswell. Methods of the inclusion of existing hardware into a simulation or emulation offerfurther advantages as well, as it could be possible to test a design in real world conditions.For example a control IC can be tested in its application of controlling some mechanicalpart.Although possible the inclusion of real hardware into a simulation is in practice limited bythe technology available today as for instance real-time simulation would be mandatoryfor interactive real world situations. For much simpler situations like integrating a real ICinto a VHDL Simulation there exist already solutions as can be found in [Zim03, Rei98].

2.3 Heterogeneity in System Design

Heterogeneity is a plurivalent word in respect to a design process, although the classifica-tion into homogeneous and heterogeneous systems is very common in system design. Thisseparation is not really that explicit, as the decision whether a system is heterogeneous orhomogeneous, can be based on many different special aspects of the considered system.For instance if a system consists of multiple subsystems related to different domains (e.g.software and hardware) it is heterogeneous in respect of its domain. However it may behomogeneous in respect to its description language, if all system parts are modeled in thesame language.As this classification is ambiguous, for this document ”heterogeneity” shall refer to thelatter mentioned aspect if not mentioned otherwise; to the description language(s) used forsystem representation. A homogeneous model is therefore modeled in one single language,

1Integrated Circuit2Field Programmable Gate-Array

Page 18: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 17

whereas a heterogeneous model utilizes multiple language sets.

It is a very difficult task to cope with heterogeneity and it entails some severe prob-lems for the design process. Especially in respect to validation and verification it is aconsiderable obstacle due to the limitations of single simulators. Therefore cosimulationtechnologies have to be used for a simulation of the entire system. However there exist se-vere reasons for the demand and existence of heterogeneous system models. The followingthree situations will be discussed in detail in the very next subchapters:

• Multiple levels of abstraction

• Different domains

• Module reuse or the integration of foreign IP-cores3

Although these situations seem to be very different to each other, they can be assignedto two main origins. The limitations encountered with the use of a single descriptionlanguage and the reuse of available models or know-how.

The first basic origin results from the lack of a general description language as discussedin [Sim98]. For a special project the limitations of a single language in respect to its basiselements, description concepts, or paradigms may require either the enhancement of thislanguage to support special needs, or the partitioning of a system, so that each part canbe modeled in an appropriate language.

Available know-how and standard modules, or the integration of foreign designs mayresult in heterogeneous system designs as well. There exist multiple different languages andtools with their own distinctive features and application areas. Besides language abilitiesthemselves, the experience of engineers with their tools shall be considered as well, as thisexperience minimizes design times and results in a better quality as well. The reuse ofalready available ”well tested” modules is a considerable option too, independent of thesource of the module description. It may come from standard libraries, former projects, oreven bought foreign designs. In many cases these will not be available in the actual useddescription language, and in the case of foreign designs they may further be encapsulatedin a special format to hide detail informations and intellectual property.

2.3.1 Multiple Levels of Abstraction

Abstraction layers or levels have been introduced to cope with the increasing complexityof products to be developed. The intention was to consider different aspects of a systemat different stages.

Figure 2.2 at page 18 illustrates the typical abstraction levels used for electronic circuitdesign processes.

3Intellectual Property cores

Page 19: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 18

Transistors

Flip−Flops, Gates

Differential Equations

System Level

Algorithmic Level

Register−Transfer Level

Logic Level

Circuit Level

Physical/Geometry

Behavioural Structural

System−Specification

Boolean Equations

Register−Transfers

Algorithms

Modules, Registers, ALU

Subsystems, Busses

CPUs, Memory

Production Masks , Polygons

Cells

Floorplan

Cluster

Partitioning

Figure 2.2: Y-diagram according to Gajski and Kuhn, adapted from [LWS94]

In this figure the abstraction levels are represented by circles, the minor the radiusthe greater the level of detail, whereas the three axes are related to different point ofviews. Intersections of circles and lines represent modeling stages, where a designer maydecompose a model (figure 2.4 on page 21). For system design the engineer will start atthe outer region (system level) and then will head by transformations (change point ofview) and refinements (change abstraction levels) to the center, what means he has anaccurate model of the final implementation. Figure 1.1 at page 10 shows the complexityof the design process in respect of the amount of design elements the development teamsare faced, and the accuracy represented by the abstraction level. A typical top-downdesign methodology starts with a specification at the highest level of abstraction, theso-called system level, and moves step-wise down to more detailed levels by refining anddecomposing the model (see fig. 2.4 at page 21).In most cases a design won’t utilize a simple top-down approach, because verificationbetween different abstraction levels will unveil errors and design flaws and as a consequencethe model has to be modified or even redesigned (maybe at a higher level of detail). Theresulting methodology is referred as ”jojo”-design.

Bottom-up methodologies work the opposite way, they start at the lowest detail leveland proceed by composing components together. These component blocks may be used

Page 20: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 19

in the next step to create even more complex components. The creation of standard celllibraries is a certain strength of this approach.

The verification between different abstraction levels is one of the key-issues for the en-tire design process. During refinement steps between detail levels, or decomposing phasesat one level, the model’s invariance to the specification has to be monitored and guar-anteed. To accomplish this, the interaction of multiple modules at different abstractionlevels has to be validated, as illustrated in figure 2.3 where module 3’s invariance is tested.

System−L.M3_c

Gate−L.M3_b

Reg.−Tr.−L.M3_a

System−L.

M4

M1 M2 M3 M4

System−Level

M1 M2

System−Level

VerificationSimulation

Figure 2.3: Module verification at different abstraction levels

As indicated in the figure, different languages may be used at different abstractionlevels. This illustrates the need of cosimulation methods for several simulators to enablethe verification steps utilizing different abstraction levels [PKPS03].

2.3.2 Inter-Domain Design

Inter-domain design is a matter of first magnitude. Today a common system design mayinclude components from heterogeneous fields like electronics, mechanics, software, andmany more e.g. [IEE99]. To be able to detect errors and side-effects of possible changesas soon as possible, validation and verification of the entire system throughout the wholedesign process is mandatory.

For convenience there has always been the wish for one universal language able todescribe everything and understandable by every tool. Besides the theoretical questionof whether such a language does even exist, today’s tools aren’t able to live up to theseexpectations.

Although languages have been enhanced to offer functionality for at least similar do-mains, this enhancements entailed drawbacks as well.

Page 21: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 20

To create a precise and accurate description of a model related to special domain, theused language has to offer special constructs and components representing the distinctivefeatures of this domain.If a language tries to cover multiple domains, it provides this interdomain functionalityat expense of flexibility and modeling power in the single domains. Considering mul-tiple domains in combination with different layers of abstraction unveils the amount offunctionality a single language would have to provide.

Even if there exists a language to cover all domains of a system, there may be areason to use multiple ones. Engineers related to a special domain in most cases rely onspecial tools providing best functionality in this domain, and have a deep know-how andexperience with their tools of choice. For a homogeneous system description all engineerswould have to abandon their know-how and learn a new tool covering all aspects of thissingle system. Furthermore this ”general language” might be different for every singleproduct. As there is an enormous amount of different domain-combinations, all coveredby different languages dependent on the specific system’s requirements, it would be a veryinefficient and time-consuming alternative to switch description language every time toget a homogeneous system description.

Again for verification and validation purposes cosimulation methods have to be pro-vided [PKPS03].

2.3.3 Module Reuse and Integration of Foreign IP cores

”Modularization” and ”Reuse of Modules” (illustrated in fig.2.4) are two essential key prin-ciples of state-of-the-art design processes. They enable short design times and minimizeorigins of error due to the reuse of well-tested components.

The aim of modularization is to divide a huge complex system into several subsystemseasier to cope with, what can be done repeatedly in a design process. Through intelligentpartitioning some components may be reused within the model itself, or already completedmodels from earlier designs may be integrated. The creation of a standard-componentlibrary should be an option considered during the partitioning steps as well. Figure 2.4illustrates this concept of decomposing and reuse.

This principle has formed a completely new branch of (semiconductor-)industry: the”IP 4 Core Business” [GWC+00].

In this business IP core providers offer their know-how and developed models packagedin IP cores. A company might buy these cores for integration into their own design, insteadof developing everything on their own. This integration process has different obstacles toconquer, as the IP provider may use a special distribution format for enclosing the IPitself, or at least uses other languages (for all or single abstraction levels).Therefore module reuse and especially the integration of foreign parts may lead to aheterogeneous design situation. A more detailed discussion of IP core business can befound in section 2.6 at page 42.

4Intellectual Property

Page 22: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 21

Level 3

Level 2

Level 1 Decomposition

Decomposition

Refinement

Refinement

Model Reuse

Already

DeveloppedDec.

System 1 System 2

Figure 2.4: Decomposition, modularization, and module reuse in a design process

2.4 Simulation of Heterogeneous Systems

Today there exists a steadily increasing amount of different design and simulation tools,whereas single tools have reached importance in specific domains or for special purposes.As discussed in the prior section this fact is one of the reasons for heterogeneous systemdescriptions. Heterogeneous system descriptions pose a challenge for an engineer in respectof its validation and verification.

Simulation is one of the means to predict the behavior of a system for validation againstits specification, or to verify special design steps. However there hardly exist simulatorsfeaturing multiple languages and description concepts. In this section methods will bediscussed to perform a simulation of a system represented by a heterogeneous description.

To accomplish this there exist homogeneous and heterogeneous approaches, implyingthe fact that a heterogeneous design does not automatically implicate the need for het-erogeneous simulation, as there exist approaches to transform heterogeneous models intohomogeneous ones.

2.4.1 Homogeneous Simulation

The distinctive feature of all homogeneous simulations is that they utilize only one singlesimulator for system evaluation. Every simulator has its own distinctive special instruc-tion and construction set for control and model description.Thus a system to be simulated by this simulator has either to be designed with these

Page 23: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 22

distinctive sets, or a heterogeneous system description has to be transformed into a ho-mogeneous model compatible to this simulator.

The transformation of a heterogeneous model into a homogeneous one contains some kindof translation. Consider a model using two different languages, possible strategies couldbe:

• The translation of modules described in language A into language B which is usedfor the rest of the system.

• The introduction of a third language accompanied by the translation of all modulesinto language C.

Although the latter approach might sound more complicated, because of the involve-ment of a third language C, the following figures show the reason why it might be the onlypossibility to obtain a homogeneous system model.

Considering the instruction set of a single language A and the set of modules which maybe described by it (L1) compared to that of another one (L2) unveils the major problemwith translation methods due to language boundaries(fig. 2.5). Only the intersection ofboth (L1+L2) contains models which may be described in either language and thus maybe translated from one into the other.

L1

L2

L1 + L2

Figure 2.5: Illustrating the expressible models for two languages: The general situation

Possible variation of this intersection according to mathematical ”Theory of Sets”shows specific situations, where the complete set of modules from one language might betranslated into the other one. In practice these situations will be very rare, as it is onlypossible if one language (e.g. L1) is a subset of or equal to the other one (e.g. L2), asillustrated in figure 2.6.

L1 L2

Figure 2.6: Illustrating the expressible models for two languages: A special case, whereL1 is a subset of L2

Page 24: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 23

The introduction of a third language changes the situation to some extent due tothe introduction of new dependencies. Figure 2.7 shows two different intersection sets toillustrate these new variants.

L1L1 L2 L2

L3

L3

Figure 2.7: Introducing a third language: (a) left: general case (b) right: L1,L2 are asubset of L3

Considering figure 2.7 it is obvious that a possible homogeneous simulation of modulesof language A (L1) and language B (L2) is partly independent on the relation between theirlanguages. The introduced language offers new possibilities due to its own relations. Case(a) of figure 2.7 shows a general case where only subsets of L1 and L2 can be translatedinto language C (model set L3), whereas case (b) shows an extrema where L1 and L2 area subset of L3 and thus all modules L1 and L2 may be translated into language C. In bothcases a homogeneous model is achievable (in case a only for subsets) although the originallanguages L1 and L2 are incompatible to each other.

An illustration for this, not related to simulations, is the compilation of a heteroge-neous programs to obtain an executable. For instance when designing a program for e.g.a 80535 micro controller containing C-parts as well as assembly routines, both languagedomains get assembled and compiled into an intermediate language understandable by alinker which merges the different object models to obtain the desired executable.

Considering language sets and subsets only covers theoretical solutions regarding languagecompatibility by determining their boundaries. In practice there is neither a standard forthe documentation of these sets, nor is it usual to specify them in a languages’ documen-tation.The exact determination of the sets is a very hard task, as is the mapping of a set of realsystems to a set of system models. To implement this approach vague determinations ofthese sets will be made.

Although this example of compiling a program is not related to simulation, the processof the translation within a standard computer compiler is the same which will be used toachieve a homogeneous system description.It will include the analysis of the description in several aspects (syntax, semantics) andthe actual code creation process. The construction of such compilers is a non-trivial taskillustrated in the ”Dragon-book” [ARJ99a, ARJ99b].

There exist several projects related to simulation implementing the approach of creat-ing a homogeneous system description:

• In [bib97] translation is used for a cosimulation of Statemate and SDL5 models. A

5Specification and Description Language

Page 25: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 24

subset of statechart may be translated into SDL.

• The ”European SystemC User Group” provides a VHDL to SystemC converter.With the VHDL-to-SystemC converter you can transform VHDL hardware descrip-tions into SystemC hardware descriptions. The converter supports only subsets ofVHDL and SystemC, so not every VHDL description could be converted. The toolis available for SUN Solaris and PC Linux workstations and includes two short ex-amples. It is available at [Eur].

• University of Verona, Italy provides in [Unia] detailed information on version 1.0of their VHDL to SystemC converter ”VHDL2SC”, containing the translation ruleset. This tool is based on SAVANT [Exp] and adds the ability to translate the IIR6

format generated by SAVANT into SystemC code.

2.4.2 Heterogeneous Simulation

The counterparts to homogeneous approaches are heterogeneous simulations, utilizingmore than one simulator for system simulation. Simulator interaction and couplings formthe basis for this approach. Regarding the interaction scheme between the single parts ofsuch a simulation network there are two major implementation strategies:

• Backplanes

• Direct Couplings

The criteria for a classification to these strategies is the way different simulators communi-cate with each other. Backplanes use a central entity connected to every simulator, whichhas control to the whole simulation. Therefore simulator interaction operates indirect viathe backplane. The other branch of heterogeneous simulation approaches uses specializeddirect simulator-connections. Both options are discussed in the following:

Backplane Approach

As mentioned before backplane approaches utilize a central control unit, connected toeach simulator, to manage the simulation. A backplane introduces a common simulatorinterface which has to be implemented with all simulators, so that all different simulatorsmay be accessed via a special API7. This API provides the necessary mechanisms for datacommunication and synchronization. A backplane takes control of all connected simulators(see fig. 2.8).

To be able to integrate a special simulator into a backplane environment, there has tobe a special wrapper for this specific simulator translating common API commands anddata types into the specific simulator’s command-set as seen in figure 2.8.

6Internal Intermediate Representation [Unib]7Application Programming Interface

Page 26: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 25

simulation backplane(synchronization / data exchange)

User

Sim. 3

electronics mechanicspart 2

software

System model

Sim. 1 Sim. 2

Wrapper 1 Wrapper 3Wrapper 2

part 1 part 3

Figure 2.8: A schematic principle of a backplane

The presence of a common API to all simulators is a key feature of backplane environ-ments and offers multiple advantages:

• Easy integration of a new simulator into the simulation environment, especially ifthere already is a wrapper which may be reused.

• Abstraction of simulators: Communication between simulator and backplane issimulator-independent which means data transfer and control are standardized ac-tions.

• For a possible speedup modules may be parted into several submodules which aredistributed to multiple instances of a simulator. The integration of multiple instancesof a simulator is very easy due to the reuse of the wrappers.

A correct wrapper implementation is essential to a backplane environment. A functioncall of a backplane may result in different actions with different simulators. The actualwrapper translates this general backplane command to the specific simulator’s syntax.Data type and time format conversion is another task of the wrapper, as each simulatorfeatures distinctive internal formats.

Thus a wrapper has to follow strictly the protocol of a backplane, which is essentialto each backplane representing its distinctive features. A backplane’s protocol may beconsidered as the combination of three rule-sets [Bar99].

• Communication-rules describe the connection-handling between the backplanes andsimulators, whereas the backplanes act as master and are therefore responsible for

Page 27: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 26

connection establishment as well as sustaining and disconnection mechanisms. Datatransfer control during simulation is necessary to enable correct ordering of simulatorinterconnection communication.

• Synchronization-rules are used for the synchronization of the different modules. In-terconnections between models require mechanisms for data-communication at theseconnections to provide data validity and avoid deadlocks.

• Implementation-rules describe the implementation of the wrappers, and may beseen as translation scheme between the common-API commands and the unique anddistinctive simulator command-sets.

Sim. 1

Wrapper 1

Sim. 2

Wrapper 2

simulation backplane

Implementation−rules

Communicationrules

Synchronisation−rules

Figure 2.9: A backplane protocol consists of three rule sets: Implementation-rules, com-munication rules, and synchronization rules

Most backplanes as well as their interfaces are implemented proprietary according totheir specific intentions. However there are intentions to develop a standard for backplanes.

The ”CAD Framework Initiative” (CFI) was founded in 1998 as a non-profit orga-nization. It’s aim is to establish standards for the integration of CAD tools to enabledesign-data management as well as tool interoperability and a common user interface.Development was divided into several sub-projects including:

• Design Representation Standard

• Data Management

• Inter-Tool Communication Standard

• Tool Encapsulation Specification

• Computing Environment Services Standard

• Multi-Simulator Backplane

Page 28: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 27

Interesting at this point is the CFI backplane standard. This standard defines theinterface between different simulators and a backplane itself. It doesn’t represent an im-plementation of a specific backplane, but a general interface between an arbitrary simulatorand an arbitrary backplane. This standard defines the partitioning of a system, commoncommunication-rules, synchronization-rules, implementation-rules, and backplane opera-tion as well as initialization at an abstract level intended for a general backplane descrip-tion. A detailed discussion may be found in [Sim98].

There are many implementations of backplanes available, two of them briefed at thispoint for further illustration:

In [NMK+02, KWG+02] a SystemC based backplane is used for the simulation andglobal validation of micro-electro-mechanical systems, whereas a free-space optical cross-connect using mirrors actuated by electrostatic devices is the actual DUT 8. The controlsubsystem of this device was implemented in SystemC, the electro-mechanical part inMATLAB and the behavior of the optical devices (mirrors, lens, beam generators anddetectors) in C++.In this approach hierarchical network lists of modules are used for system descriptions.Each module consists of a behavior and ports. These ports may be connected via com-munication channels. As the modules use different languages the implementation detailsdiffer from module to module. Wrappers are used to implement the general mechanismsfor each module. They constitute the interfaces of the modules and isolate their inter-nal behavior. Internal ports are connected to the module and external ports connect themodule via channels to the global simulation. For convenience an automated generationof this communication and simulation interfaces is featured, based on internal librariesand specification of the module’s behavior and ports. Figure 2.10, illustrates this processand shows the resulting schemata of a cosimulation utilizing this approach.

Figure 2.10: A SystemC based cosimulation backplane with automated interface genera-tion [KWG+02]

8Device Under Test

Page 29: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 28

To gain confidence of the desired approach a cosimulation of the mentioned opticalcross-connect was performed to test the abilities of this system. The actual representationof this example is illustrated in figure 2.11:

Figure 2.11: Cosimulation of an optical cross connect using a SystemC back-plane [NMK+02]

The overall system simulation was performed on a SUN Ultra-Sparc 1 in about 30seconds, and resulted in a successful test of the design and the cosimulation environmentused for this test. where a SystemC based backplane is used for multi-domain and multi-language cosimulation.

Page 30: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 29

In [Bar99] Tvrtko Barbaric discusses HW/SW codesign based on a backplane approach.The developed cosimulation environment consists of the following three parts:

• Backplane program

• Interface-Link modules

• Client-Simulators

The implementations of these parts are based on a predefined backplane rule-set as illus-trated on page 25. The backplane features event-driven scheduling with an event queueordering future events. All data transfer between processes is relayed at the backplane toact as a global event queue. The backplane’s scheduler manages this queue and transfersevents according to their global order, waiting for the response after each transfer.A general VHDL simulator interface for this backplane (as illustrated in figure 2.12) isintroduced to achieve a hardware software cosimulation.

Figure 2.12: A backplane communication interface for a VHDL model [Bar99]

Access to the VHDL model is based on several receive and send nodes and the use of aforeign architecture as shown in figure 2.13 at page 30. Foreign architectures are a specialfeature of the involved VHDL simulator offering the option to integrate foreign C-codeinto the simulation. The master node avoids deadlocks and controls the data transfers viasending and receiving special commands to and from the backplane.For a conclusion the used conservative timed synchronization strategy is discussed inrespect of several optimization possibilities.

Page 31: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 30

Figure 2.13: The different entities of the introduced VHDL interface [Bar99]

Direct Couplings vs. Backplanes

Contrary to backplanes many approaches for a heterogeneous cosimulation are based ondirect simulator couplings. The main difference is the absence of a central control entityas featured with backplanes. With direct coupling two simulators are connected withoutconsidering interfaces to other simulators or interface standards. This includes minimalinterfaces dealing only with special needs for a single project. The obvious advantage ofdirect couplings is that they range from minimal project specific approaches to generalsolutions for a powerful general purpose simulator interconnection.

The origin and strategy of these approaches is very intuitive: If a simulator is not ableto perform all tasks a designer needs it to, it has to be enhanced. A simple approachwould be to enhance this simulator with special methods to integrate further functional-ity/resources by connecting a second simulator. An example would be the integration ofa MATLAB Engine for mathematical computation as proposed in [Thea].

The use of a backplane would always inhibit the design of a complete interface regard-ing to the standards and protocols of the backplane, which is time-consuming A directcoupling would only need the implementation of features needed, and is even more flexible,as backplanes show limitations due to their used concepts and protocols.A major drawback of such a dedicated interface is its reusability as it is limited in sensi-tivity to the implementation strategy. A layered approach using standard functionality asfound with backplanes would enhance it significantly.

The most contrary feature of direct couplings versus backplane approaches is the lack ofa central control unit. The operation of the complete environment, including synchroniza-tion and data management, is up to the simulators themselves and implied by the interface

Page 32: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 31

implementation. A more detailed discussion of backplanes versus direct connections canbe found in [Sim98].

In [Tud00] a dedicated direct simulator connection is used for a hybrid cosimulation.Signal and Simulink are used to model hybrid systems. Signal is a powerful tool for model-ing complex discrete behaviors and Simulink is used to describe continuous dynamics. Thecombination of both is utilized to offer a cosimulation of a discrete controller controllinga continuous environment represented by a plant, as illustrated in figure 2.14.

Figure 2.14: A hybrid system containing a discrete controller and a continuousplant [Tud00]

Two approaches to perform the desired cosimulation are presented in this work, whereasboth make use of the ability of both tools to create stand-alone simulation code. In thefirst one, the system part modeled with Signal is the master and controls the changesin the continuous part, by using Simulink procedure calls. In the second approach thecode created from the Simulink model is the master and the link between the discrete andcontinuous parts is implemented via global variables.

The second approach is used to simulate the prior mentioned hybrid system. TheSimulink main file runs the model simulation in an infinite loop illustrated by the followingpseudo-code:

while (true){OneStep_Simulink_model;

}

After the calculation of one step, the simulation advances by a single time-unit. Tosynchronize the Simulink and Signal simulation this loop was altered by the author toinclude synchronous or asynchronous events of parts modeled in Signal:

Page 33: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 32

while (true){OneStep_Simulink_model;

synchronous : OneStep_Signal_controller;

asynchronous : if "triggered" then OneStep_Signal_controller;

}

Data transfer is achieved via global variables as mentioned before. For a practical testingthe approach was used to perform a cosimulation of a siphon pump machine.

The availability of stand-alone code of the simulation provides great flexibility in re-spect of interconnectivity, as no proprietary interface of a simulator has to be used for aninterface implementation but there might be the possibility to gain access to the simulationkernel and its environment

The ability of Simulink to create stand-alone code of a simulation was used by anotherproject as well, for the implementation of an object oriented interface [Mad00]. Thisinterface may be used for direct simulator connections as well as backplane approaches.

LaSRS++ is an object-oriented framework used by the NASA to create real-time sim-ulations. As many simulation customers of NASA Langley Research center have selectedMathWorks Simulink for their designs, the simulation software group at Langley createda reusable, object-oriented interface to integrate Simulink simulation code, provided viaits Real Time Workshop, into the Langley Standard Real-Time Simulation.For the realization of an object-oriented interface, the produced code was altered to beaccommodated within a single class and its member functions as illustrated via an UML9

diagram in figure 2.15.

Figure 2.15: An UML diagram for an object-oriented interface for Simulink mod-els [Mad00]

9Unified Modeling Language

Page 34: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 33

A simulation can be performed with the available public member functions. Thesimulation code is heavily related to the original code for the chosen Generic RealTimeMalloc target found in grt malloc main.c. Thus the features of the optional external mode(for a single module, as external mode uses global data) and Simulink data logging featuresare available within the code. For operational use the interface was design to support dataexchange via model ports and initialization and update functions were implemented tooperate the model.

2.5 Simulators

Simulators represent the basis for each simulation. Each simulator features a specificdescription method in respect of used languages and design methods. With the modelof computation the expressiveness of models featured by a simulator can be illustrated.It may be used to illustrate the computation algorithm of the simulator as well as thefeatured design elements.

Due to the limitations of single simulators a connection of several kernels is sometimesnecessary to simulate a heterogeneous modeled system. The model of computation for thiscosimulation setup has two main aspects; the synchronization of the various simulatorskernels and the utilized means of data transfer for the communication system.

The following two sections cover several models of computation as well the basics foran implementation of a simulator connection.

2.5.1 Models of Computation

During a design process a system may be described with different languages and formal-izations. Languages can be represented by a set of symbols and tokens, a syntax offeringrules for valid combinations of these symbols and tokens, and its semantics representing arule-set for the interpretation of the symbol and token combinations.

The model of computation describes a more abstract aspect of the design abilities,although it is heavily influenced by the used description language. It may be seen as adescription of the behavior and interaction of different blocks of a design.A design is usually represented as a network of different modules, which interact witheach other and maybe with an extern environment (e.g. a testbench). The model ofcomputation defines the behavior of these modules as well as the interaction betweenthem.The underlying model of computation of a language defines the power of a language incombination with its syntax. Thus it describes its expressiveness - what can be describedwith this language and how. The syntax describes the means of description, thus influencesthe readability, compactness, modularity and reusability of a system description.The semantics can be considered as an aspect of the model of computation. For itsdescription there have evolved two different approaches, whereas a language may containboth [ELESV97]:

Page 35: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 34

• Operational semantics date back to Turing machines. With operational semantics,the meaning of a language is described by an abstract machine and the actions itmay take.

• Denotational semantics describe the meaning of a language via relations.

For operational semantics, the behavior of the abstract machine is a feature of the modelof computation underlying the language. For denotational languages the same feature isdescribed by the kind of relations which are possible.Other aspects of the model of computation are communication style, how the behaviorof individual blocks is consolidated to the behavior of more complex systems, and howhierarchy is involved in abstracting such complex systems.

There are a lot of different models of computation [ELESV97, JB00], some compatiblewith each other so that they may be used simultaneously in a system, some not.

Discrete Event

A discrete event (DE) simulator usually has a global event queue, storing occurred eventsordered via a time stamp [ELESV97]. This global event queue implicates a total orderingof all events. Thus DE modeling may become expensive as the sorting of time stamps canbe very time-consuming with a complex system model.

A major advantage of DE simulation is, that only changes of single system states andparts have to be propagated and processed instead of the complete system. Therefore DEsimulation is most efficient with complex system, where the different subsystems operateautonomously, or become frequently idle. This means that the activity of a system isminimized and the DE paradigm becomes very efficient.

Simultaneous events however pose a serious challenge to DE simulators. Events have tobe ordered, but if they are concurrent they are not because of their identical time stamp.

t

tA B

Ct

A B

Ct

A B

C

t t+dt

(b) (c)(a)

Figure 2.16: The effect of simultaneous events in discrete event computational mod-els [ELESV97]

Figure 2.16 illustrates this situation and unveils several problems that occur withsimultaneous events. Let’s consider three processes A, B and C whereas B has zero delaytime. Process A produces two events with the same time stamp. The question whether

Page 36: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 35

process B or C should be called first is nondeterministic as shown in case (a). This decisionhas a serious impact on the result. Let’s consider that process B is the first to be invoked.Because it has zero delay time it produces an event with the same time stamp as well asshown in case (b). The designer of a simulator is now faced with a decision between threepossibilities:

• Invoke process C once, and interpret both input events concurrently

• Invoke process C twice, first consider input event produced from process B

• Invoke process C twice, first consider input event created by process A

Some languages (e.g. VHDL) and simulators introduce a second time line implementedby delta delays to prevent this. This dual scale simulation time is divided into equidistantslices, which represent single time steps. A single time step may then be broken into(maybe an infinite number of) delta steps. The delta timing information is hidden fromthe user, thus the reported simulation time contains no delta information. Zero-delaysmay then be described as delta-delays enabling an ordering of concurrent events.

Case (c) of figure 2.16 shows the result of delta delays. Process C has now two inputevents, one created by process A with time stamp t and one created by process B withtime stamp t+dt. So process C will be invoked two times, whereas it will see the inputevent from process A at the first invocation and the event from process B at the secondone. Thus the events are ordered in a deterministic manor.However delta delays don’t avoid the problem completely and introduce new problems asdiscussed in [Gos02].

Discrete event simulation is often used in digital hardware design, Verilog and VHDLfor instance represent DE based languages.

Synchronous Models

Like DE models, synchronous models use a generic clock for a linear advancing represen-tation of time [ELESV97]. In contrary to DE models, in a synchronous model of computa-tions all signals have events at every single clock cycle. The ordering of concurrent eventswithin a time-step may be totally ordered, partially ordered, or even unordered dependenton the actual model of computation. A pre-order might be determined by data precedenceand dependencies, whereas cyclic precedences and dependencies shall not be allowed dueto obvious reasons, and arbitrary decisions left could be judged by the scheduler.Comparing synchronous models to DE models, the simulator is simplified due to thefact, that no sorting of the signals is required ,as all signals have events at every time-step [ELESV97]. This simplification of the simulation engine comes with the lack ofminimized event, as events for all signals at each clock tick have to be processed.

With systems incorporating signals which change their values rarely or containing partswhich are inactive most of the time, a synchronous simulation strategy is very inefficient

Page 37: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 36

due to the calculation of a huge amount of nonrelevant events. As a solution to thismulti-rate systems or the implementation of special tokens representing inactivity may beconsidered.

Synchronous models or cycle-based models, will however show advantage in very activesystems due to the simplified simulator and fit very well for clocked synchronous circuitssince these correspond well to the implied strategy.

Dataflow Process Networks

Describing a model by dataflow, a system is specified by a directed graph. A graphas shown in figure 2.17 contains nodes (or actors) reflecting a computation, and arcscombining nodes to streams (totally ordered event/token sequences). This representationmay be hierarchical so that an actor may refer to another directed graph.Event production in this model is called token firings [Hub98]. Each firing consumes andproduces tokes, and represents an indivisible part of calculation. A sequence of firings,scheduled in a list as shown in fig 2.17 is a process.

Figure 2.17: Dataflow networks: (a) a directed graph (b) a corresponding single-processorstatic schedule [ELESV97]

2.5.2 Simulator Connections

In subsection 2.4.2 starting at page 24 several strategies for cosimulations are mentioned.In this chapter aspects of an actual implementation of simulator interfaces needed by thesestrategies will be discussed. As mentioned in the introduction to simulators on page 33there exist two main aspects, which will be considered in the following:

• Synchronization

• Communication media

Page 38: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 37

Synchronization

For a synchronization of different simulators there exist several strategies as discussedin [Sim98]. These different approaches can be classified in between the following twoextrema:

• Optimistic Simulation: With this synchronization method, each simulator calculatesat its own speed. If a signal is received from an external simulator, its time ofoccurrence has to be determined correctly. A problem results from the possibilitythat the simulator’s actual internal time could be in the future relatively to the timeof the received event. If this occurs a ”backtracking” (see fig. 2.18) of the simulatorhas to be performed to put it in the state it has had at the time of the received event.It is obvious that storing information for backtracking needs an enormous amount ofmemory. Furthermore it has to be available within the simulator. TyVis is a projectbased on the Warped simulation kernel, offering an optimistic simulation based onthe Timewarp algorithm discussed in [Sim98].

• Lockstep Algorithm: With the lockstep algorithm the need for backtracking methodsis not present, as all simulators calculate synchronous and equal time-steps.

1 5

Real Time

TimeSimulation

SimulationTime

SimulatorB

SimulatorA

1

1 2

2

5

5

event

’’backtracking’’

Figure 2.18: Backtracking within a simulation

Figure 2.18 illustrates the disadvantage of backtracking operations; calculated resultshave to be abandoned, what can lead to a very inefficient simulation if a backtrackinghappens frequently. An actual approach might lie in between these two extrema as severaloptimizations to the lockstep algorithm can be applied without the need of backtracking.Considering DE-Event simulators a synchronization at time-steps might suffice, withoutthe need of global synchronization of the internal delta-cycles. This would result in apartially optimistic solution, as within a time-step there is no interference desired. Ofcourse such small improvements to the very conservative method of the Lockstep Algo-rithm depend heavily on the desired strategy and imply restrictions to the design, as forthe mentioned example events within a time-step would not be supported.

Usually the representation of time within simulators differ from each other. Besidesthe question of discrete or continuous time, the actual implementation may differ in therepresentation of time-units.

Page 39: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 38

A time-unit might only be considered as means of ordering, or may relate to an equidistandtime-unit like seconds. As introduced with optimistic simulation strategies time does notnecessarily increase steadily within a simulation. Simulators for continuous systems mightuse the following algorithms to proceed in time, including an option for backtracking;

• Calculation for equidistant rising time-steps

• Calculation for non-equidistant rising time-steps.

• Calculation for non-equidistant, not necessarily rising time-steps, with the possibilityof ”backtracking”

It is obvious that the seclection and success of an actual implementation of a synchroniza-tion strategy is heavily influenced by the internal simulation paradigms of the involvedsimulators.

Communication Media

For means of communication between different parties there exist two common paradigms:

• Shared ResourcesShared memory may be used as a communication media. For synchronization a read-modify-write mechanism is commonly used. During access by read and write opera-tions the referenced memory location is locked to ensure data consistency [ELESV97],thus these functions have to be implemented as atomic functions. Atomic means theyhave to be indivisible so for instance the interrupt mechanism of an operating sys-tem has to be disabled during these functions. For simulator interconnections sharedmemory is seldomly used.

• ChannelsChannels represent a direct point to point connection, thus the data flow is ”chan-neled” to a specified destination. The implementation of a channel may rely onmany different medias like PC interfaces (serial, parallel, USB10, IEEE 139411, net-work functions (sockets, RPC12), or local file mechanisms like pipes.

State of the art interfaces make heavy use of channels. Therefore the three majorapproaches Named Pipes, RPC, and sockets are presented at this point to illustrate theirdistinctive features.

10Universal Serial Bus11Often referred as FireWire or iLink12Remote Procedure Call

Page 40: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 39

Named Pipes

Named pipes provide the possibility to manage communication via standard file primitives,as they seem like normal files to the user. Named pipes are provided on many platforms,for example in Windows/NT as well as UNIX, and thus represent a platform spanningcommunication method.The possible use of file primitives for access is very interesting, as many tools include somefunctions for file access, but no interface to third party components. Furthermore theyoffer a simple but efficient method for process synchronization:If a process wants to read of an empty pipe he gets suspended till another process fillsthe pipe with data. This enables an easy creation of FIFO13 synchronization mechanismsbetween different processes.

For a speed-up named pipes can be created in a temporary file system located inmemory instead on a disk. The possibility to create such ”ramdisks” is available withalmost every operating system.A further enhancement to named pipes is the combination with network functions likesockets to enable network connections and thus distributed simulations.

In [RPS98] pipes are used for the integration of external components into a VHDLsimulation on a Windows NT platform. Although some simulators offer interfaces tospecial languages as Modelsim14 SE does with its FLI15 for C-models, the VHDL languagespecification [IEE02] does not provide such interfaces and therefore these are proprietaryand simulator dependent. However VHDL provides file primitives like file open, file close,read and write.

Remote Procedure Calls

Remote procedure calls represent a high level of abstraction of a communication. Thesimple term remote procedure call does not imply a special implementation, but only thepossibility to execute remote tasks via simple function calls. The functionality of RPCcan be described as a combination of several rule sets:

• A set of rules for marshaling and unmarshaling parameters and results. This is theactivity that takes place at the point where the control path in the calling and calledprocess enters or leaves the RPC domain.

• A rule-set for encoding and decoding information transmitted between two processes.

• Operations to invoke an individual call, to return its results, and to cancel it.

• Process structures to maintain and reference states shared by the participating pro-cesses.

13First In First Out14A VHDL Simulator of Model Tech15VHDL Foreign Language Interface

Page 41: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 40

The communication primitives are implemented according to a client server principleas illustrated in figure 2.19.

main {

}

call remote procedure 1

Computer 1

main routine

Server 1providing procedure 1

Server 2providing procedure 2

procedure 2call remote

proc. 1 {

return(value)}

proc.2 {

return(value)

}

RPC A RPC B

Figure 2.19: Nested remote procedure calls

Two servers (Server 1, Server 2) provide two different procedures (procedure 1, pro-cedure 2) for remote use. A client may access these function via a RPC. In figure 2.19a main program executing on a simple client makes a remote procedure call (RPC A)of procedure 1 provided by server 1, whose functionality is based on remote procedure 2which is provided by server 2 (RPC B).This illustrates that RPC can be nested, whereas the user doesn’t recognize that theinvoked function is calculated on different machines.

As mentioned earlier, RPC does not imply a special implementation and furthermorethere is no general standard an implementation has to comply with.This means that different RPC implementations offer distinctive features and are nom-inally incompatible with each other. Features to be desiref for an RPC implementationcould be the following due to their influence on usability, design, functionality, and costsof RPC based applications:

• Support of synchronous and/or asynchronous operations

• Support of different operating systems (client/server)

• Support of file systems

• Support of different networking protocols

• The availability of the server functionality individual application or only bundledwith a special server operating system

For an application the use of multiple RPC implementations may be considered as well,due to the distinctive features of special implementations.

Page 42: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 41

Sockets

Sockets represent an elegant mechanism for managing I/O tasks, providing the ability forinterprocess communication using file descriptors. This is the common mechanism used inthe Unix domain. Fact is in Unix every I/O task is based on file descriptors and socketswhere needed.

There are multiple variances of sockets available, designed for the same intention, butdiffering in their technical implementation. The availability of a special socket implemen-tation depends on the operating system(s) used, whereas the decision for one may be basedon the entailed operational constraints. Example of these constraints are : connection lessvs. connection oriented, local vs. Internet domain, and so on. As stream sockets will beused in this work, a more detailed discussion on sockets will follow in subsection 4.1.1 atpage 71.

When using connection-oriented channels like stream sockets, a single socket is oneend point of an interprocess communication channel. A communication channel is basedon a client server model, whereas the client and server processes use dedicated sockets fordata transfer. The system calls for a connection establishment differ between server andclient and are illustrated in the following.

The typical steps of a client during a connection are as follows:

• Creation of a socket

• Connect to the server via a pre-known address

• Data transfer

• Close connection

A server works a bit different:

• Creation of a socket

• Bind the socket to an address

• Listen to connection requests on this address

• Accept a connection

• Data transfer

• Close connection

For further illustration an actual implementation of simple server and client programsusing stream sockets may be found in appendix B.1.

For socket connections there exist various libraries and some operating systems providestandard functionality for a simple realization of a socket connection. Linux for instanceincludes all necessary routines and primitives within its standard C libraries.

Page 43: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 42

2.6 IP Core Business

Due to market pressure there is always the need of shortening development duration.Modularization and the reuse of modules are key methods in accomplishing this. Thebuilding and reuse if standard component libraries is an efficient way implementing thesemethods.This design agenda has lead to the occurrence of a whole industry branch, called IP16

business [GWC+00], which is presented within this section. Due to the rising complexityand the need of minimized design times, this business sector, dealing with complete designsof components, has gained more and more importance over the years.Todays development environments shall feature the requirements underlying this businessscheme, what is the reason why this topic shall be discussed in more detail.

Prior to a detailed discussion of the business it is necessary to define the item IP core.”Intellectual Property” may be represented and described in many different ways. It mayconsist of algorithms, software, hardware, methods, and many other components.IP cores can be seen as ready-to-use and maybe plug-and-play products. This means theyare virtual components featuring a well defined access interface. The interface may includesupported tools and access-functions as well as usage informations.

For an introduction the global players in this business are presented and discussed asfound in [GWC+00]:

• IP Core Provider

For a service provider, customer service is a matter of first magnitude. To com-pete with rivals an IP business company must provide ”quality of service” to theircustomers. This includes complete documentation, an easy reuse methodology aswell as quality assurance. A major problem with this is the lack of standardization,which makes IP evaluation and comparison time-consuming and difficult. The majorconcerns of an IP core provider contain:

– IP core representation: Selecting the representation of IP is a very sensitivetask. The considerations whether to offer the IP as hard or soft IP, and pa-rameterizable or not, are as important as the question of adaptivity by the IPintegrator. Hard IP is predictable but not portable, whereas soft IP is portablebut not predictable. For instance production masks for a CMOS manufacturingprocess are predictable but not well portable. An algorithm is well portable,but performance on a special processor is limited predictable.

– Documentation affects the usability of the provided core, thus it should becomplete, well structured, searchable, and as concise and comprehensive aspossible. It should contain functional descriptions as well as integration andverification guidelines.

16Intellectual Property

Page 44: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 43

– Quality Assurance: Confidence is a major issue with service providers. Thusthe provided IP core should be able to verified in as most as possible respects,considering possible parameter variations as well. Methods should be providedto show the customer that provided verification methods are sufficient.

• IP Integrator

Standards are the designers best friend in the IP integration area. Standards enablesthe IP integrator to explore, compare and integrate the foreign components conve-niently. From the view of an IP integrator the following aspects are most importantand should be featured by any design environment:

– Exploration: During system-design engineers need to conquer all design alter-natives and the appropriate IP cores for those. Therefore the concept space hasto be explored as well as the offerings on IP cores.

– Integration: IP integrators have to rely on support and information providedby the IP vendor. The quality of IP vendor service, IP core information, anddocumentation is the basis for a successful system integration. In this respectverification is a very important task. The validation of the provided core isa necessary step during integration. The possible reuse of verification mecha-nisms for system validation is a considerable option, as estimations concludethe system-verification integration part to be up to 90% of total integrationexpenses [BG02].

– Reuse Methodology and Environment: For a system design company it is veryefficient to integrate the IP core reuse agenda into company philosophy. Thismeans a company-wide design-for-reuse culture and infrastructure. A manualto this may be found in [MP02].

The role-play between these parties is quite obvious. The IP provider offers its know-how packaged in IP cores and another company buys this know-how and IP integrators(designers) of their design department try to integrate this know-how into corporate de-signs.

A third party, the IP tool developers, facilitates the whole system by providing nec-essary tools for IP development as well as IP-integration. A realization of the idea of IPbusiness is not an easy task, as every party and the business model itself have their owndistinctive issues and constraints as discussed in [GWC+00] and discussed prior. Theseissues refer to business as well as technical aspects.

Currently there exists neither a standard IP business implementation nor a standardbusiness model. The business model should encompass pricing, service, legal issues, aswell as security rules. Important issues to be considered include the following ones:

Page 45: Design and Implementation of a Cosimulation Environment ...

CHAPTER 2. BACKGROUND AND RELATED WORK 44

• Legal Issues are a main concern of business model. Some of them may be overcomewith contracts, copyrights or patents. Without definitions of legal responsibilities ofan IP user however, there is always the threat of legal actions from the IP vendorto the IP user due to infringement of intellectual-property rights. Thus a completesolution is mandatory.

• The security of know-how is a very difficult task even in a single company. Whentrading with this valuable property, secure mechanisms have to be provided for datatransactions and data storage to aid legal methods.

In respect of technical issues, the encapsulation and encryption of know-how is asimportant as the development of new methodologies to enhance reusability and the inte-gration process.

The presented introduction of IP core business represents only a short briefing of theidea and the contained issues and problems, and is far from a complete description. Forfurther information on this topic the following articles shall be mentioned, covering general,integrational as well as implementation aspects of a successful IP business implementation.

• Essential Issues for IP Reuse [GWC+00]

• Reuse and Protection of Intellectual Property in the SpecC System [DG00]

• The Use of SystemC for Design Verification and Integration Test of IP Cores [FFS]

• Reusable Verification [BG02]

Evident in these papers is the significance of cosimulation technologies in the IP corebusiness. As mentioned in chapter 2.3 on page 16 heterogeneity in respect of systemdescription can arise due to the integration of foreign designs.IP cores may use special description formats to hide the internal IP or just a differentlanguage. Therefore cosimulation methods are needed to enable a system simulation.

From the view of the IP core provider appropriate cosimulation technologies couldfeature an interconnectable self-executing simulation of the IP core to be included withthe system-simulation of the customer, resulting in a hidden, but usable IP Core.Network functionality could feature the option to have some IP Cores simulations availableon a public server, which interested customers could evaluate briefly via connecting theirdesigns to this server.

Page 46: Design and Implementation of a Cosimulation Environment ...

Chapter 3

Design of a HeterogeneousCosimulation Environment forSimulink, Modelsim, and SystemC

This chapter covers the design of a heterogeneous cosimulation environment for designenvironments using Simulink, Modelsim, and SystemC. These dedicated tools have theirdistinctive features and vary from in many aspects from each other. Therefore, prior toa design of a cosimulation environment, the distinctive features of these tools have to becollected and considered to determine the basic conditions for possible solutions.

According to these basic conditions a model of computation will be designed for thecosimulation. The global cosimulation concept, shown afterward, completes the generalcomputational model with details in respect of a realization.

Finally possible options for the realization of interfaces between the cosimulation en-vironment and the designated simulators are investigated and concepts for an implemen-tation presented.

3.1 Development Profiles

The objectives illustrated at page 12 represent the general task set for the intended de-velopment process. According to some considerations of the information found in thebackground chapter, several master profiles for the actual design and implementation pro-cesses of the entire cosimulation environment and its interfaces were established. Thesemaster profiles determine desired features of the intended solution and were chosen asfollows:

• Easy adaptability for new simulators as well as new technologies, such as communi-cation technologies and the integration of security features.

• The ability of distributed simulation.

45

Page 47: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 46

• Interconnections of simulators on different platforms shall be possible.

• Implementation independency: For single simulators in the cosimulation environ-ment it shall be nonrelevant which tools have been used for the design of the othermodules.

• No distribution of model IP1 and know-how via the cosimulation-interface.

• Minimization of overhead to create and conduct a cosimulation as well as the prac-tical implementation (e.g. calculation time, memory needs).

• Easy usability.

• Minimal cosimulation setup time for a new model.

These objectives originate from the fact that the result of this theses is intended forproduction use. Therefore it shall not be a technology demo of theoretical options, butprovide a ready-to-use solution.

To ensure this real-world usability, the designed environment is tested with an up-to-date system currently developed in industry.For the implementation Linux workstations are used, as well as standard programminglanguages as C in combination with standard libraries.

3.2 A brief Overview of Simulink, Modelsim, and SystemC

To determine the basic conditions for the development of a cosimulation environment, theinvolved tools will be briefed within this section.

3.2.1 Simulink

This subsection provides general information about Simulink and related add-ons. For acharacterization of these tools, the following quotations were taken from their respectivemanuals [Matc, Matb, Mata, Matd].

”Simulink is a software package for modeling, simulating and analyzing dynam-ical systems. It supports linear and nonlinear systems, modeled in continuoustime, sampled time, or a hybrid of the two. Systems can also be multi-rate,i.e. have different parts that are sampled or updated at different rates.For modeling Simulink provides a graphical user interface (GUI) for buildingmodels as block diagrams, using click-and-drag mouse operations. With thisinterface you can draw the models just as you would with pencil and paper (oras most textbooks depict them).”

1Intellectual Property

Page 48: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 47

”The Real-Time Workshop generates optimized, portable, and customizablecode from Simulink models. Using integrated makefile based targeting support,it builds programs that can help speed up your simulations, provide intellectualproperty protection, or run on a wide variety of real-time rapid prototyping orproduction targets.”

”The Target Language Compiler tool is an integral part of the Real-TimeWorkshop. It enables you to customize the C or Ada code generated fromany Simulink model and generate optimal, inlined code for your own Simulinkblocks. Through customization, you can produce platform-specific code, oryou can incorporate your own algorithmic changes for performance, code size,or compatibility with existing methods that you prefer to maintain.”

Summarizing these quotations, Simulink is a powerful tool with an graphical interfacefeaturing the design and modeling of a system and the simulation and analysis of thecreated design. As Simulink is integrated into MATLAB, the simulation results can beanalyzed and visualized within MATLAB easily.

With the Real-Time Workshop (RTW) feature, a stand-alone executable of the modelsimulation can be created to speed up the simulation. This executable needs less memory(as not the complete MATLAB GUI has to be loaded) and its code can be adapted tosomeone’s needs.

The code creation process of the RTW is based on the Target Language Compiler(TLC). There exist some default targets with their distinctive features, illustrated in ta-ble 3.1. Furthermore the user is encouraged to alter these targets and is offered the optionto create new ones living up to his own expectations.

The design process in Simulink uses data-flow oriented block diagrams. Simulinkprovides several default blocks, organized in block libraries according to their behavior.The following standard blocks are included in Simulink block library since library version4.1:

• Sources are blocks that generate signals, what means they are blocks with output(s)but no input(s), e.g., External Input, Constant, Clock, Signal generators, Importfrom workspace ...

• Sinks display or write block outputs, so they offer input(s) but no output(s). Ex-amples are External Outputs, Scope, File export, and Workspace export.

Page 49: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 48

Feature GRT Real- RTW DOS Tornado S-Func RTTime Embedded Windowsmalloc Coder

Staticmemory Y N Y Y Y Y Y

allocation

Dynamicmemory N Y N N Y Y N

allocation

ContinuousTime Y Y N Y Y Y Y

Supportsexternal Y Y N N Y N Ymode

Intendedfor rapid Y Y N Y Y N Y

prototyping

Executes inhard real Y Y Y Y Y N Y

time

Nonreal-time Y Y Y N N N N

executableincluded

Table 3.1: Features supported by several Real-Time Workshop targets

Page 50: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 49

• The Discrete blocks library contains blocks that describe discrete-time components(e.g., Unit Delay, Discrete Time Integrator ...).

• Continuous blocks describe linear functions (e.g., Integrator, Derivative ...).

• Math blocks contain general mathematical functions, for instance Summation,Product, and Gain.

• Functions and Tables blocks describe general functions and table look-up opera-tions.

• Nonlinear blocks describe nonlinear behavior as found in saturation for example.

• Signal and System blocks allow multiplexing, demultiplexing, implement externalinput/output, pass data to other simulation parts, and perform other functions, suchas Mux, Demux, Bus Creator, Goto and many more.

• Subsystem blocks can be used to create subsystems containing single modules ofa design.

• The Blocksets and Toolboxes library contains the Extras block library of spe-cialized blocks (e.g. Neural Network Blockset, DSP Blockset ...)

• Demo blocks contain useful MATLAB and Simulink Demos.

More details and a complete Block Reference may be found in chapter 9 of the Simulinkuser guide [Matc].

Simulink offers the ability to model continuous systems and uses a real-world relatednotification of time within the design. A design may include discrete rates for block com-munication, specific delays and continuous states. To proceed in time Simulink providestwo options according to the first two possibilities offered for simulations of continuoussystems at page 38.Simulation results can either be calculated at equidistant time-steps, or a variable time-step size determined by Simulink can be featured.

Further options of a Simulink simulation include the start and end time of the simula-tion and the desired solver mode for the calculation of continuous states. For more detailedinformation on available solver modes it is referred to Simulink manuals [Matc, Matb].

A simulation may be started within the Simulink GUI, or at the MATLAB commandprompt.

3.2.2 Modelsim

Modelsim is a very widespread HDL2 simulator offered by Modeltech, which is available forseveral platforms including most Windows operating systems, Unix (and its derivatives),

2Hardware Description Language

Page 51: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 50

Solaris, and Linux. Modeltech itself claims Modelsim to be ”The world’s most popularHDL simulator.”

Due to a special simulation kernel Modelsim is able to simulate both VHDL3 andVerilog transparently within a single design, with a common intuitive graphical interfacefor development and debugging at any level, regardless of the language.

A major feature of Modelsim is the availability of several interfaces to third partysoftware and therefore its adaptivity. Via several different interfaces (e.g. PLI4, FLI5,Tcl/Tk 6 interface) it is possible to take influence on the simulation, connect third-partysoftware, and integrate custom code into the simulation.

There are different versions of Modelsim available offering different interfaces, whereasthe SE version is the most powerful and complete one. For this thesis, the interestinginterface is the FLI (only present in the SE Version of Modelsim), which enables theintegration of custom C-code into the simulation and which includes special functions forthe control of the internal simulation. Anticipated, this interface will be used for therealization of the cosimulation interface.

The internal simulator of Modelsim, vsim, operates according to the DE paradigmdiscussed on page 34 including the concept of delta delays [Gos02]. A simulation may beperformed via the GUI of Modelsim. To illustrate this, a usual simulation setup flow willbe presented in the following.

Modelsim VHDL Simulation Flow

The presented design and simulation flow refers only to the development of a VHDL model,as the intended usage of Modelsim is to act as a VHDL simulator. A detailed explanationand introduction to the VHDL language may be found at [LWS94], wile the completeIEEE7 VHDL standard is presented in [IEE02].

Modelsim is a complete design environment integrating a simulator and editing toolsinto a graphical user interface. Each design or model is organized within a project. Everyproject has a project file, a project directory, and a working library where compiled codeis organized. Source files can be added to a project in several ways. They may be newlycreated, and referenced or copied from other projects.

VHDL models consist in most cases of three parts. First, a description of its interface(entity), second, one ore more description of its functionality (architecture), and third,one or more configurations (configuration) describing the relations between entities andarchitectures. It is possible to group standard types and routines into libraries (packages)for further reuse.

During the compilation process the compiled modules will be registered hierarchically

3VHSIC (Very High Speed Integrated Circuit) Hardware Description Language4Verilog Programming Language Interface5VHDL Foreign Language Interface6Tool Command Language and its graphical ToolKit7Institute of Electrical & Electronics Engineers

Page 52: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 51

via their entities and different architectures within the working library.Afterward a simulation can be initialized by loading a design. For example the behavioralmodel of an entity asic, containing the behavioral description of an ASIC8.A simulation can be performed by typing ”run time-value” at the command prompt ofModelsim. The simulation is continuable, what means it can run for 100 ms at first, andanother 10 seconds if needed. By the use of waveform tracing via special wave windows,or a debugging of the design, the development results can be verified.

The given description here is only a glimpse on how a typical straight-forward designflow looks like. For a more detailed explanation an excellent tutorial with a very detaileddescription is provided by Modeltech [Mod02].

3.2.3 SystemC

SystemC is a relatively young and fast evolving language intended to support multiple ab-straction levels, and therefore getting rid of conversion problems within a design process, asillustrated in figure 3.1 at page 53. SystemC provides its functionality via C++ libraries,therefore enhances a language many designers and engineers are familiar with. The ad-vantage of this is that no new syntax has to be learned, but only the added functionality oflibraries. SystemC is open-source and does not include a graphical development interface.The SystemC user guide [sys01b] and the functional specification [sys01a] characterize thelanguage as follows:

”SystemC is a C++ class library and a methodology that you can use toeffectively create a cycle accurate model of software algorithms, hardware ar-chitecture, and interfaces of your SoC (System On Chip) and system-leveldesigns. You can use SystemC and standard C++ development tools to createa system-level model, quickly simulate to validate and optimize the design, ex-plore various algorithms, and provide the hardware and software developmentteam with an executable specification of the system. An executable specifi-cation is essentially a C++ program that exhibits the same behavior as thesystem when executed.”

”Although continuous time models as used for example in analog modelingcannot yet be constructed in SystemC, virtually any discrete time system canbe modeled in SystemC. Some well-known models of computation, which canquite naturally modeled in SystemC 2.0, include:

• Static Multi-rate Data-flow

• Dynamic Multi-rate Data-flow

• Kahn Process Networks

• Communicating Sequential Processes

8Application Specific Integrated Circuit

Page 53: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 52

• Discrete Event as used for

– RTL9 hardware modeling

– network modeling (e.g. waiting room models)

– transaction-based SoC platform modeling”

”SystemC supports hardware-software co-design and the description of thearchitecture of complex systems. The following features of SystemC version2.0 allow its use as a codesign language:

• Modules: SystemC has a notion of a container class called a module. Thisis a hierarchical entity that can have other modules or processes containedin it.

• Processes: Processes are used to describe functionality and they are con-tained inside modules. SystemC provides three different process abstrac-tions to be used by hardware and software designers.

• Ports: Modules have ports through which they connect to each other.

• A rich set of port and signal types.

• A rich set of data types: SystemC has a rich set of data types to supportmultiple design domains and abstraction levels.

• Clocks: SystemC has the notion of clocks (as special signals).

• Cycle-based simulation: SystemC includes an ultra light-wight cycle-basedsimulation kernel that allows high-speed simulation.

• Multiple abstraction levels: SystemC supports untimed models at differentlevels of abstraction, ranging from high-level functional models to detailedclock cycle accurate RTL models. It supports iterative refinement of highlevel models into lower levels of abstraction.

• Waveform tracing

• Debugging support: SystemC classes have run-time error checking thatcan be turned on with a compilation flag.”

Summarized, SystemC is intended to offer a tool covering as many aspects of a systemdesign as possible to minimize the amount of tools needed. This is illustrated by the fol-lowing figure adapted from the SystemC user guide [sys01b] and comparing the traditionalhardware design process with a new one utilizing SystemC.

9Register Transfer Level

Page 54: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 53

C,C++ System Level Model

Refine

VHDL/Verilog

Simulation

Synthesis

SystemC Model

SimulationAnalysis

Results

Rest of Process

Manual Conversion

Refinement

Synthesis

Rest of Process

a) b)

Figure 3.1: A typical hardware design flow: a) standard and b) with SystemC [sys01b].

3.3 Considerations for a Model of Computation for the Cosim-

ulation

The model of computation is a means of description for the underlying scheme of a tool orlanguage, characterizing its specific expressiveness (refer to subsection 2.5.1 at page 33).In respect of simulator interconnections, the model of computation for the cosimulationdetermines the interconnectivity, whereas the synchronization of single simulators andutilized communication mechanisms represent aspects of first magnitude.

The requirements to be met with the design of a computational model have a strongrelationship to practical reasons and needs of designers. Therefore the basis for the actualdesign is built by the development profiles introduced at page 45 and the features offeredfrom the tools to be connected.

In the following a model of computation for the desired cosimulation is discussed inrespect of three main aspects: time, synchronization, and communication system.

3.3.1 Time and Synchronization

Modelsim features a DE-simulator, as does SystemC. Thus both tools or languages uti-lize a linear equidistant advancing time-line. Concurrency at a single time-step is repre-sented by the introduction of a second time base called the delta-cycles (refer to page 34or [ELESV97] for DE Simulators).

For the interconnection of DE-simulators an option for a cosimulation would be toconnect their distinctive event queues and synchronize them globally. Such an attemptwould require the availability of the internal event queues to a central control entitycontrolling the global cosimulation progress. The global synchronization in respect to a

Page 55: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 54

global event queue would be a non-trivial task. However as Simulink features anothersimulation concept, such an attempt would not be appropriate, violating the intention ofsimulator independence of the realization of a single connection.

Simulink offers the possibility to model continuous system and uses a real-world relatednotification of time within the design. A design may include discrete rates for blockcommunication, specific delays and continuous states. The simulation may be performedaccording to the first two options for simulators for continuous systems presented onpage 38. Thus when a simulation is executed, the user may choose the granularity of thesimulation, either of fixed or variable step size. Several solver modes can be used for thecalculation of continuous states. Using fixed time-steps the behavior of Simulink is similarto DE-simulators, as the system state will be calculated at equidistant time intervals.

For the synchronization of different simulators there exist several strategies as in-troduced in section 2.5.2 at page 37 or discussed in [Sim98]. These strategies may becategorized in between two extrema, asynchronous optimistic approaches, or synchronousconservative methods. For asynchronous optimistic synchronization backtracking mech-anisms have to be featured by the simulators, to trace back in time if a received eventdates back in time. The selected simulators do not include such backtracking mechanisms,therefore asynchronous optimistic cosimulation will not be available due to the simulatorsused for this project. Asynchrony can only be featured in situations where the violationof time causality is inhibited.

Although the internal computations of a single time-step differs in many aspects be-tween the involved simulators, a synchronization between these computations would beappropriate. Signal data containing the internal states of the modules can be transferredto build the basis for the calculation of the next time step of other modules. This systemwould result in a so-called ”cycle-based cosimulation”.

With cycle-based cosimulation the single simulators may only work asynchronouswithin the computation of single time-steps and are synchronized after each step. Consid-ering model interaction, this option to avoid time causality errors is not always necessary.As it is only necessary to transfer needed values, and for these values there exist the possi-bility that they may change only at a specific frequency minor to the simulation resolution,the rendezvous points for a synchronization can possibly be minimized.

The following example illustrates such a situation: A memory interface for a 1 GHzprocessor may only run with 133 MHz. Although the simulation resolution would be 1 nsto simulate the behavior of the processor, signal changes on the memory interface will onlyoccur at a rate of 133 MHz. Therefore a transfer of this value is only needed at this rate.Due to model design it is ensured that for simulation steps between this time referencesnothing will happen on the memory interface. Due to the use of this concept, a lot of

Page 56: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 55

unnecessary traffic can be avoided, and the different modules may calculate asynchronouslyfor a longer time period.

The intention of the synchronization of the single simulators is to provide each simula-tor with the necessary input values for the calculation of the next time step. To implementthis intention, a data-driven synchronization mechanism may be used in a way that whensingle simulator has all its input values available, it may progress in its simulation andhas to distribute the resulting output values to all simulators referencing these signalsafterward.

To implement this idea of a synchronized cosimulation the following concepts will beused:

• A global time-line representing the global simulation resolution is introduced. Allsimulators refer to this time line for the ordering of external events.

• The interconnections operate synchronous, thus for each equidistant time interval ofa desired connection rate signal values have to be distributed.

• Each simulator calculates a time step with the given input values on its own, inde-pendent from other simulators.

• A single simulator may trigger its own progress of a single time unit autonomously,if it has valid values for all input signals available for this time step.

• Signal passing happens before and after the computation of a time-step, but notwhilst the calculation.

This strategy binds simulators only by its dependencies to the global simulation. If asimulator does not have external inputs but provides signals to other simulators, it mayadvance independently if the calculated output values are buffered time-stamped to beretrieved by the desired simulators as needed.

The concept does not support feedbacks to external modules within a time-step, whathas to be taken into account for model-design. Such feedbacks causing zero delay loops10

should be avoided, as differential equations would have to be resolved for calculating asolution. This is not possible for loops between different simulators, and many simulatorsdo not even offer this feature for their models.If a desired loop between external models exists, one of the modules has to be classifiedas starting module to be given an initial input value at the start of the simulation. Thecalculation will be done in direction of the data dependencies and introduces a delay ofone time step at the connection of the first and last modules of the loop, as each moduleis calculated only once per time-step.

10In MATLAB these loops are called algebraic loops

Page 57: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 56

The presented synchronous interface was chosen due to the lack of backtracking mech-anisms, as thus each simulator has to have consistent input values at each time step. Apossible simplification of the data representation for signals containing no value changeswould be an option to decrease bandwidth usage, but is an aspect addressed by the usedcommunication system and will be discussed in the next subsection.

3.3.2 Cosimulation Control and Communication

For the control and implementation of simulator interconnections there exist various strate-gies like decentralized direct interconnects or backplanes, with their distinctive featuresas introduced in section 2.4.2. An approach featuring the advantages of both would be awelcome compromise. To please this demand easy usable interfaces, connectible directlyor to an optional central entity, will be featured in this approach.

The used connection mechanisms are very essential to the list of features of a cosim-ulaton, as for instance network capable mechanisms imply the feature of distributed sim-ulation. The implementation of the used protocols for synchronization and data transferaffects a cosimulation environment’s usability and the time needed for a fresh setup of acosimulation. Furthermore due to introduced latencies from the connection mechanismsand available connection bandwidth, the simulation time can be swayed significantly.

Further aspects which have to be considered for the design of a cosimulation commu-nication system and its communication mechanism include:

• Simulation Control: Many simulator connections feature special protocols forsimulation control and data transfer. The desired synchronization mechanism ofdata dependency, as introduced prior, has no special need for this. To perform asimulation it is only necessary to provide the output values to the input ports of theother simulators at pre-determined time-steps.The use of dedicated channels between the different simulators would implement theidea of direct connections. A central node may be an option to have a central datalogger, offering complete simulation data in a single data set, instead of having tocollect the data of every simulator, likely available in different formats.A further application area of a central node would be for instance a very complexsystem, where a central control unit could manage available network bandwidth (orworkstation power if several simulators run on the same machine) via simple storeand forward mechanisms to achieve a minimized simulation time.

• Independency: Independency is a very essential feature for a designer. Whenconnecting a model to external sources, it is convenient for a designer if he doesnot have to take into account in which language the external module is described,by which simulator it is actually simulated, or on which workstation platform theexternal simulation performs.A big part of this independency is solved by the desired synchronization and simu-lation control mechanism as only data is transfered and the synchronization of it is

Page 58: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 57

up to the receiver. For a further support of independency the communication has tobe implemented in a way that a general protocol is used which is translated at bothends of a connection.

• Network Functionality: The utilization of network capable communication mech-anisms has the effect of providing the ability to perform a distributed simulation onseveral computers. This shall not be considered only for reasons of limited calcu-lation power and memory of a single workstation, but for possible options in thedesign process as well.For design verification of their own single system parts, in many cases engineers haveto install a multitude of programs and libraries used by the other design teams inthe design process of this product. This causes the necessity of acquiring licenses ofthese tools for each computer running an instance for design or test purposes. Everysingle design team has to take the effort and costs for the setup of such workstationsor environments to test their system modules.A scenario where each developer may provide his own module computed by his owndevelopment equipment to be included into a simulation of the entire system shall bean considerable option for many design teams. It offers the possibility to minimizecosts and setup time, as each interface is built by the designer related to this specialmodule according to a general rule set.

• Data Transfer: Simulators may use different representations of one and the samesignal. Therefore type conversions may be necessary. To illustrate this, the exampleof a bus system shall be considered. A specific module may use a single word forvalues transferred on this bus, whereas another module utilized 32 single bit valuesfor the bus signal representation. Platform dependencies might occur as well, as forinstance an integer may include a different amount of bytes on different platforms.Byte-order issues shall be considered as well.

• Implementation: The use of proprietary libraries and available tools to implementa cosimulation interface may limit its flexibility and maybe inhibits additional licens-ing costs. A mechanism shall be utilized available on many platforms via standardlibraries, freely available or even provided by the operating system. For a maximumof reusability, a general implementation language shall be used, whereas standard”C” seems appropriate as it is featured by all three tools and is widely known.

After a consideration of many aspects, the communication model was designed asfollows:

The communication shall be based on wrappers according to figure 3.3 at page 59. Eachsimulator is connected to a wrapper, which translates internal data representations to acommon description used on the communication channel. This common signal descriptionhas to be determined prior to the cosimulation setup.

Page 59: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 58

To support the desired synchronization and provide network functionality stream socketsbased on TCP/IP shall be used, which offer a reliable, in-order, bidirectional, and platform-independent communication media.Due to the desired synchronization method no simulation control protocol is needed. Signalvalues have to be transfered, including a global time-stamp for a future identification.The transfer of data chunks containing all values which have to be transfered on a singleinterface at one time stamp, marked with a single time step is encouraged.

3.4 The global cosimulation concept

This section introduces the global concept of the cosimulation environment according tothe desired model of computation. Abstract concepts for the simulator interfaces areincluded as well.

The central idea of the desired cosimulation environment is to connect concurrentlyacting entities. According to the discussed model of computation, the different simulatorsof a cosimulation exchange status information at predefined synchronized times. The rate,at which certain connections transfer data, may be different for each connection, but hasto be synchronous to a global time-line. Thus each connection may have its own transfer-rate synchronous to the global simulation time as illustrated in figure 3.2). The globaltime-line is used for a synchronization of received extern values.

Time

A

B

C

Global Time

Data Transfer A−B Data Transfer B−C

1 2 3 4 5 6 7 8 10 119

"Channel A−B" "Channel B−C"

Figure 3.2: Cosimulation synchronization illustration

The synchronization of the simulation flow of the various simulators is data driven.For each time-step a single simulator waits until he has received all input-values for theactual time-step from the cosimulation environment, then it continues with its simulationto compute the output signals of this time-step.After the computation and reaching the next time-step it has to wait again until all input

Page 60: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 59

values have been received. Due to this synchronization strategy the complete simulation istriggered by data dependency, and no simulation control protocol has to be implemented.If several modules are connected in a loop, one module has to be chosen to be providedwith an input value and start the simulation, otherwise a deadlock will occur. Zero delayloops are not supported, as mentioned prior.

After a computation of a time-step the simulator has to distribute the output val-ues needed by other simulators via specific connections. Specific signals may only betransferred every third step, dependent on the assigned connection rate as illustrated infigure 3.2. Multi-rate systems feature connections at different rates. To simplify the mech-anisms needed for a connection between two simulators, signals have to be transferred ata common rate.

For the realization a wrapper concept is used. These wrappers shall contain the syn-chronization, translation, and communication functionality. Wrappers are integrated intothe simulators with the intention to translate internal data to a general standard descrip-tion used for the communication.Channels based on stream sockets are used to connect the different simulators. Thesechannels have to be established only between simulators transferring data to each other.For the implementation of the channels stream sockets based on TCP/IP shall be used toprovide a network capable, reliable and bidirectional communication media.

The resulting system is illustrated in the following figure 3.3:

S3

W3

W[1..3] Wrappers

SimulatorsS[1..3]

optionalCentralControlUnit

S1 S2W2W1

Figure 3.3: General cosimulation concept

The flexibility to either connect all simulators directly or use a central control utilityas discussed in subsection 3.3.2, dealing with aspects of cosimulation control and com-munication, is present in figure 3.3 as well. The data packages sent on the network aretime-stamped. Therefore such a central control unit may take control of the global simu-lation using a simple store and forward principle. An intention for doing so could be thecontrol of available calculation power of different machines or bandwidth reasons. Another

Page 61: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 60

possible use of a central node would be the implementation of a central simulation datalogging entity.

For the implementation of the simulator cosimulation interfaces based on wrappers,two general options seem appropriate:

1. The wrapper includes the synchronization: For the synchronization of thecosimulation the wrapper has control of the simulator. The wrapper enables a cycle-based simulation by stopping the simulator after the computation of each single time-step, fetches the output values from the simulator and transfers them via designatedchannels to dedicated simulators. Before the wrapper commands the simulator tocompute the next time-step, all necessary input values have to be received from theother simulators.For this wrapper implementation approach, the simulator has to offer possibilities tohalt a simulation after the computation of a single time-step. An integration of thewrapper into a design for the realization of a cosimulation interface requires none orminor redesign of the model.

2. Cosimulation synchronization is provided by the model: In this case thewrapper offers operations for the data transfer to the designer. In contrary to thefirst approach taking control of the simulation, the designer has to integrate thesefunction into the model design and has to ensure that they are executed by thedesign to act according to the desired synchronization.Not all simulators offer the possibility to control them directly or indirectly by modelindependent mechanisms. For such simulators this wrapper implementation ap-proach shall be used. Most likely the integration of the wrapper has to be takeninto account during the development of the model description to enable a correctsynchronization.

In the following section, these concepts will be implemented to provide cosimulationinterfaces for Simulink, Modelsim, and SystemC.

3.5 Interfaces for Simulink, Modelsim and SystemC

This section covers the development of interfaces for the various dedicated simulators.According to the global cosimulation concept these interfaces are designed as wrappersto be enclosed to the actual design. In this section the simulator dependent conceptsof the wrappers to synchronize to the simulator internal simulation and gain access tosignal values are discussed. Details on the realization and implementation follow in theimplementation chapter, starting at page 70.

3.5.1 MATLAB/Simulink

In this section a cosimulation interface to a Simulink simulation will be designed. Firstseveral options for the realization of such an interface will be discussed. MATLAB and

Page 62: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 61

Simulink offer several interfaces which can be used for the integration of an interfaceaccording to the first option for a wrapper implementation (page 60). Therefore the useof the MATLAB-C interface and the utilization of the Real-Time Workshop code-creationprocess will be investigated.

The following subsections discuss the available interfaces and in the last one a designof an cosimulation interface using the code-creation process is presented.

Matlab C-Interface

MATLAB provides several capabilities for the communication with the following programsand devices [Theb]:

• External C and Fortran Programs

• Object oriented technologies like Java and ActiveX

• Hardware devices on serial ports

The external C-interface of MATLAB offers interconnectivity in both ways. It is possibleto start an external C-subroutine from within MATLAB to act as if it were a built-infunction as well as to start MATLAB from within an external program to act as ancomputational engine.External C-code can start and stop a MATLAB process, work with MATLAB MAT-files,and send commands to and exchange data with MATLAB. However the capabilities of theinterface are platform dependent, as for instance some functions like engOpenSingleUse()are only available on Windows Platforms.

As the interface is intended to cope with a Simulink simulation, now Simulink connec-tivity to the command line will be discussed. The Simulink user guide [Matc] indicatesthat a Simulation may be run via executing commands in the MATLAB command win-dows or from an M-file, or via the Simulink menu. Thus a simulation may be run via thesim() and set param() commands to perform an unattended simulation or a Monte Carloanalysis by running simulations with changed parameters.

The sim() and set param() commands may start a simulation by setting the simulationparameters and triggering the simulation. The command get param may then be used togather information of the current simulation state.For the desired interface a possibility shall be found to perform the simulation time-step-wise (cycle-based) and interactively.Although the simulation may be stopped, paused and continued, there is no indicationthat this could be achieved at fixed time-steps. Besides the sim command (running a sim-ulation of a given duration) and set param which may actually stop, pause, and continue asimulation, there is no control in these commands to accomplish this at desired time-stepsand at a special state of the simulation as would be required for the intended wrapperrealization.

Page 63: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 62

Therefore this interface may be used for interfacing the MATLAB engine itself, butthe development of a wrapper for Simulink as intended is not encouraged by the docu-mentation.

Real-Time Workshop External Mode

The external mode allows a client/server based communication between two systems,MATLAB/Simulink as client, and the created executable as server, running on a desiredtarget. In this situation the Simulink GUI acts as a graphical fronted to the executable ofthe simulation. The opportunities of this feature include:

• The modification and tuning of block parameters in real time, without recompiling.

• Monitoring and logging of simulation data, whereas the conditions under which datais uploaded from the target to Simulink may be defined.

The possible transport protocols and mechanisms for the connection depend on thedesired target of the executable. For instance GRT, GRT malloc, and Tornado targetssupport TCP/IP an the Real-Time Windows Target makes use of shared memory.

A possible wrapper would have to emulate complete behavior of the Simulink/Matlabpart of this interface, which shall be achievable via an examination of the communicationprotocol. The use of TCP/IP as transport protocol would fit very well with the desiredcommunication model.As with the Simulink command line interface, there is no evidence of the possibility toperform the simulation cycle-based and stop at a desired phase in the calculation (at theend of the computation of a single time-step).The Simulink Control interface itself offers the possibility to start and stop the simulation,as does the command-line interface, and furthermore some mechanisms to trigger datalogging. The offered possibilities, indicated by the documentation, however do not promisethe desired features for the realization of this interface.

Real-Time Workshop Code Generation

As mentioned before it is possible to generate a standalone executable of the simulationvia the RTW. The code creation process itself is illustrated and discussed in detail insubsection 4.2.1, starting at page 81. Considering the design flow, the executable creationprocess starts with the design of the model itself, followed by the setup of the simulationparameters (e.g., simulation time duration and granularity), and is completed by thedecision of the actual build target and the code creation process itself.

The desired target shall be chosen due to the intended application area. Simulinkprovides five code formats:

• Real-time for rapid prototyping with static memory allocation, supporting almostall built-in blocks. This is the most comprehensible target.

Page 64: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 63

• Real-time malloc for rapid prototyping with dynamical memory management, en-abling multiple instances of a model within a program (if no stateflow blocks are inthe model), but more difficult to handle.

• S-funcion for creating proprietary S-functions, dynamically linked libraries, or MEX-file objects, code reuse, and speeding up the simulation.

• Embedded C for deeply embedded systems.

• Ada: This option requires a special Add-on: ”Real-Time Workshop Ada Coder”,and supports no continuous states.

For this purpose the Generic Real Time target (GRT) seems appropriate, as it is intendedfor rapid prototyping, supports most of the built-in blocks of Simulink, and promises moreconvenient handling than GRT malloc.The lack of dynamical memory management and therefore the possibility of multiple in-stances of an object is made up by the ability to connect multiple instances via the pre-sented cosimulation technology.

In contrary to its name the Generic RealTime target does not use real-time operatingsystem tasking primitives, and thus provides a non-real-time simulation for a workstation.This behavior is needed, as otherwise all other simulators connected would have to providetheir values within the real-time schedule of Simulink, thus limiting the granularity of timein the simulation to the speed of all simulators.

The granularity of a Simulink simulation is one of its parameters, defining the rate atwhich the outputs of a system will be determined. Figure 3.4 shows the flow chart for theexecution of code generated for rapid prototyping targets (as GRT) [Mata].

Given the start and end time of a simulation run and furthermore the granularity, theamount of loop iterations as seen in the figure is determined and thus the computationtime needed for the whole simulation. It is obvious that with an increasing amount, thisrelation will become almost linear scaling as the initialization and termination functionswill have decreasing impact on the whole simulation time.

Considering the simulation flow in figure 3.4, and investigating the produced code andthe RTW documentation [Mata, Matd] it becomes obvious that a time-step-wise controlledsimulation run is possible. Furthermore there exist special sinks and sources which areeasily accessible for data exchange; external in- and outputs. They are accessible via twospecial global vectors rtU and rtY indexed by their names e.g. rtY.out2 for an externaloutput of name out2.

In accordance to the cycle-based loop of the simulation execution, input values shallbe distributed into the Simulink model before the execution, and after their calculationthe output values may be read and transferred to the other connected simulators.

Summarized an alteration of the code produced offers all features needed for a success-ful implementation of a wrapper.

Page 65: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 64

Figure 3.4: The flow chart for the execution of code for rapid prototyping targets [Mata]

3.5.2 Modelsim

In this subsection a wrapper for the VHDL11-simulator Modelsim will be developed. Tointerface the simulator of Modelsim to third-party software there exist several options.One option used in [Rei98] is to use language internal features like file primitives. Theother option is to use simulator dependent interfaces. For instance Modelsim features aproprietary interface called ”Foreign Language Interface” (FLI) for VHDL simulations.

Both methods will be discussed in the following, whereas the latter one more detailed,as it will actually be used for the design of the desired Modelsim wrapper.

VHDL Language Interface

VHDL itself is a simulator independent HDL12. Therefore it is not related to a specialsimulator, but is featured by several ones, like Modelsim from Modeltech, Savant fromthe University of Cincinnati, or VHDL Simily from Symphony EDA. Therefore specialinterfaces like the prior mentioned FLI are not standardized and only available with specificsimulators.

11Very High Speed Integrated Circuit Hardware Description Language12Hardware Description Language

Page 66: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 65

Stefan Reichor et al. try, as illustrated in several publications [Rei98], to offer a simulatorindependent VHDL interface by the use of the fileinterface integrated in the VHDL lan-guage. In this project named pipes accessible via VHDL’s file operations are used insteadof physical files to gain a speedup.As VHDL may open a file only for reading or writing exclusively, for bidirectional commu-nication two pipes will be needed. For a convenient user handling the external componentsare packaged into standard VHDL entities, which then connect in turn to the communi-cation server.

The synchronization acts according to the standard VHDL signal mechanism of sen-sitivity; all signal changes of the external component entity (determined via a sensitivitylist) at a special time point (a delta cycle is therefore considered as time-point as well) aredistributed via the pipes to the communication server.

The communication server propagates these values to the hardware, reads back alloutput changes, and delivers the results to the VHDL simulator.

From the point of view in respect of synchronization, this system acts according to amaster slave principle similar to a remote procedure call, where the computation runs ona different server and is initiated by providing the input values and completed when thevalues are read back.

For a desired cosimulation method in respect of the first wrapper realization option(see page 60) such a mechanism is not sufficient, as it does not provide a synchronouscycle-based interface.The cycle-based synchronization would have to be realized within the model design itself,according to the second wrapper implementation option. However, the FLI interface ofModelsim offers possibilities to schedule special processes within the VHDL simulationout of an external C program, what can be used for an implementation of the wrapperaccording to the first option and will be discussed in the next subsection.

Modelsim SE: Foreign Language Interface

The Foreign Language Interface (FLI) of Modelsim is a proprietary interface to provideprocedural access to information within the Model Technology’s HDL simulator vsim.An external program can use the provided functionality to gather information about thedesign of a model or its values, and may even take control of a simulation run to someextent.An interface utilizing FLI may use one of the following concepts:

• Foreign architectureA foreign architecture is a design unit containing no VHDL code, but realized bya VHDL stub linked to a C model that can communicate to the rest of the designthrough the ports of the foreign architecture. Such a C model may create processesor retrieve and drive signal values, behaving in the same manner as VHDL code butwith the advantage of the power of C.

Page 67: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 66

• Foreign SubprogramA foreign subprogram is a VHDL function or procedure that is implemented in C asopposed to VHDL. A foreign subprogram reads its in and inout parameters, performssome operation(s) which may include accessing simulator information through FLIfunction calls, writes its inout and out parameters, and returns a value (in the caseof a function).

• CallbackA callback is a C function that is registered with the simulator for a specific reason.The registered function is called whenever the reason occurs. Callback functionsgenerally perform special processing whenever certain simulation conditions occur.

The processes created in FLI routines may be scheduled within the simulation for specifictimes or may be sensitized to trigger signals, thus provide much power for an externalprogram. There are several process types with special priorities referring to their executionorder within the calculation of a single time-step. These processes are represented by C-functions which are invoked when the process is executed.

At the start of the simulator, first an elaboration phase is executed loading the VHDLdesign and its connections, and initial values get assigned. For FLI interfaces this elabora-tion phase loads the foreign libraries and performs the initialization routines of the foreignarchitectures. Therefore external programs incorporating foreign architectures have initialaccess to the VHDL environment even before the simulation starts execution.This fact is used by foreign architectures to schedule their processes for the first invocation.

For data access to VHDL signals, the FLI offers several functions and structures forboth reading and writing. Special signal handles identify the signals to be read, or to bewritten via special driver structures.

With the ability of scheduling processes with special priorities at specific times, andgathering signal values from or drive values to a VHDL signal, a wrapper according to thefirst option presented on page 60 can be designed.The intended wrapper utilizes a foreign architecture scheduling a process with a priorityensuring that it is invoked first at each time step and synchronously scheduled to readoutput values from a design and drive collected input values to the VHDL model.Due to the time-specific scheduling of the process instead of a sensitivity triggered exe-cution the wrapper is more model independent as an implementation utilizing the VHDLfile primitives. However as a design may possibly contain other FLI processes with thesame priority, possible interferences have to be determined and solved by the designer.

Page 68: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 67

3.5.3 SystemC

SystemC [sys01b, sys01a, WJH+] is a relatively young and fast evolving freely availabledescription language based on C++. Version 1.0 provided modeling constructs similar tothe ones used in HDL languages like VHDL for behavioral and RTL13 modeling, thus someconstructs and features for system-level modeling as well. However the communicationand synchronization mechanism of hardware signals is of somewhat limited usability as asystem-level design would maybe specify several modules communicating via queues, orconcurrently executing processes sharing global data via mutexes.

Version 2.0 extends these constructs to enable system-level modeling. As system designmay utilize a wide range of models of computation, design abstraction levels, and designmethodologies, a generic purpose modeling foundation was added, on whose top the dif-ferent methodologies may be built on. This small general purpose modeling foundation ofSystemC 2.0 is referred as the core language and is actually the central component.

To be able to establish a connection between two models however the actual model ofcomputation is essential because of its impact on the synchronization of the connection.As there are multiple models of computation available for SystemC, it is obvious thatan interface would depend on a special design method. Therefore no general wrappercan be designed, as it is possible with Simulink and Modelsim. As all design methods ofSystemC are built upon the small general purpose foundation mentioned earlier, its modelof computation is examined to provide information of mechanisms to get access to thesimulation.

SystemC has a linear notion of time, whereas version 1.0 featured a real-valued andrelative notion of time and version 2.0 uses an integer based and absolutely ordered timenotion as discussed in [sys01b].Concurrent behavior in SystemC is modeled via different processes scheduled by the sim-ulation kernel. They are connected via ports and signals, whereas signals represent com-munication mechanisms to be connected to the ports of the modules.Processes implement the functionality of the modules. For execution of processes they canbe sensitized to special events to be triggered.

In System C there are three major types of processes, each offering different featuresand behavior:

• SC METHODS: These processes behave like functions, meaning they are executedwhen a signal value, of a signal the process is sensitive to, changes. The methodexecutes and returns control back to the simulation kernel afterward.

• SC THREADS: Thread Processes may contain wait() functions to suspend theirexecution until another event occurs, to which the process is sensitive. A watchingconstruct monitoring a specific condition may trigger a restart of the execution ofa THREAD process from the beginning (e.g. for exiting an endless loop or re-initialization).

13Register Transfer Level

Page 69: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 68

• SC CTHREADS: Clocked thread processes implement a special case of threadprocesses, as they trigger only on one edge of a single clock. Wait() and watch-ing() statements are available for clocked threads as well. Furthermore there is await until() construct available, enabling the designer to suspend the execution untila specific event occurs.

The scheduling mechanism in SystemC is non-preemptive, meaning that a process willrun until it yields execution by either a wait() statement or when it ends (see page 23of [sys01a]). The scheduler in SystemC controls the simulation according to the followingscheme, whereas a detailed discussion of the simulation semantics of SystemC may befound in [WJH+]:

1. All clock signals changing their values at current time are assigned these new values.

2. All triggered SC METHOD and SC THREAD processes are executed in a non-specific order.

3. Triggered SC CTHREAS have their outputs updated, and are saved in a queue forexecution in step 5. The outputs of executed threads in step 1 get updated as well.

4. Steps 2 and 3 are repeated until there is no change of any signal value anymore.

5. SC THREAD processes in the queue produced in step 3 are executed in no specificorder. Their output is saved internally and updated at the next active edge (step 3)

6. Simulation time is advanced to the next clock edge and the scheduler starts withstep one again.

Simulation control is available through the sc start(), sc stop(), sc initialize(), andsc cycle() commands. The start command is mainly used in the main routine to startthe simulation after all modules are initialized and connected, whereas the stop commandmay be used within a program as well, for instance after a detected error.The start command has the simulation time as a parameter, a negative value indicatinginfinite run time.

The initialize and cycle functions give the user the opportunity to perform the sim-ulation himself. The initialization function has to be invoked to initialize the scheduler.After a possible alteration of the signal values, sc cycle(x) may be invoked to simulate theeffect of the changes and to increase simulation time by the value x afterward.

Essential for the technical implementation of an interface to SystemC are the compu-tational model of the simulation kernel as well as the computational model of the design.Although the modeling foundation of SystemC works with discrete events, it is a basiswhich is intended to be used to implement other models of computation as well. As theintention of SystemC is to be used at system-level it is much more likely that these other

Page 70: Design and Implementation of a Cosimulation Environment ...

CHAPTER 3. DESIGN OF THE COSIMULATION ENVIRONMENT 69

models of computation will be used, than that a model which is used from HDL simulators.Furthermore SystemC is a library which may be extended by third parties to meet theirrequirements, as for instance in [CRAB01] a GUI is developed for monitoring use, whereasseveral adoptions to the simulation kernel were necessary to accomplish this.Therefore a general wrapper including the synchronization seems impracticable as men-tioned above. General ways to interface third party models to be synchronized by thedesign itself like offered by an implementation of the wrapper according to the secondoption presented on page 60 seem much more appropriate.Considering the SystemC features both wrapper options can be implemented according tothe following concepts:

• Synchronous conceptAs a mixture between the wrappers for Simulink and Modelsim the following schemecould be realized. The simulation is controlled via a loop in the main routine, con-taining an sc cycle command advancing simulation by a single time step, and per-forming read and write operations to signals intended for external use.As the times of output data synchronization differ between different types of threads,according to the scheduler scheme, special care has to be taken into account. Resultsfrom the execution of clocked threads are for instance not available after the calcula-tion of a time step, but are propagated during the computation of the next time step.An alteration to the scheduler itself could provide access within the computation ofa single time step.

• Synchronized by the designThe external model may be interfaced via a SystemC stub. Due to the differentscheduling scheme packing the communication routines into a process and schedul-ing it does not bring the same results as with the Modelsim Wrapper.However the mentioned SystemC stub can be used for a data driven synchroniza-tion between SystemC models and foreign models. Therefore these stubs have to betriggered by the design to synchronize according to the intended scheme. To illus-trate this possibility such an attempt will be made in the implementation section,where two Simulink models will be packed into two SystemC modules containingSC METHOD processes. The two SystemC subs will be interfaced within SystemCresulting in a data driven connection mechanism.

The first concept is very similar to the wrapper design for Modelsim and Simulink as itcorresponds directly to the DE-event mechanism. The second concept does not providesynchronization itself but it has to be provided via the wrapper integration into the systemdesign. As it is more general it suits more to the intention of SystemC to support a widerange of system-level design methods.

Page 71: Design and Implementation of a Cosimulation Environment ...

Chapter 4

Implementation of theCosimulation Environment

This chapter deals with the actual implementation of a cosimulation methodology as de-signed in the last chapter. After an illustration of the implementation of the commoncommunication mechanisms, the implementation of wrappers for Simulink, Modelsim,and SystemC will be addressed. Used implementation methods will be presented togetherwith code fragments of the actual wrappers. In the last section the setup of several cosim-ulations using these wrappers and their results will be presented. For the implementationstandard PC’s running Suse Linux 7.1 are used.

4.1 Communication Mechanisms using Sockets

As discussed in section 2.5.2 at page 41 sockets represent an elegant mechanism for manag-ing I/O tasks, providing the ability for interprocess communication using file descriptors.A single socket represents one end point of an interprocess communication channel. Asintroduced in section 2.5.2 there are several socket types available, featuring differentimplementation details and connection variants.

As discussed in the design chapter, for this project a reliable, bidirectional, in-orderconnection is desired. As stream sockets have all these desired features it is not necessary toimplement these details due to the use of this socket type.The actual development platformwas Linux, providing standard functionality for sockets in its standard libraries. Whenconnecting machines and workstations using different processors and architectures theremight arise several issues, for whose addressing several further functions were implemented.

To illustrate the use of stream sockets, this section begins with a briefing of streamsockets and their standard Linux libraries as well as arising problems. Detailed informationon how these sockets are used in the actual wrapper implementation completes this section.

70

Page 72: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 71

4.1.1 Stream Sockets

Stream sockets offer a reliable, bidirectional, sequential and in-order communication, basedon continuous character streams. A user may establish a connection between two points,transfer data over this channel, and terminate the connection as seen in the exampleslocated in appendix B.1 at page 114. As a connection has to be established prior to actualdata transfer, channels based on stream sockets are connection oriented. With streamsockets there is no message boundary, but both ends of a channel may send and receivedata in character trunks of independent size and in both directions.As stream sockets connections are reliable and in-order connections, there is no need toorder incoming traffic or do error checking about it. Stream sockets can have differentdomain types, addressing the incorporated address format used to ”call” another streamsocket for a connection establishment. Two domain types are the local UNIX domain andthe Internet domain. The first is intended to address local file-handles, the latter for theuse of Internet addresses as known with TCP1 [bib81a], including an IP address and aport number.This diversity of these address schemes illustrates the level of abstraction of stream sockets,hiding the actual implementation details to the user.

Local Unix Domain

In the local UNIX domain two processes share a common file system communicate, whatmeans they talk via a local file-handle. In this domain a character string is used toaddress sockets, representing a file entry in the local file system. It is essential to includethe complete path of a file into the address, as illustrated by the following examples:

• Socket Address ”channel1”This address does not include path information, which is interpreted to the factthat the actual local path shall be used. If the running program is executed from”/home/guest”, the communicate ”channel1=” will therefore be created in the di-rectory ”/home/guests”.An address without the correct path is therefore only comfortably applicable, if clientand server programs are located within the same directory.

• Socket Address ”/temp/channel1” This address includes complete path infor-mation in respect to the root directory. Thus independent from where the programwas called, the file communicate will be created as ”/tmp/channel1=”. This com-municate is accessed via one global address, independent from the location of clientand server executables.

Please notice the attached ”=” at the end of the filename. The address itself does notcontain this ”=”, but it is attached by the operating system to indicate a file-handler.

1Transmission Control Protocol

Page 73: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 72

When displaying the contents of a directory, a postfix ”=” indicates that this file is a ”filecommunicate” (for a socket communication).

The length of a socket address is limited to 14 characters due to the internal datastructures.

Internet Domain

An address of the Internet domain consists of an IP address (IP2 address) and a portnumber.An IP number is represented by a 32 bit value, for representation purposes usually dividedinto 4 octets 3 and interpreted in decimal letters: e.g. 129.27.146.146. The port numberis represented by a 16 bit unsigned integer, thus ranging from 0 to 65535.Port numbers minor to 1024 are normally reserved for system use, for example for wellknown ports as 21 for an ftp server.

4.1.2 Programming Stream Sockets

To maintain and use a connection based on stream sockets, there exist several predefinedcommands in the standard Linux libraries for data transfer, as well as the establishmentand termination of these connections. This section provides a short briefing of the availablecommands used for the actual implementation of a socket connection and unveils someof the problems enclosed. Further information on the standard Linux libraries should beavailable on any Linux machine via the respective man-pages or general socket program-ming tutorials.

In the following a few necessary commands and structures will be presented and com-mented. For a further illustration two simple server and client programs may be found inappendix B.1 at page 114.

Socket Commands and involved Structures

At this point some of the necessary commands for UNIX socket programming are intro-duced. Further documentation to these commands may be retrieved via the UNIX orLinux man-pages which should be available on any UNIX or Linux machine.

• int socket (int domain, int type, int protocol)This command is used to acquire a socket from the operating system. The callingparameters describe the desired socket type and the return value represents a uniqueinteger for the use as socket descriptor. A negative return value would indicate anerror, which would occur for example when the maximum number of sockets anoperating system can handle is exceeded.

2Internet Protocol [bib81a]3An octet are 8 bits, which is a byte

Page 74: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 73

To acquire a stream socket in the Internet domain with automatic protocol detection(which is then TCP) s=socket(AF INET, SOCK STREAM, 0) would be used.

• int bind (int sockfd, struct sockaddr *my addr, int addrlen)The bind command is used to associate a socket to an actual address. This isnecessary for instance for a server which wants to listen for incoming connectionsto a certain address. The structure sockaddr holds this address, and is the generaladdress type. Depending on the domain of the socket to sockaddr down-castedsockaddr un or sockaddr in will be used for local Unix domain sockets or Internetdomain sockets.

• int listen (int sockfd, int backlog)The listen command is intended for the server of a communication. With listen()the server listens to a socket for an incoming connection request. The integer sockfdidentifies the socket descriptor to listen on, and the backlog is the amount of differentconnections allowed. Before a socket can be listened, it has to be bound to an actualaddress, otherwise the kernel will listen on a random port.

• int accept(int sockfd, void *addr, int *addrlen)When a server is listening on a socket, incoming connection requests are queued.With an accept command an incoming connection request can be accepted. Theinvolved parameters for this command include sockfd for the listening socket, *addras a pointer to an address descriptor where the address of the client can be storedat, and addrlen to indicate the length of this address descriptor.The return value represents a new socket descriptor for further communication tothe client. Again a return value minor to zero would indicate an error.

• int connect(int sockfd, struct sockaddr *serv addr, int addrlen)Listen(), bind(), and accept() are used by the the server for connection establishment.Connect() is the command a client uses to establish a connection to a server. Theparameters are sockfd for the internal socket to connect, *serv addr for the addressof the server to connect to, and addrlen for the length of the serv addr.The return value just indicates success or error, whereas a value less than zero meansthat an error occurred.

• int send(int sockfd, const void *msg, int len, int flags)The send command conducts a data transfer using a socket. The parameters aresockfd for the socket to be used for the transfer, *msg representing a pointer to thedata to be sent, len indicating the length of this data, and flags for setting someflags (which should be 0 in most cases). For an explanation of the flags refer tothe corresponding man-page. Send() returns a value indicating the amount of sentbytes. If the return value is not equal to the intended size, the program itself isresponsible for iterative invocations of send() to transfer the rest. This need not bean error but can occur due to operating system and network related limitations.

Page 75: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 74

• int recv(int sockfd, void *buf, int len, unsigned int flags)Recv() reads a defined amount of data from a socket into a buffer. Parameters arethe socket descriptor to read from (sockfd), a pointer to the buffer where the datashall be stored (*buf). and the amount of bytes to be read. Again some flags for thedata transfer can be set (please refer to the man-page). Recv() returns the numberof bytes read or minus one if an error occurred. If the amount of bytes read differsfrom the intended amount, take care to receive the rest by invoking recv() again.

• close (int sockfd)For the termination of a connection all sockets have to be closed via close(socketfd),whereas socketfd is the descriptor of the socket to be closed. Closing a socket preventsany further reads or writes on this dedicated socket, resulting in an error if someonetries to do so.

The practical use of these commands is shown in two small example programs locatedin appendix B.1 at page 114.The parameters of many commands include a pointer to a sockaddr structure, instead ofan actual sockaddr un or sockaddr in for their respective domains. As suggested in thedescription to the socket() command, these structures shall be down-casted to the generalstructure of sockaddr, when used as a parameter.Sockaddr and sockaddr in are listed at this point to show the relation between the structs

struct sockaddr {unsigned short sa family; /* address family, AF xxx */

char sa data[14]; /* 14 bytes of protocol address */

};

struct sockaddr in {short int sin family; /* Address family */

unsigned short int sin port; /* Port number */

struct in addr sin addr; /* Internet address */

unsigned char sin zero[8]; /* Same size as struct sockaddr */

};

struct in addr {unsigned long s addr;

};

Sockaddr is the struct internally used by the commands. It contains an unsignedshort for the address family and 14 bytes of data. The interpretation of data is basedon the socket family. Sockaddr in contains the same information, but the 14 data bytesare interpreted according to the Internet domain. These 14 bytes are split into severalblocks for a more convenient access when using Internet sockets. Please note the contained

Page 76: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 75

sin zero array which is needed to reach the size of 14 bytes.The limited size of protocol address is the reason why a local Unix domain address islimited to 14 characters, discussed at page 72, as 14 address bytes can accommodate only14 characters.

Very essential to these structures is the byte order of the contained data. Generallyspoken, there exist two orders; ”Most Significant Byte First”(MSBO) and ”Least Signifi-cant Byte First”(LSBO)4. The actual ordering of data used in a program depends on themachine’s architecture the program was compiled, and where it is executed. As informa-tion contained in the address structures (e.g., sockaddr()) is encapsulated in the networktraffic, these values have to be in a distinct order to be correctly interpreted by the re-ceiving host.Due to this a network byte order was established, which is in fact MSBO. A programmerhas to take care that the used information is ordered correctly. There exist several routinesto transfer data between network byte order and the actual ordering on the host (hostbyte order). For example htons() converts a short from host byte order to network byteorder.

When send() or recv() commands are used for data transfer it is not ensured thatthe complete data is transfered, due to possible limitations of the operating system andnetwork implementations (e.g., internal buffers). These commands report however theamount of bytes actually transfered. Special subroutines, which call these commandsiteratively until the whole data is transfered, can solve this problem. A maximum numberof iterations shall be provided to take care of the problem without creating an infinite loopif a real problem occurs. The following pseudo-code illustrates such a function which isused for this project:

#define MAXRETRY 15

int i_send(int sockfd, const void *msg,int len, int flags) {....

int sum=0, ret=0, counter=0;

while (counter<MAXRETRY) { ret = send(rest of data);

if ret=(-1) break;

sum=sum+ret; };return(sum);}

Network Traffic issues

The byte order may play an important role for the transfered traffic as well. When asend() command is executed, the desired data is sent according to the order it is storedon the host machine. If the receiving machine has another byte ordering, it receives the

4often referred as Big Endian Order and Little Endian Order

Page 77: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 76

same amount of data, but it interprets it in a different way, because the MSB 5 may beinterpreted as LSB 6 and vice versa. This is a problem the socket programmer has to takecare of. Either a well known standard ordering is used for the transfer, and both hostsconvert the traffic, or only the receiving client converts traffic from the well-known byteorder of the sending machine. When both hosts are of the same machine type (e.g. PCLinux workstations) this issue will not occur.

Data type sizes may vary on different machines, and this can be an issue. A specialdata type may use 2 bytes on one machine and 4 bytes on another. When transferring thedata type between machines using different sizes for a data type this entails a problem.For instance the sender sends 2 bytes for this type, and the receiver expects 4. It is up tothe programmer to solve this problem.

Alignment boundaries may play a role for the data traffic too. For a periodical datatransfer (as it is used in this thesis) it is convenient to pack all data to be sent in a structureand send the structure afterward to minimize the amount of commands used.On many machines variables may start only at distinctive memory addresses, for instanceat multiples of 4 or 8. Such a struct consisting of one integer with 4 bytes and two doubleswith 8 bytes each may use 20 bytes on a machine with alignment boundaries at multiplesof 4 and 24 bytes on machines with alignment boundaries at multiples of 8.This has to be taken into account when considering data transfer based on structs betweendifferent machines and operating systems.

4.1.3 Implementation of the Cosimulation Communication

The prior subsection contained an introduction on how to program sockets. The inten-tion of this section is to deal with the specific implementation details in respect to thecosimulation interface.

Establishing the connections

According to the global concept as discussed in section 3.4 the simulators are connectedvia their wrappers according to their data dependencies. Thus two simulators exchangingvalues shall establish a (bidirectional) connection for their data transfer. For an actualcosimulation with multiple simulators several connections have to be established, but onlybetween simulators which need to exchange signals.The used stream socket connections implement a server-client model, as introduced insection 2.5.2. For the selection of which partner of a single channel shall be the server,and if a wrapper includes several channels this mechanism has to be taken into accountdue to the following reasons:

5Most Significant Byte6Least Significant Byte

Page 78: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 77

• Using the procedures presented in the last subsection the server has to be runningat the time a client tries to connect, otherwise the client will receive an error. Thismeans the simulator and wrapper containing the server of a connection has to berunning prior to the client.

• If several wrappers have multiple connections, problems may arise from a sequentialestablishment of channels. Either its is not possible to have the server started priorto the client trying to connect, or if this is tried in a loop for each channel this willresult in a deadlock.

X Y

Z

A

BC

Simulator Y Simulator ZSimulator X

{....establish channel Aestablish channel C....

}

....

establish channel C....

establish channel B....

....establish channel Bestablish channel A........ ....

initialize initialize initialize{ {

} }

Figure 4.1: Problematic connection establishment sequences

Figure 4.1 illustrates such a problematic connection establishment sequence. Onepossible solution is that X is server of channel A, Y server of channel B, Z server ofchannel C, and all clients try to connect within a loop until a connection is made. Asolution to avoid polling mechanisms is to have X as server on channel A and C, Y asserver on B, whereas Y shall initialize channel A prior to B, and Z as client on both channelC and B. Then X, Y, and Z would have just to be invoked in rising order to provide aproper connection establishment.

It is obvious that this depends heavily on the actual cosimulation to be performed. Forthe test implementation no polling mechanism is intended, as a correct decision whetherwhich host on a channel shall be server and in which order the channels are establishedcan solve this problem. Advanced polling mechanisms are however an option for furtherimprovement.

Data Transfer

The traffic on the cosimulation connections consists only of signal values, as the cosimu-lation utilizes no dedicated control protocol, and synchronization is data-driven. In thedesign section it was discussed to use a simplified data representation for the transfer ofsignals containing no value changes. This would however lead to the need of an actual pro-tocol describing the delivered data, resulting in an overhead. A simplification would onlytake advantage with very static systems, where considering the DE-simulator paradigmthe used calculation power is also minimized. With very active systems, using much cal-culation power, the protocol overhead would result in higher bandwidth demand.

Page 79: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 78

Further taken the decreased usability, implied by this simplified data due to a more so-phisticated traffic management, into account, this is considered as an option but not usedfor the actual implementation.Therefore data chunks containing the values will be transfered at pre-defined simulationstages (at a fixed rate) with a pre-known data size, as every desired value is representedby a fixed data type and has to be transferred at every time-step.

Thus, the receiver always knows how many bytes of the incoming data stream refer tothe data transfer of a single time-step and how these have to be interpreted.

Due to this concept there is no need to have a special protocol describing the datatransfered on the channel, as it is pre-known by the receiver. Therefore an additionaloverhead can be avoided again.

The routines of the data transfer shall be synchronized within the simulation accordingto the following scheme:

initialization()

while (simulation) {receive all external input values from other simulators;

simulate a single step;

distribute output values referenced by other simulators;

}

The considered loop may however need a lead-in or/and a lead-out in specific situations,where no initial value can be retrieved for the first time-step, or the last output is notneeded by other simulators. A model containing a loop is such a situation.

Zero delay loops can not be modeled with this cosimulation method, but only loopsbroken at some point to result in a chain. At this point a delay of one time-step is inserted,as the actual output value of the chains last element can be delivered to the first one onlyat the next time-step. Considering this, the first module of the chain is not able to retrievean external input value for the very first time-step, and the output of the last module ofthe chain will not be needed by the first module anymore.Therefore the first module has to have a lead-in to the loop, where this specific inputvalue is not fetched from the network but provided internally, and the last element in thechain needs a lead-out as the specific output value has not to be transferred anymore.Actual other connections of both modules are not influenced by this, therefore the fetchand distribute commands have to be integrated into the respective lead-in and lead-out.

The necessity of lead-ins and lead-outs are again specific to an actual design and hastherefore to be determined and implemented accordingly.

Page 80: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 79

Implementation Rules

For a convenient use, traffic data values can be stored in special data containers to besent as complete chunk afterward, or if this is not possible due to network traffic issuesmentioned prior (see page 75) the values are at least stored fpor convenient access. Sucha structure shall be used for incoming and outgoing traffic, as needed.All internal variables and structures should feature a general naming scheme including anidentifier for the channel as illustrated in the following source code.

#define CHANNEL 1 SERVER IP // e.g. "IN ADDR ANY" or ""11.10.0.10""

#define CHANNEL 1 SERVER PORT // "3778"

typedef struct {int stamp;

double In1;

double In2;

} DATA channel 1 in;

typedef struct {int stamp;

double In1;

double In2;

} DATA channel 1 out;

struct sockaddr in channel 1 server, channel 1 client;

int channel 1 server socket, channel 1 client socket;

Although it would be possible for a server to handle multiple connections via a sin-gle server socket, it is desired to use dedicated sockets for each channel. Connectionhandling becomes much easier and automation is encouraged as discussed later on. Theestablishment of all socket connections shall happen prior to the simulation as part of theinitialization.

As the different modules may use different data representations of signals to be trans-ferred, a common representation format has to be chosen for the actual transfer. Bothsides have to translate the internal data types to the type used within the special datatransfer structures. Although the signal values are stored within these special structures,due to network traffic issues (refer to page 75) it may be necessary to send or receive allstored values on each own instead of the complete structure.

Considering the wrapper concept, template wrappers shall be implemented containingbasic elements which can be altered afterward according to the needs of an actual cosim-ulation. This is encouraged by the implementation style chosen, as the schemes used forsocket connections and their use within the cosimulation are standard to every connection.

Page 81: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 80

Options for Automation

In the prior sections several aspects of implementing the communication of the simulationhave been discussed. Although automated interface generation is not part of this work,some aspects of the interfaces automation shall be discussed in respect of automation inthe following.

For an automated interface generation it would be necessary to have a network descrip-tion of the cosimulation, containing all values to be distributed. This description is neededfor the determination of channels which to be established. Furthermore it is advisable tomake the decisions of which part of a channel shall be server or client, and in which ordershall the connections be established according to the data dependencies contained in sucha network descriptions.

A much more complicated task is an automated determination of the transferred datatype of signals if they should be different. This could be addressed however by userinteraction.

The program elements used to establish a connection for data transfer encourage au-tomation, as they follow a simple common principle (see examples for server and clientprograms in appendix B.1 at page 114). Templates covering the establishment and main-taining sockets could be established easily. Also the desired fact of having dedicated serversockets for each channel and the presented naming scheme fit very good for a desired au-tomation.

Summarizing the chosen style of implementation encourages an automated interfacegeneration, as it uses basic blocks of which the interfaces shall be built. However toimplement an automation for finding correct connection establishing sequences seems tobe a non-trivial task.

4.2 Simulink Interface

In this section an interface to Simulink will be implemented. A glimpse on Simulink andits features was presented in the design section, starting at page 46. The concept for anactual wrapper implementation was presented at page 62, suggesting to use the simula-tion code from the stand-alone simulation code creation process of Simulink, and alter thiscode to integrate the wrapper functionality as desired by the general cosimulation concept.

For the simulation interface the Real-Time Workshop code creation process be used togenerate a stand-alone executable of the model to be adopted for a synchronous cycle-based cosimulation interface for foreign models connected via sockets. Special sinks andsources will be used to provide ports for a data exchange with the cosimulation network.

The special ”Generic Real-Time Target” of Simulink is intended for rapid prototyping(see table 3.1 for more details). In contrary to its name it provides a non-real-time simu-lation for workstations, as it does not use real-time operating system tasking primitives.As mentioned in the design section on page 62 this special target features all necessary

Page 82: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 81

features needed to provide a simulation of the model and include the desired cosimulationinterface in this simulation.

To illustrate the development of the actual implementation of the interface the Real-Time Workshop code creation process will be investigated in detail. A presented realizationconcept is completed with implementation details.

4.2.1 Real-Time Workshop Code Creation Process

Simulink is a modeling, simulation and analyzing tool with an graphical interface (GUI)where a designer may compose the desired system. Via the Real-Time Workshop(RTW)a stand-alone executable of the model simulation may be created to speed up simulation,use less memory (as not the complete MATLAB GUI has to be loaded), or adapt thesimulation to someone’s needs by an alteration of the produced code.

This code creation process is based on the Target Language Compiler(TLC). Thereexist some default targets, but the user is encouraged by ”The MathWorks” to alter themor create new ones living up to the designers expectations.

For the actual implementation the Generic RealTime target of Simulink was chosen.The code creation process for this target may be visualized according to figure 4.2, whereasmore details can be found in section 2 of the Real-Time Workshop user guide [Mata].

Make Process

TLC

RTW Build

Simulink

grt_unix.tmf

grt_main.c

model.regmodel.prmmodel.hmodel.c

model.rtw

model.mdl

3. Makefile Creation

1. Model Design

2. Code Creation

4. Stand−alone Executable Compilation

model

Figure 4.2: An illustration of the code creation process of the Real-Time Workshop,adapted from [Tud00]

Page 83: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 82

The process can be divided into four major steps, which will be discussed in the following:

• Model design for the creation of a Simulink model, and the setup of simulationparameters

• C Code generation

• Makefile creation

• Stand-alone executable compilation

Model Design and Simulation Parameters Setup

The first step of a code creation process is the design of a module within Simulink via itsgraphical user interface. A simple example for a design is illustrated in figure 4.3. Thisdesign will be represented by a .mdl file in the actual working directory of MATLAB.Before a simulation or the code creation process can be started, it is necessary to set thesimulation parameters according to the designers needs. These options may be found inthe simulation parameters menu accessed via the simulation menu as seen in figure 4.3.

Figure 4.3: A simple Simulink model

In the solver tablet, shown in figure 4.4 at page 83, the designer may adopt simulationstart and stop time, whether the time steps are of fixed or variable size, if the model usessingle- or multitasking, and the desired solver mode. The solver mode is related to thesimulation of numeric integration of sets of Ordinary Differential Equations(ODEs). Fora more detailed information on available solver modes or other parameters, please refer tothe corresponding Simulink manual [Matc].

Page 84: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 83

Figure 4.4: Simulink simulation parameters tablet

C Code generation

Via the RTW a stand-alone executable (or its c-code) of the simulation may be generated.Prior to the actual creation process, the correct simulation parameters have to be enteredas described on page 82, and the desired target (see table 3.1) has to be chosen in theReal-Time Workshop parameter tablet illustrated in figure 4.5.

Figure 4.5: Real-Time Workshop parameters.

With an invocation of RTW, in the current working directory of MATLAB a build

Page 85: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 84

Figure 4.6: Real-Time Workshop target selection.

directory will be created, whereas the name will be assembled from the modelname, thedesired target, and a special ”rtw” postfix. Therefore for the model ”asic” and the ”GenericRealTime Target” the directory name will be ”asic grt rtw”.

Into this directory the RTW will put all necessary files for the code creation processspecific to the model design. For instance the main routine for the simulation is generalfor all creation processes of a target, and will be only put into this directory when onlycode is created but no actual executable is compiled (via special parameters regarding thecreation process). However the executable will not be created in this directory, but in theactual working directory itself.

The amount and names of the files created during the build process may vary betweendifferent Simulink or RTW versions due to internal changes. For instance MATLAB Suite6.1.0.450 Release 12.1 with corresponding Simulink and RTW versions produces differentfiles than MATLAB 6.5.0.180913a Release 13.The filenames in figure 4.2 on page 81 correspond to Release 12.1, whereas with Release13 model.prm and model.reg will not be available. What files will be created for an actualSimulink version can be determined in section 2 of the corresponding RTW userguide(e.g. [Mata]).

Summarizing the simulation code specific to the model is divided into multiple files,dependent on the Simulink and RTW versions used. Common to both versions tested herewere model.c and model.h, containing the model itself (initialization, computation ....)and structure definitions to access the model. From within the Simulink source directoriesseveral files will be included to provide the computation functions of the simulation engineand the main routine of the simulation.

Page 86: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 85

Makefile generation

Simulink uses Makefiles for the compilation of executables. It automatically generates amodel’s makefile from a template specific to the desired target. For Unix (and Linux)grt unix.tmf is the Generic Real-Time Target template file. In the RTW manual [Mata] adetailed description of this file may be found.

Under normal circumstances a user does not have to deal with the contents of themakefile, as the standard template is automatically chosen according to the desired target.However a user may edit this file to include further sources to the actual compile and linkprocess to include own code.

The makefile is put into the build directory and the name will be ”model.mk”.

Stand-alone executable compilation

The creation of the executable can be accomplished either within the Simulink GUI by themenu or a hot-key ”Ctrl + B”, or without an actual running Simulink at the commandprompt. Due to the use of makefiles also the manual compilation and link process ofthe executable is rather simple for the user. It may be started by calling the followingcommand from within the build directory:

make -f model.mk

The created executable will then be placed in the root directory of the build directory.This executable may then be used to perform a simulation without the actual need ofhaving Simulink installed or running on this workstation. If several signals were set to bemonitored on the MATLAB Workspace, a .mat file will be created in the same directorycontaining these values to be analyzed with a MATLAB session at any time.

4.2.2 Simulink Wrapper Concept

The aim of the desired wrapper is to enclose an interface to a simulink model for com-munication with foreign models. The communication and synchronization with the entirecosimulation is intended to be synchronous, based on a fixed time-step size, and to usestream sockets for the implementation of the desired communication channels. The com-plete concept may be found in the design chapter.

A cycle based synchronization may be achieved by performing the simulation in singlestep mode and provide input values before the computation of a single time-step anddistribute the output values thereafter. Examining the produced code of the GeneralRealTime Target unveils that the created executable uses a very similar concept, whichcan be adopted to include the desired features.

One possibility for this adoption is to write a new target. This is a very time-consumingtask and needs special experience. Similar to several other projects using the code cre-ation process to interface Simulink to a cosimulation [Mad00, Tud00], it was decided toaccomplish the adoption with an alteration of the produced code.

Page 87: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 86

As mentioned on page 84 the main routine resides in a special file in the Simulinkdirectory, global to simulations of a single target. For the Generic RealTime target thisfile is called grt main.c. This file will only be copied to the model’s build directory, if thegenerate-code-only option was chosen for the build process, otherwise it will included fromwithin the Simulink source tree during the compilation.

Referring to figure 4.2 on page 81 and keeping in mind the differences in the files cre-ated, there are four main files containing the simulation code and relevant to the cosimu-lation interface; model.h , model.c, grt main.c and model.mk.A detailed inspection of these files shows a clear information separation between the files;the model information resides in the model.* files, the main routine controlling the com-plete simulation is located in grt main.c, and the makefile is used to determine the neces-sary parts and actions to create the executable.An investigation of grt main.c unveils that the main routine follows a very simple concept:After an initialization phase including the allocation of memory and starting the Simulinkdata logger, the model is operated in single time-steps within a loop until the simulationend-time is reached, followed by a final cleanup for memory reallocation and closing thedata logger to write the .mat file including the observed signal values as mentioned onpage 85.

As mentioned before a cycle-based cosimulation interface can be implemented by run-ning the simulation in single step mode within a loop, and transfer signal values at eachtime-step. An investigation of the documentation and the code of grt main.c shows thenecessary steps to achieve the desired operation. Generally spoken the mentioned func-tionality contained in the grt main.c can be divided into three routines called by the actualwrapper to perform the simulation:

• Initialization Routine

• A routine to perform the computation of a single step

• Final Cleanup Routine

The concept now provides the ability to run a model in single step mode within thewrapper and synchronize the model to the global cosimulation as desired. As mentionedbefore for a correct synchronization with other modules it is necessary to have time-stepsof a predefined equidistant size. For a Simulink Simulation, this is possible via choosingthe simulation parameters prior to the code generation as described in section 4.2.1 onpage 82 to feature a fixed time-step size.

For a data exchange with foreign modules, it is necessary to drive values to simulinkmodel inputs and retrieve values from its output signals. Examining the documentationand the generated code shows that there exist special sinks intended for this; ”ExternalIn- and Outputs”.

These special sinks and sources are available in the standard libraries and are usedfor the communication of subsystems within a simulink model. These special in-/outputs

Page 88: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 87

of a model are accessible in the C-Code via two special structures; the input-vector rtUand an output-vector rtY. It shall be mentioned that only the special signals of the rootmodule are contained in the vectors, but not the signals of sub-modules. At this pont thesimulation concept of the wrapper is complete:

• The cycle-based synchronization is achieved by running the simulation in single stepmode,

• In- and output values may be driven and retrieved via special in- and output vectorsrtU and rtY.

• The communication has to be implemented according to implementation of thecosimulation communication presented in section 4.1.3 at page 76.

Figure 4.7 illustrates the concept for a practical realization of the wrapper.

sock

ets

WRAPPER

simulation initalization

while simulation {

retrieve model inputs

distribute model outputs

}

simulation cleanup

perform model single step

Cleanup

ComputationSingle Time Step

Initializationgrt_main.c

Routines

DivisionFunctionality

Foreign Models

..............

communication initialization

..............

communication termination

create

close

Figure 4.7: Simulation concept of the Simulink wrapper

This general implementation concept will be discussed in more detail in the followingsubsection.

4.2.3 Simulink Wrapper Realization

The wrapper was implemented according to the concept presented in the last subsectionillustrated in figure 4.7. An executable containing the Simulink simulation code andthe wrapper operating this simulation is desired. To implement the functionality of thewrapper and include the desired operation into a single executable the following four filesare used:

Page 89: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 88

• grt main 65.c, grt main 61.cThis file contains three routines to operate the Simulink simulation as mentionedon page 86. During the development of this project two different MATLAB ver-sions were used, with minor changes concerning internal Simulink data types andstructures. Therefore two different versions had to be written taking care of thesechanges.

• sim wrapper types.hThis file holds some definition concerning return values and similar things.

• sim wrapper.cThis file represents the wrapper itself. The wrapper is implemented in the mainroutine of the executable. The wrapper has to establish all connections, initializesthe model simulation, perform the simulation in single-step mode within a loopincluding the data transfer as well, and terminate the Simulink simulation and closeall open connections. The implementation of the communication is discussed startingat page 76.

• sim wrapper.hThis file contains several subroutines of the wrapper representing the implementa-tion of the cosimulation communication discussed starting at page 76. For examplethe i send() routine discussed on page 75. The sim wrapper.c is intended as a tem-plate wrapper to be altered by the engineer to meet the actual model. For betterreadability of sim wrapper.c all common subroutines reside in this sim wrapper.hfile included from sim wrapper.c.

To create the desired executable the model.mk makefile provided by the code creationprocess was used. To include the cosimulation interface, this makefile has to be adapted toinclude the wrapper code: In the ”Source Files” section there are two variables REQ SRCSand USER SRCS, which have to be altered. REQ SRCS has to include the adaptedgrt main 6X.c instead of the original grt main.c, and the sim wrapper.c containing thewrapper has to be added to the USER SRCS as illustrated.

...

#----------------------------- Source Files -----------------------------------

REQ SRCS = $(MODEL).c $(MODULES) grt main 65.c rt sim.c rt nonfinite.c

$(EXT_SRC)

USER SRCS = sim wrapper.c

...

Due to this changes a ”make -f Makefile” will produce a standalone executable con-taining the Simulink model operated by the wrapper.

Page 90: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 89

General Structure

In the generated simulation code all model data is associated directly or indirectly witha special central structure, which is of type SimStruct in case of MATLAB 6.1 andRT MODEL in case of MATLAB 6.5. The routines applicable to this structure andoperating the model take a pointer to this structure as an argument to identify the modelto operate.

Considering the three desired routines to operate the model, it becomes obvious thatinitialize() will create the model and shall return a pointer to the connected SimStructwhich then can be used by perform single step() and clean up() to address the model.

The general concept of the wrapper was already presented in subsection 4.2.2. Streamsockets use send and receive commands to transfer data ; these routines however do notensure the sending of all data but return a value indicating the amount of data sent (referto subsection 4.1.2 for more details). Therefore two further subroutines i send() i recv()will be used to provide more flexibility.

As mentioned before, a fixed time-step size is used for the model simulation to easesynchronization, what will be assumed in the following.

Wrapper Simulation Routines - grt main 6x.c

In the generated code the standard Simulink file grt main.c includes the operation of thesimulation. In this code all model data is associated directly or indirectly with a specialcentral structure of type SimStruct in case of MATLAB 6.1, and of type RT MODEL incase of MATLAB 6.5. Although the structures are named differently one can be castedto the other. The routines applicable to this structure and operating the model take apointer to this structure as an argument to identify the model to operate.Simulink provides a variety of functions to operate a model, such as MdlUpdate() forupdating discrete states, MdlDerivatives() for the calculation of the derivatives for con-tinuous states of a block, or MdlOutputs() to calculate its outputs. A detailed view of allsubroutines and functions used would be to much to include here, but can be obtained fromthe RTW and TLC documentations [Mata, Matd] or an investigation of the grt main.cfile itself.

Considering the three desired routines to operate the model, it becomes obvious thatinitialize() shall create the model instance and return a pointer to the connected SimStruct,which then can be used by perform single step() and clean up() to address the model.

Although there have to be written different versions of these functions for both MAT-LAB versions due to the internal changes, the mentioned compatibility of the generalstructures SimStruct and RT MODEL, offering the possibility of casting to each other,implies that the wrapper implementation does not dependent on the used version, despiteof the three mentioned routines. This greatly enhances the usability of the wrapper code.

For the implementation of the desired simulation operation function the standardgrt main.c was investigated in detail in combination with the documentation to determine

Page 91: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 90

all necessary internal functions; In grt main .c the internal model operation functions aregrouped into subroutines including error handling at the beginning of the file. Thesesubroutines are then used in a main() routine to perform actual simulation.

After a check of the command line parameters for the main routine (please refer to theRTW user guide [Mata] for documentation) the simulation environment gets initialized,what includes memory allocation, the instantiation of the general SimStruct for the actualmodel, and the setup of initial values and parameters. Afterward the model is executedclock-tick by clock-tick and return values are checked and results stored. A special returnvalue of the single time-step simulation execution indicates the end of simulation duration,at which all logged values are written to an output file and a final cleanup releases allocatedmemory.

As this procedure is well tested and maintained, it is a good idea to adopt the wholeprocedure including the complete error handling and alter it, instead of writing completenew functions. The following three pseudo-code sections describe the actual implementa-tion of the desired function.

SimStruct* matlab initialize (int T argc, const char T *argv[]){

check command line arguments;

allocate memory;

create SimStruct for the model;

initialize the model;

start the model;

return a pointer to the model’s SimStruct

for further use within the wrapper;

}

int matlab execute singleStep(SimStruct *B){

(assume input vector rtU is set correctly)

proceed in time by one time step;

calculate outputs (output vector rtY);

return a value indicating an error / success / end of simulation;

}

void matlab cleanup SS(SimStruct *S){

stop data logging and write/close output file;

terminate the model;

}

Page 92: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 91

The presented functions offer a wrapper the option of operating the Simulink simulationlike desired. In the following the realization of the wrapper functionality is presented.

Sim wrapper.* : The Simulink Wrapper

In subsection 4.2.2 the general concept for a Simulink wrapper was presented. The wrappershall operate the simulink model time-step-wise and synchronize with foreign models cycle-based via sockets. Due to the actual code length it is not possible to include the completecode within the document. In subsection 4.1.3 the implementation of the cosimulationcommunication was discussed in respect to the communication channels.To illustrate how these communication mechanisms integrate with the prior presentedsimulation operation functions to provide the desired executable, a general description ofthe wrapper implementation is presented in the following.

The actual wrapper represents the main function of the created executable. Its se-quential procedure can be divided into three stages, as illustrated in figure 4.7 on page 87:

• InitilizationIn this stage the communication details are instantiated and the desired channelsare established as discussed in section 4.1.3 starting at page 76. A global variable forthe model’s SimStruct is allocated and initialized via matlab initialize() presentedin subsection 4.2.3.

• Cosimulation OperationThis stage is intended to include the model’s Simulation operation and the cosim-ulation data communication. Within a loop with possible lead-in or lead-out sec-tions(see section 4.1.3 for more details), needed external input values are retrievedfrom the cosimulation network and written to the input vector ”rtU”, followed by thecomputation of a single time-step of the simulation via matlab execute singleStep().After the computation the output values are read from the output vector ”rtY” andsent via the specific communication channels to the according external models. Theloop contains a counting value, increased with each iteration, to indicate the actualtime-step for use as a time-stamp for the sent data.The vectors rtU and rtY contain the external in- and outputs indexed by their names.Thus an external input with name ”In1” can be accessed via ”rtU.In1”. Howeverif a simulink signal has a name, this name overrides the input port name. So if anexternal input with name ”In1” is connected with a signal named ”rate” to a block,the input can be accessed only via ”rtU.rate” but not ”rtU.In1”.The operation loop runs until the end of a simulation is reached, indicated by a spe-cial return value ”SS REACHEND” from the matlab execute singleStep() routine.According to the communication implementation rules presented in section 4.1.3 onpage 79 special structures are used for the communication implementation.

Page 93: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 92

• Final CleanupAfter the cosimulation was performed, the simulink model needs a cleanup via mat-lab cleanup SS() presented in subsection 4.2.3 and opened communication channelsshall be closed as addressed in section 4.1.3 and illustrated in the examples availablein appendix B.1.

In the design chapter the possibility of having different rates for single communicationchannels was discussed. The model operates at an internal rate according to the enteredtime-step size. If signal values do not have to be transferred at this rate, but only at aninteger multiple of this rate it is possible to perform a modulo operation on the countingvalue and perform the actual data transfer operations according to the result of thisoperation.

4.3 Modelsim Interface

This section deals with the implementation of a wrapper to Modelsim as introduced onpage 64 in the design chapter. Modelsim is a very widespread HDL7 Simulator fromModeltech. A major feature of Modelsim is the availability of several interfaces, andtherefore its adaptivity. For the implementation of the wrapper the FLI8 and its providedfunctionality to take influence on the simulation itself and connect custom C-code to thesimulation kernel will be used.The FLI interface is only available with the SE version of Modelsim, so the use of thisversion is mandatory.

An introduction to the FLI interface was given in the design chapter. For further infor-mation please refer to the corresponding information found in [Mod01]. In the followingsubsections the wrapper concept derived in the design chapter will be discussed in moredetail for an actual implementation.

4.3.1 General Modelsim Wrapper Concept

The aim of the Modelsim wrapper is to enclose an interface to a VHDL model for acommunication with foreign models. The communication and synchronization is intendedto be cycle-based with a fixed time-step size and shall utilize sockets to feature networkcommunication.

In the Simulink wrapper the cycle based synchronization is achieved by performing thesimulation in single step mode, which means time-step by time-step. This is realized byan alteration of the available simulation code. For Modelsim such simulation code is notavailable, thus the Modelsim wrapper has to integrate into the complete VHDL designenvironment. This means, the wrapper code has to gain control of the simulation flow

7Hardware Description Language8VHDL Foreign Language Interface

Page 94: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 93

to some extent. It has to halt and resume the simulation at special simulation states toprovide the possibility for a synchronous data exchange with foreign models.

As mentioned in the design chapter, Modelsim offers several powerful interfaces, whereasthe most appropriate for this thesis is the FLI9 interface. Refering to subsection 3.5.2and [Mod01] the FLI offers the possibility to integrate foreign architectures (C-code) intoa VHDL design. Via the FLI interface it is possible to create special processes, which maybe scheduled or sensitized to VHDL - signals. A special self re-scheduling process of typeimmediate will be used in the wrapper for the desired synchronization.Modelsim uses a time-step size of one nanosecond by default. If a foreign module providesor needs data at a rate of 2kHz (what represents a time-step size of 500 µs) a processof type immediate will be scheduled at this rate. The steps done within this processwill include halting the simulation, exchanging signal values with the foreign model andrescheduling itself before continuing the simulation.

This schema implies that this rate has to be an integer multiple of the simulationgranularity used by the VHDL simulator. Furthermore it shows that it is easily possibleto have connections of different synchronization rates. For a convenient handling of multi-rate systems a process table containing all different rates may, and will, be used.

Generalized, for the actual realization the wrapping code resides in a foreign architec-ture and is included in the simulation according to the following figure 4.8

Wrapper Implementationso

cket

s

entity module entity cosim interface

Por

t

foreign architecture

Por

t

VHDL Model

entity cosimulation

e.g. clock

Figure 4.8: Integration of the Modelsim wrapper into a VHDL simulation

To feature this concept the VHDL model to be cosimulated has to include all desiredcommunication signals in its port. Then the higher order cosimulation entity encloses thewrapper and the VHDL model to be simulated, and provides all necessary signals to theVHDL model (e.g. clock) as well as the interconnectivity between the two entities.

A simulation can then be carried out by compiling all sources, loading a design of thecosimulation entity and running this design afterward.

In the following the creation of a foreign architecture and the desired possibility toexchange data with a VHDL model will be discussed, completed by an illustration of theactual implementation of the wrapper.

9VHDL Foreign Language Interface of Modelsim

Page 95: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 94

4.3.2 Creation of a Foreign Architecture

This section provides a short introduction to foreign architectures and how to create andintegrate them into a VHDL simulation. Foreign architectures represent design unitsfeaturing an external implementation of VHDL entities via custom C-code.With the use of FLI to integrate a foreign design into a VHDL simulation, a VHDL entityis used to provide the interface to the actual C code implementation of the architecture(see figure 4.8). The implementation itself has to be provided via an object file, which isconnected to the VHDL part through a special architecture description. In the followingthe creation of both parts will be discussed.

For detailed information on foreign architectures and the FLI please refer to the FLIdocumentation [Mod01].

The VHDL architecture description

The VHDL code of an FLI design consists of three parts; the generic, port, and architecturedefinitions. In the architecture definition the FOREIGN attribute has to be declared(which is available in the STANDARD package of VHDL since VHDL93) to indicate thatthe functionality of this architecture resides in foreign custom C-Code. An actual foreignarchitecture description looks like the following:

ATTRIBUTE foreign OF name : ARCHITECTURE IS "app init app.so; parameter";

As mentioned the keyword ”foreign” is used to indicate that the functional implementationuses custom C-code. The parameters ”app.so” and ”app init” refer to the name of theshared object file containing the C-Code and the name of the initialization function of thiscode to be called in the simulation initialization phase as discussed on page 94.It is advisable to include the complete path in the filename, as otherwise only the localdirectory will be searched for this library. The third argument ”parameter” is preceded bya semicolon and is optional. It may contain parameters to be provided to the initializationfunction.

The C-code Implementation

The custom C-code relating to a design using the FLI has to be implemented accordingto several rules:

• C initialization functionThe C initialization function is very essential for using the FLI. It is invoked duringthe elaboration phase of Modelsim, thus when a design is loaded and the simulatorstarts. This elaboration phase is intended to load all foreign shared libraries andexecute their initialization functions.

Page 96: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 95

The initialization function typically

– allocates memory to hold variables for this instance

– registers a callback function to free the memory when the simulator is restarted

– searches for (port-) signals to be read from and saves the handles to these signals

– creates drivers on the ports that shall be driven (written at)

– creates one or more processes, and connects C functions to the created processesto be invoked at process activation

– either sensitizes the processes to a list of signals, or schedules them

• The functionalityThe functionality of the architecture resides in C functions which are related to pro-cesses, and are invoked, when a process is activated. This may happen by sensitizinga process to signals to be invoked when these signals change, or by scheduling theprocess (what implies intended self-rescheduling in many cases).

• Final CleanupAs memory might be reserved in the initialization function, this memory has to befreed when the simulator stops or is restarted. There may be other stuff to do aswell, for instance close open (socket-) connections and similar things.

A special header file ”mti.h” has to be included to provide access to the FLI functions,data types and definitions. These functions and definitions can be used to interact withthe Modelsim simulation environment, and present structures according to prior definedimplementation rules. Detailed information on the provided functions and structures isprovided within the FLI documentation [Mod01], whereas some details will be presentedin the following ”Modelsim Wrapper Realization” subsection.

As mentioned earlier the external C-code has to be provided as a shared library, com-piled and linked accordingly. For Linux gcc and cc compilers are supported and the typicalsyntax to create a shared library would be:

gcc -c -I/<install_dir>/modeltech/include app.c

ld -shared -E -o app.so app.o

4.3.3 Modelsim Wrapper Realization

The last few sections provided an insight on how to integrate foreign C-code into a VHDLsimulation via the FLI interface. In this section these method will be used to implementa Modelsim wrapper for the desired cosimulation, and implementation details relating tothis will be discussed.

Concerning data transfer into and out of a VHDL design, FLI offers complete mech-anisms to access the port signals of the foreign architectures via signal handles to readsignals and driver mechanisms for flushing values on signals.

Page 97: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 96

In the following details about the synchronization and data transfer implementationwill be presented.

Interface Synchronization

As mentioned earlier Modelsim is a discrete event simulator using delta cycles to describeconcurrency. This time utilization enables Modelsim to proceed step by step in generaltime and order concurrent events within a single time-step. The aim of the wrapper is, toaccess all values after the completion of the computation of a single time-step and beforethe simulator begins with the calculation of the next time-step.

The FLI offers the possibility to create and schedule processes with special priorities,which are IMMEDIATE, NORMAL, SYNCH, NBA, and POSTPONED in descendingpriority. If triggered these process groups are executed in descending order. The FLIuserguide [Mod01] characterizes processes of type immediate as follows:

”All immediate processes run immediately after signal activation (if triggered).If any immediate process activates any signals, then the signals are reevaluatedand all immediate processes (if triggered) are run again in the same delta. Thiscycle continues until no more signals are activated.”

Thus immediate processes scheduled at a special time are the first ones to be activatedwithin the computation of this single time-step. This means, if a C-function containingthe data transfer mechanisms is bound to a process of type IMMEDIATE scheduled at thedesired rate of the connection, the synchronization will fulfill all requirements. Howeverthis inhibits the use of other immediate processes, or at least other IMMEDIATE processeshave to be used with precaution to do not alter the validity of the signal values to betransferred by the cosimulation interface.

In [Gos02] the problems entailed by using to much delta delays within a design arediscussed. A secure precaution to minimize side-effects of delta delays, and to ensure thevalidity of the cosimulation interface as well, is to minimize the use of these delays withina design.If a design has a rate of 20ms and all system activity is calculated until 18ms (and thelast 2ms contain no system activity) it is safe to schedule the interface at 19 ms for thefirst time, and reschedule it at a rate of 20ms afterward, as there will be no other systemprocess or activity the interface might interfere with.

In respect to the implementation of the desired synchronization, the initialization partof the FLI interface contains the setup of the processes related to the desired interfacesand schedules them for the first time. Interfaces with different rates can be realized withmultiple processes, whereas each rate has one single process.An FLI process is accessed via a handle of type mtiProcessIdT and created via the com-mand mti CreateProcessWithPriority(name, func, param, priority). Name is a string

Page 98: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 97

which can be assigned to the created process, and func is a pointer to the c-function con-nected to the process. Param may contain parameters to be passed to the c-function andpriority determines the desired priority of the process. The following code generates aprocess proc1 of type immediate which executes the c routine i face() with no parameters:

...

mtiProcessIdT proc1;

proc1=mtiCreateProcessWithPriority("P1", (mtiVoidFuncPtr) i face,

NULL, MTI_PROC_IMMEDIATE );

...

The synchronization of the data connections of the wrapper with the VHDL simulationis implemented according to presented scheme. As interfaces with multiple rates shall besupported, for each rate a single process of type IMMEDIATE is created and connected to aC-function containing the actual data transfer routines. In the initialization function of theFLI design these processes will be created and scheduled for their first time. The processesshall then reschedule themselves at the desired rate after each connection, therefore theirconnected C-Functions contain the corresponding commands.

Modelsim Data Acquisition

Modelsim provides a complete set of functions to access signals within a foreign archi-tecture. For this work it was decided to use only the port signals, however it is possibleto access signals not contained in the port of a foreign architecture as well [Mod01]. Forthe access of all necessary functions the Modelsim header file ”mti.h” has to be includedby the foreign C-Code. In the following details on how to access, read and write portsignals of the foreign architecture will be provided by the presentation of the available FLIfunctions and needed data types.

To address a VHDL signal, a signal handler is needed. Special FLI functions can beused to read a signal addressed via this handler. To write to a signal, a signal driver hasto be created. These mechanisms will be now presented in more detail

Acquiring a signal handle handle

To address a signal, a handler of type mtiSignalIdT is needed. The signals to be accessedby the desired interface are located within the port of the entity. To acquire a handle fora port signal, the following syntax can be used:

mtiSignalIdT signal_id;

signal_id = mti FindPort( list, name )

Page 99: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 98

The function mti FindPort() searches the interface list (list) and returns a handle to theport signal whose name matches the specified name (parameter name refers to a string).

Read a signal value

The FLI offers several functions to access the data of signals. Depending on the signal typedifferent routines have to be used. For instance mti GetSignalValue(signal id) returns thesignal value for signals of type enumeration, integer and physical. For composite, real,and time type signals, mti GetSignalValueIndirect(signal id, void* buffer) has to be used,whereas the buffer parameter is a pointer to the memory location the value should beplaced. It can be NULL to tell Modelsim to allocate this memory on its own. The returnvalue of mti GetSignal ValueIndirect() is the pointer to the memory address the value isstored at. A simple way to avoid memory allocation and release issues is to use globalvariables within the FLI application and provide their address to this function.The following sample code illustrates read access to Modelsim signals:

real output1;

int step;

....

mtiSignalIdT sinus id, step id; // - create signal handles

signal id=mti FindPort(list, "sinus"); // - acquire them

signal id=mti FindPort(list, "step number");

mti GetSignalValueIndirect(sinus id,(void*) &output1); // - read values

step=mti GetSignalValue(step_id);

...

Reconsidering the schema of foreign architectures (refer to page 94) it is recommendedto have the signal ids as global variables, and acquire them within the C initializationfunction. Considering the global concept of the wrapper, the actual reading will thenoccur in the process representing the special interface.

Write a value to a signalTo write a value to a Modelsim signal a signal driver has to be used. To address this driver

a driver handle of type mtiDriverIdT is needed, which is created at the driver creationprocess via mti CreateDriver(signal id).To avoid unexpected behavior a driver must have a driver owner, which is a process iden-tified by an mtiProcessIdT value and is connected via the mti SetDriverOwner(driver id,process id) command.To write the value to the signal, the driver has to be scheduled to accomplish this withthe mti ScheduleDriver(driver id, value, delay, mode) function call.The driver id parameter of mti ScheduleDriver() identifies the driver to be scheduled, valueis of type long or (void*) depending on the signal type. For a signal of scalar type, value

Page 100: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 99

is the actual value to be driven, for a signal of type real, time, or array it is a pointer tothe value to be driven. Via the delay and mode parameters the behavior of the driver canbe determined. The delay parameter represents the delay in current time units until thedriver flushes its value onto the signal, and ”mode” indicates whether a transport delay isused or the value shall be driven inertial.

The desired Modelsim wrapper uses drivers for all signals to be written. Reconsideringthe components a foreign architecture (see page 94) it is convenient to place the creation ofthe drivers into the C-initialization function, and have the driver ids accessible via globalvariables. The actual driver scheduling will be done within the process.

A short piece of sample code shall illustrate the signal driving schema used within thewrapper. A driver for the signal ”sinus” is created, whereas its owner is a process ”pro-cess1” containing the functions to retrieve the value from another simulator and schedulesthe driver to write the actual value to the signal.

C initialization function:

mtiDriverIdT sinus driver;

mtiSignalIdT sinus id;

...

sinus id=mti FindPort(list,"sinus"); // Find the signal

sinus driver=CreateDriver(sinus id); // Create a driver for it

mti SetDriverOwner(sinus driver, process1); // Set its owner

process1

...

retrieve value sinus via socket connection;

mti ScheduleDriver(sinus driver, (void*) &sinus,

(mtiDelayT) 0, MTI_INERTIAL );

....

4.3.4 Summarized Modelsim Wrapper Implementation Concept

Summarizing and completing the information presented in the prior sections dealing withthe different aspects of the wrapper implementation, the complete wrapper is implementedaccording to the following rules specific to Modelsim, extending the cosimulation commu-nication implementation presented in section 4.1.3 starting at page 76:

• The wrapper consists of an VHDL part and a C-code implementation. The VHDLpart contains the VHDL entity of the wrapper, and a higher order entity cosimulationconnecting the wrapper entity to the VHDL design. The C-Code implementationis provided as a dynamic library and provides the functionality of the cosimulationinterface.

Page 101: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 100

• The C-implementation is parted into two files; interface.c and interface.h. The headercontains some subroutines and definitions in the wrapper.The actual functionality resides in interface.c.

• For each rate at which data shall be transferred, a single rescheduling process of typeimmediate is created. The related the C-function for this process is called RateX,whereas X is a identification number, starting with 1. These functions acquire signalvalues from the VHDL model as well as the foreign models and transfer these valuesto the intended recipients.

• In the C-initialization function first all socket connections needed are established,and a process table is built. All processes shall be registered with this table accordingto their rates. For a process map entry a special structure proc info, containing theprocess id, the rate/delay and the information whether a lead in is needed for thisrate is used. All signal ids for the signals to be accessed are determined and storedinto global variables. The necessary signal drivers are instantiated as well. The laststep of the initialization function is to schedule all processes included in the tablefor the first time.

• A cleanup function invoked at the end of the simulation frees reserved memory andcloses open sockets.

As mentioned on page 78 loops between different modules require a special connectionscheme. As the synchronization is data driven, one module within the loop has to bechosen to start the simulation with an initial provided input value, instead of retrieving itfrom the network connections to simulators which have not started simulation yet as theydid not get the desired input values. Within the Modelsim wrapper, the lead-in has to berealized in a different way as in the Simulink wrapper due to the different implementationconcepts.A special flag used in the process map indicates whether a process related to a rate and oneor more connections needs a lead-in or not. After the first invocation of this process in theC-initialization function this flag will be set to ”no”. Therefore the lead-in can be realizedwithin the C-code connected to this process. The following pseudo code representing aprocess function shall illustrate this:

rate1 ()

{// 1. Read Values from Modelsim and possibly distribute them

Read values out of Modelsim

if (!lead-in)

{ send values to the other models;

}

Page 102: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 101

// 2. Read Values from foreign models and drive them

if (!lead-in)

{ retrieve values from co-simulation network;

}else { values = initial values;

}drive values into Modelsim;

lead-in = no;

reschedule rate1;

}

The simulation of Modelsim is continuable in contrary to Simulink. Therefore it has nodedicated timetable of the simulation. The user may start the simulation, proceed in timeas long and as many times as desired, and has to quit the simulation himself. Therefore adedicated lead-out is not needed necessarily. When connected to an Simulink simulationwith a dedicated simulation end-time, however an error on sending the data may beinterpreted as the indication to end the cosimulation and quit it. Another possibilitywould be to have a global counter and at a fixed value referring to the Simulink simulationend-time the process function may perform a lead-out and halt the simulation via a specialFLI command. When the entered simulation time of the VHDL model corresponds to thesimulation time of Simulink, and no lead-out was implemented the VHDL simulator willwork as normal, just an error message perhaps implemented in the C-code function willbe put out on the console.

4.4 A Wrapper for SystemC

The wrapper for SystemC is different than the wrappers intended to Simulink and Mod-elsim as discussed in the design chapter. In this section the encapsulation of a foreignsimulation into a wrapper will be shown and SystemC interconnection to provide a cosim-ulation of two wrapped foreign modules. For a better understanding of SystemC pleaserefer to the introduction given in the design chapter.

SystemC is library for simulation available in the C++ language. There is no GUIor development environment contained in SystemC. Setting up a SystemC simulation istherefore like writing a C++ program, but using the offered libraries. The simulationcontrol lies in the main routine which may instantiate and connect several SystemC com-ponents, initiates the scheduler and afterward starts the simulation.

A short introduction to the basics of SystemC may be found in subsection 3.2.3 atpage 51, however the consultation of the SystemC user guide is advised for a betterunderstanding.

Page 103: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 102

4.4.1 Building a SystemC Entity for a Foreign Module

Modules are the basic building blocks within SystemC representing single parts of theentire system. Modules hide internal data representation and algorithms from other mod-ules and provides public interface via port declarations. The functionality of modules isimplemented via processes. Processes are functions registered with the SystemC kernel.To register a process to the kernel, the module constructor SC CTOR is used. This specialconstructor provides the function a process refers to as well as a sensitivity list and thetype of the process to the SystemC kernel.The following pseudo-code illustrates this scheme:

///// name.h

SC MODULE(name) {

// SystemC Port declarations

sc_in <double> ulast;

sc_out <double> rate;

// Internal variables

int socket;

~name() {close network channels;

};

SC CTOR(name) {SC METHOD(perform step);

Sensitivity list;

Open network channels;

}

///// name.cpp

name::perform step () {

fetch signal values from network and write to port signals;

read signal values from port signals and send over network;

}

Page 104: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 103

This pseudo-code illustrates the scheme of a module implementing the desired wrappingof a foreign design. As usual with a design, declarations are located in name.h and thefunctionality in name.cpp. In the module declaration two port signals are defined, oneinput and one output port to the module. An internal variable for the use of a socket isdefines. The destructor’s functionality is to close open socket connections at the end ofthe simulation. The constructor registers a SC method process and its sensitivity list withthe simulation kernel.The function related to the method process is intended to perform the actions for a singlestep; collect the signal values from the foreign simulator and write them to the internalsignals, perform a single step and transfer the output values afterward.

Comparing this scheme it is obvious that the synchronization is not provided by thewrapper itself, but has to be implemented via a correct integration of this module into thesimulation.

The activation of this module represented by the sensitivity to an input port may playa significant role with this. A possibility would be to use the input signal for activation.If the SystemC-model relies on the internal time-representation it has to be ensured thatthe functionality of fetching and distributing data is only performed once a time step, andwith the desired data. Defining a dedicated trigger signal for this is an option. In the nextsection a cosimulation using this wrapper type illustrates this concept.

As mentioned in the design chapter it is also possible to create a similar wrapperas for Simulink, as simulation control is available to the user via sc initialize and sc cyclecommand. However the simulation semantic of SystemC as discussed in the design chapterunveils that values resulting from cthread processes get assigned at the next time-steponly, which would have to be considered when using this strategy. Similar to the Simulinkwrapper the actual code would reside in the main function of the SystemC model asillustrated in the following pseudo code:

sc main {open communication channels;

instantiate models;

connect models;

...

sc initialize;

loop lead in;

for simulation duration do

{ fetch values from network connections and assign them to the signals;

sc cycle

fetch signal values from SystemC-models and distribute over the network;}loop lead out;

close communication channels;

...

}

Page 105: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 104

After the initialization section for the simulation and communication channel setup, thesimulation is performed within a loop and possible a possible lead-in or lead-out. Withinthe loop cylce extern input values are retrieved, the simulation advances, and the compu-tated output signal values are distributed to the connected external modules.

4.5 Cosimulation Setup and Results

To test the designed and implemented cosimulation environment, several cosimulations ofan industry project were performed. This section covers documentation on these cosimu-lations to illustrate the cosimulation setup process and indicate an example design flow.The illustrattion is based on a design scenario where an asic and its test-bench are ini-tially designed in Simulink, and afterward a VHDL implementation of the asic shall becosimulated to verify the cosimulation behavior against the Simulink version.For a better overview this section covers only the setup process of a cosimulation andwill not deal with implementation details. Therefore it is highly recommended to readthe prior sections of the implementation chapter to have implementation details availablewhen reading this section.

As aimed in the objectives (see page 12) a typical automotive application is used forthis test. This application is however under an NDA10, thus no model internals can beprovided, but only a general view and some signal diagrams. Figure 4.9 shows a simplifiedmodel view. The ASIC’s11 aim is to control a system. A model of this system acts asa test-bench for the asic and returns a status value indicating the system state, to beconsidered by the control algorithm of the asic.

ASIC Test−BenchControl

Reference

Figure 4.9: An example system based on an ASIC and a test-bench

A typical design process starts with a Simulink design of the entire system for a firstbehavioral test. Simulink simulations are performed to check the design’s behavior, andto have a reference for future comparisons with other simulation and cosimulation re-sults. Special sinks can be used to access signal values of the Simulink model and storetheir values at the MATLAB workspace. Using compiled executables of the simulations,

10Non-Disclosure Agreement11Application Specific Integrated Circuit

Page 106: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 105

these results will be stored in a model.mat file which can be imported into the MATLABworkspace at any time to view the results.

To test the cosimulation environment, the next step was to part the complete systeminto two Simulink models, one containing the asic, the other one representing the test-bench. As the Real-Time Workshop is able to translate used subsystems within a design,subsystem modules may be used in the simulink design to simplify the partitioning step.Otherwise the different parts of the complete system may be transferred by drag&drop intonew Simulink models, whereas their simulation parameters have to be chosen accordingto the entire system. To access model data, external in- and outputs are used (refer tosubsection 4.2.2).For both modules, the asic and the bench, the RTW code creation process was carriedout, implementing single-tasking simulation of fixed time-steps of 20 microseconds and asimulation duration of 15 seconds. The grt main 6x.c files (see page 89) were copied tothe respective build directories, and the makefiles were edited to include these new filesand the wrapper code (see page 88).Both the asic and bench connect to one single other module, implying one single channelto be established for each of them. As the connection of the modules is based on a loop,one has to chosen to start with an initial value (refer to page 78). The asic was thestarting module and was chosen to implement the server functionality of the connection(see page 76) as well. The bench would be the client. Therefore the asic features a lead-into the simulation loop (see page 78) of the Simulink wrapper (illustrated in figure 4.7 atpage 87) and the bench a lead-out. The lead in of the asic is illustrated here:

..

rtU.In1 = 14.5;

execute single matlab simulation step;

send output values (rtY) on channel 1;

while (simulation)

{ retrieve input values on channel 1 and set rtU accordingly;

ret = execute single matlab simulation step;

if (ret != end of simulation reached)

send output values (rtY) on channel 1;

}..

According to the general communication rules at page 79 general structures and specificvariable names were used for an implementation according to the details presented insection 4.1.3 staring at page 76. For the simulation two different Linux hosts were used,therefore data transfer problems as mentioned on page 75 had not to be addressed. As bothcosimulation partners used the same internal representation of signals to be transferred

Page 107: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 106

no translation had to be performed, and doubles were used for the data transfer. Thecosimulation was performed on two Linux hosts connected via a 10 Mbit LAN12 connection.The asic had to be started first, as it included the server implementation of the socketconnection and no polling mechanisms were realized (page 76). The actual bandwidthused was about 400kB/s.

The results of this simulation will be discussed and compared to results of other sim-ulations at the end of this section.

The next step of the test was the setup of a cosimulation containing a VHDL repre-sentation of the asic and the Simulink model of the bench. To show the independency of asingle module to the actual simulators of other connected modules, the bench executablecreated in the last test for the Simulink cosimulation was used in this test as well.

Therefore the decisions made for the asic represented in Simulink are valid for a VHDLdescription as well. The asic shall be the server of the connection, and a lead-in is neededto provide an initial value. The VHDL entity of the wrapper has to include signals forthe control and reference value (figure 4.9 at page 104) in its port, and the cosimulationentity has to connect the wrapper entity to the asic’s VHDL model.As the asic does only connect to the bench, a single process scheduled at the rate of thesystem (20 µs) is used for the wrapper. In the C-initialization function of the Modelsimwrapper the server of the connection has to be implemented, and the connection to thebench has to be established. Signal handlers stored in global variables have to be retrievedfor access to the control and reference values which have to be transferred between theasic and the bench. For the reference value a driver has to be created to write the receivedvalue onto the VHDL signal. A single process has to be created, registered with theaccording flag for a lead-in with the process table, and scheduled for the first invocationat the desired rate. This functionality referred to the C-initialization function.The C-function connected to the process has to manage the actual data transfer, readingvalues from their respective sources and propagate them to their destination. As mentionedbefore a lead-in as illustrate on page 100 for a Modelsim wrapper has to be implemented.The actual simulation can be started by loading the design into Modelsim, starting theSimulink executable, and starting the VHDL simulation with the dedicated Modelsimcommand.

The last step of this test concerned the SystemC wrapper. Due to the lack of anactual SystemC representation of the asic or bench, the interface was tested in anotherway. Both the asic and test were represented via Simulink executables wrapped intoa SystemC SC Module as presented on page 102. The port signals include the controland reference signals, and boolean get control and give control signals for triggering themodel’s functionality routine.

The used SystemC wrapper is different from the wrappers of Modelsim and Simulink as

12Local Area Network

Page 108: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 107

it’s concept does not include the task of synchronization. This task is up to the SystemCmodel itself. For this test, the synchronization between the asic and the bench was realizedin SystemC according to their data-driven dependency to each other. The get controlsignal of the asic is connected to give control module of the bench and vice versa.In theperform() function of each model, the give control signal is inverted to trigger the perform()function of the other module.

The sc main function has to initialize the modules and connect the data signals of botmodules, and has to provide an initial stimulus on the control signal to trigger the asic forthe first time, as illustrated by the following code:

int sc main(int argc, char* argv[]) {

sc signal<double> reference, control;

sc signal<bool> control1, control2;

// instantiate models and bind signals (make connections)

part1 asic("asic");

asic.get control(control1);

asic.give control(control2);

asic.out(control);

asic.in(reference);

part2 bench("bench");

bench.get control(control2);

bench.give control(control1);

bench.in1(control);

bench.out1(reference);

reference=14.5; // initial value

control1=NULL;

sc start(1); // start simulation

....

}

The result of this is an endless loop executed within a single time-step of SystemCand broken when the Simulink models with their predefined simulation time exit. It isobvious that an interpretation of the SystemC time in respect of the global simulation timeis useless, as in SystemC the time does not proceed. As mentioned in the introductionto SystemC starting at page 51 SystemC is intended to be used for multiple models

Page 109: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 108

of computation, whereas here a data driven model of computation was used for testingpurposes.

With actual SystemC models this will however be different, but it is up to the SystemCdesign to synchronize to the global cosimulation (time).

In the following, time-diagrams of a single signal determined at the different cosimu-lations are offered to illustrate the validity of the cosimulation environment. This signalrefers to an internal state of the bench which is very sensitive to minimal changes of thecontrol signal.

Figure 4.10: Time-diagram of signal ”A” determined at a Simulink simulation

It is evident in these diagrams, that the presented signals is consistent to the differentco-simulations, indicating that the developed cosimulation environment has no impact onthe validity of signals. Although there might be small differences in the quantity of thesignals due to varying internal calculations, the quality of the signals is obviously consistentbetween the various simulations. This fact ensures the usability of the developed approachin future development processes.

Page 110: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 109

Figure 4.11: Time-diagram of signal ”A” determined at a Simulink cosimulation

Figure 4.12: Time-diagram of signal ”A” determined at a Simulink - Modelsim cosimula-tion

Page 111: Design and Implementation of a Cosimulation Environment ...

CHAPTER 4. IMPLEMENTATION OF THE COSIMULATION ENVIRONMENT 110

Figure 4.13: Time-diagram of signal ”A” determined at a SystemC based Simulink cosim-ulation

Page 112: Design and Implementation of a Cosimulation Environment ...

Chapter 5

Conclusion and Perspectives

Verification and validation are essential tasks of every development process. Simulation isa solution to these tasks, available and used in almost every design environment.Single engineering tools are scarcely able to cope with the steadily increasing exigenciesin respect of complexity and integration density. Especially the combination of variousdesign domains in a single product poses a severe challenge to available design methods.Therefore available verification and validation techniques are faced with heterogeneoussystem descriptions.To extend the widely used concept of simulation, cosimulation approaches, combining thepower and expressiveness of different simulators and design tools, have been developed toprovide a means of validation and verification for heterogeneous system designs.To interconnect simulators there exist various approaches presented in this work and dif-fering in several implementational aspects. Global simulation control, simulator synchro-nization, and communication mechanism represent only a small choice of these aspects.

In this work a cosimulation approach has been developed to combine the featuresof Simulink, Modelsim, and SystemC for the design of a single product. The designedcosimulation method provides the essential means of validation and verification of designprocesses utilizing heterogeneous system descriptions developed with these tools.Usability, extensibility, and independency were essential master profiles for the develop-ment process of the cosimulation approach. The provided solution supports simple designsas well as complex systems. An implementation of the developed approach was utilizedfor the verification of single steps in the design process of an automotive application. Theimplemented cosimulation environment was used for the cosimulation of various heteroge-neous system descriptions of this application. The implemented solution had to prove itsvalue with a real-world application and stood this test.

111

Page 113: Design and Implementation of a Cosimulation Environment ...

CHAPTER 5. CONCLUSION AND PERSPECTIVES 112

There exist various options to enhance the developed and implemented cosimulationenvironment, which shall be mentioned at this point and are partly addressed within thedocument as well:

• Development of cosimulation interfaces for further simulators: To extendthe expressiveness of the available cosimulation environment, wrappers for furthersimulators could be developed.

• A standard signal logging entity: A central signal logger would enhance theusability of the cosimulation significantly, as the simulation data and results wouldbe available via a single tool and in a single format.

• Automation of the interface generation: A network list of an actual systemdescription could be used to generate the according wrappers for the single mod-ules automatically. A reorganization of the available wrapping code into templatesavailable via a special library would support this concept.

• Implementation of libraries: To decrease the code length of the wrapper mainfiles and enhance their readability, libraries containing routines for standard proce-dures could be realized. Special procedures like the communication establishmentcould be integrated into single subroutines organized in such libraries.

• Enhancement of communication setup and transfer mechanisms: Currentlythe implementation lacks the availability of polling mechanisms. Therefore the sim-ulators have to be started in a special order, and within the wrappers the establish-ment of channels and data transfer routines are sequential and blocking. The use ofpolling mechanisms for the connection setup, or the integration of special approachesto dynamically reorganize the sequence of data transfers within a single time-stepcould affect the usability and simulation time of complex systems in a positive way.

Page 114: Design and Implementation of a Cosimulation Environment ...

Appendix A

List of Acronyms

API Application Programming InterfaceASIC Application Specific Integrated CircuitDE Discrete EventDUT Device Under TestFLI VHDL Foreign Language Interface [Mod01] of ModelsimFPGA Field Programmable Gate ArrayFIFO First In First OutGRT Generic RealTime Target of SimulinkGUI Graphical User InterfaceHDL Hardware Description LanguageIEEE Institute of Electrical & Electronics EngineersIC Integrated CircuitIP Intellectual Property

Internet Protocol [bib81a]LAN Local Area NetworkNASA National Aeronautics and Space AdministrationNDA Non-Disclosure AgreementOS Operating SystemPLI Verilog Programming Language Interface of ModelsimRPC Remote Procedure CallRTL Register Transfer LevelRTW Real-Time Workshop [Mata]TCL/TK Tool Command Language and its graphical ToolKitTCP Transmission Control Protocol [bib81b]TLC Target Language Compiler [Matd] used by the RTWUML Unified Modeling LanguageUSB Universal Serial Bus, a PC interfaceVHDL Very High Speed Integrated Circuit Hardware Description Language

113

Page 115: Design and Implementation of a Cosimulation Environment ...

Appendix B

Examples

B.1 Example Stream Socket Server & Client

To illustrate stream socket programming two example programs will be listed, a serverand a client. They connect to each other and each party sends and receives one integer.In these examples local Unix sockets are used, and no error detection is implemented tominimize the code length.

B.1.1 An example server program

#define ADDRESS "/tmp/sock1"

main()

{int server s, client s; // server and client socket

int length; // buffer variable

int mesg in, mesg out=5; // data to be received and sent

struct sockaddr un server a, client a; // server and client address

server s=socket(AF UNIX,SOCK STREAM,0); // acquire a socket

server a.sun family=AF UNIX; // set server address family

strcpy(server a.sun path,ADDRESS); // and address

length=sizeof(server a.sun family)+strlen(server a.sun path);

bind(server s, server a, length); // bind the socket to the address

114

Page 116: Design and Implementation of a Cosimulation Environment ...

APPENDIX B. EXAMPLES 115

listen(server s, 5); // listen to the socket,

//and allow 5 connections pending

client s=accept(server s, client a, &length) // accept a connection request

// to the server socket and

// retrieve the client address

send(client s, (void*) &mesg out, sizeof(mesg out), 0); // send data

recv(client s, (void*) &mesg in, sizeof(mesg in), 0); // receive data

close(client s); // close sockets

close(server s);

}

B.1.2 An example client program

#define ADDRESS "/tmp/sock1"

main()

{int server s; // socket to communicate with server

int length; // buffer variable

int mesg in, mesg out=5; // data to be received and sent

struct sockaddr un server a; // server address struct

server s=socket(AF UNIX,SOCK STREAM,0); // acquire a socket

server a.sun family=AF UNIX; // set server address family

strcpy(server a.sun path,ADDRESS); // and address

length=sizeof(server a.sun family)+strlen(server a.sun path);

connect(server s, server a, length); // connect the socket to the server

recv(client s, (void*) &mesg in, sizeof(mesg in), 0); // receive data

send(client s, (void*) &mesg out, sizeof(mesg out), 0); // transmit data

close(client s); // close sockets

close(server s);

}

Page 117: Design and Implementation of a Cosimulation Environment ...

Bibliography

[ARJ99a] Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullmann. Compilerbau Teil 1.Oldenburg, second edition, 1999. ISBN 3-486-25294-1.

[ARJ99b] Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullmann. Compilerbau Teil 2.Oldenburg, second edition, 1999. ISBN 3-486-25266-6.

[Bar99] Tvrtko Barbaric. Hardware/Software Codesign mit Backplane-Verfahren undoptimierter Synchronisation. Technical Report F755-9130093, 1999.

[Bec99] Kent Beck. Embracing change with extreme programming. 32(10):70–77,October 1999.

[BG02] Alistair Bruce and John Goodenough. HW/SW-Co-Verifikation von IP-Blocken: Wieder verwendbare Verification. (5):30–32, 2002.

[bib81a] RFC:791 Internet Protocol, Darpa Internet Program Protocol Specification,September 1981. http://www.rfc-editor.org/rfc/rfc791.txt.

[bib81b] RFC:793 Transmission Control Protocol, Darpa Internet Program ProtocolSpecification, September 1981. http://www.rfc-editor.org/rfc/rfc793.txt.

[bib97] Erweiterte Verwendung und Validierung von Statemate Modellen durch Kon-vertierung zu SDL. Berner & Mattner, 1997. 5. Deutsches Anwenderforumfuer Statemate.

[CRAB01] Luc Charest, Michel Reid, E.Mostapha Aboulhamid, and Guy Bois. AMethodology for Interfacing Open Source SystemC with a Third Party Soft-ware. Technical report, Universite de Montreal, Canada, 2001.

[DG00] Rainer Domer and Daniel D. Gajski. Reuse and Protection of IntellectualProperty in the SpecC System. Technical report, Department of Informationand Computer Science, University of California, USA, 2000.

[ELESV97] Stephen Edwards, Luciano Lavagno, A. Lee Edward, and AlbertoSangiovanni-Vincentelli. Design of embedded systems: formal models, vali-dation, and synthesis. In Proceedings of the IEEE, volume 85, pages 366–390,march 1997.

116

Page 118: Design and Implementation of a Cosimulation Environment ...

BIBLIOGRAPHY 117

[Eur] European SystemC User Group. VHDL-to-SystemCConverter. download at http://www-ti.informatik.uni-tuebingen.de/systemc/download software.html.

[Exp] Experimental Computing Laboratory, University of Cincinnati. SAVANT:VHDL Analysis Tools. http://www.ececs.uc.edu/paw/savant/.

[FFS] Alessandro Fin, Franco Fummi, and Denis Signoretto. The use of SystemCfor Design Verification and Integration Test of IP-Cores. DST Informatica,Universita di Verona, Italy.

[Gos02] Sumit Gosh. In search of the origin of vhdl’s delta delays. In Proceedingsof the international Symposium on Quality Electronic Design, pages 310–315,2002.

[GWC+00] Daniel D. Gajski, A. Wu, V. Chaiyakul, S. Mori, T. Nukiyama, and P. Bricaud.Essential Issues for IP Reuse. In Proceedings of the ASP-DAC 2000, pages37–42, 2000.

[Hub98] Heiko Hubert. A Survey of HW/SW Cosimulation Techniques and Tools.Master’s thesis, Royal Institute Of Technology, Sweden, 1998.

[IEE99] IEEE/ASME International Conference on Advanced Intelligent Mechatronics,editor. Methods and tools for the design of novel multi-functional automoitivelighting, 1999.

[IEE02] IEEE Computer Society, 3 Park Avenue, New York, 10016-5997, USA. IEEEStandard VHDL Language Reference Manual, 2002 edition, may 2002.

[JB00] Axel Jantsch and Per Bjureus. Composite signal flow: a computational modelcombining events, sampled streams, and vectors. In Design, Automation andTest in Europe Conference and Exhibition 2000, pages 154–160, 2000.

[KWG+02] L. Kriaa, W.Youssef, G.Nicolescu, S.Martinez, S. Levitan, J. Martinez,T. Kurzweg, A.A. Jerraya, and B.Courtois. SystemC-Based Cosimulation forGlobal validation of MOEMS. Technical Report ISRN TIMA-RR-02/01-1–FR,TIMA Laboratory, Grenoble, France / Department of Electrical Engineering,University of Pittsburgh, Pennsylvania, USA, 2002.

[LWS94] G. Lehmann, B. Wunder, and M. Selz. Schaltungsdesign mit VHDL.Number ISBN 3-7723-6163-3. Franzis’ Verlag, 1994. http://mikro.ee.tu-berlin.de/ kds/text all.pdf.

[Mad00] Michael M. Madden. An Object-Oriented Interface for Simulink Models. Tech-nical Report AIAA-2000-4391, NASA Langley Research Center, Hampton,USA, 2000.

Page 119: Design and Implementation of a Cosimulation Environment ...

BIBLIOGRAPHY 118

[Mata] The MathWorks Inc., Natick, USA. Real-Time Work-shop For Use with Simulink Users’s Guide, 5 edi-tion. http://www.mathworks.com/access/helpdesk//help/pdf doc/rtw/rtw ug.pdf.

[Matb] The MathWorks Inc., Natick, USA. Simulink Model-Basedand System-Based Design; Simulink Reference, 5 edition.http://www.mathworks.com/access/helpdesk/help/pdf doc/simulink//slref.pdf.

[Matc] The MathWorks Inc., Natick, USA. Simulink Model-Based and System-Based Design; Using Simulink, 5 edition.http://www.mathworks.com/access/helpdesk/help/pdf doc/simulink//sl using.pdf.

[Matd] The MathWorks Inc., Natick, USA. Target Language CompilerFor Use with Real-Time Workshop Reference Guide, 5 edition.http://www.mathworks.com/access/helpdesk/help/pdf doc/rtw//targetlanguagecompiler.pdf.

[Mod01] Model Technology, Portland, USA. Modelsim: Foreighn Language Interface,5.5f edition, August 2001.

[Mod02] Model Technology, Portland, USA. Modelsim SE Tutorial, 5.6 edition, March2002.

[MP02] Mike Keating and Pierre Bricaud. Reuse Methodology Manual for System-on-a-Chip Designs. Kluwer Academic Publishers, third edition, 2002.

[NMK+02] G. Nicolescu, S. Martinez, L. Kriaa, W. Youssef, S. Yoo, B. Charlot, andA. Jerraya. Application of Multi-domain and Multi-language Cosimulation toan Optical MEM Switch Design. Technical Report ISRN TIMA-RR-01/09-1–FR, TIMA Laboratory, Grenoble, France, 2002.

[PKPS03] Markus Pistauer, Suad Kajtazovic, Ingo Pill, and Christian Steger. Systemver-ifikation im Designprozess heterogener mikroelektronischer Systeme, Septem-ber 2003. Analog ’03 Conference, Heilbronn, Germany.

[Rei98] Stefan Reichor. Integration realer Hardware in den VHDL-Simulationsablauf.Master’s thesis, Abteilung Mikroelektronische Systeme des Instituts fu Sys-temwissenschaften, Johannes Kepler Universitat Linz, april 1998.

[RPS98] Stefan Reichor, Markus Pfaff, and Markus Schutti. Integration externer Kom-ponenten in den Simulationsablauf von VHDL. Technical report, Research In-stitute for Integrated Circuits, Johannes Kepler University Linz, AltenbergerStr. 69, A-4040 Linz, Austria, 1998.

Page 120: Design and Implementation of a Cosimulation Environment ...

BIBLIOGRAPHY 119

[Sim98] C. Simhart. Implementierung einer HW/SW Cosimulations-Schnittstelle furdie Simulation heterogener Systeme. Master’s thesis, Technische UniversitatGraz, Osterreich, 1998.

[sys01a] SystemC Konsortium. Functional Specification For SystemC 2.0, Final, 2001.http://www.systemc.org.

[sys01b] SystemC Konsortium. SystemC Version 2.0 User’s Guide, 2001.http://www.systemc.org.

[Thea] The MathWorks. MATLAB The Language of Technical Computing: ExternalInterfaces Version 6.

[Theb] The MathWorks. MATLAB The Language of Technical Computing: UsingMATLAB Version 6.

[Tud00] Stephane Tudoret. SIGNAL-SIMULINK: Hybrid System Co-simulation. InLinkoping Electronic Articles in Computer and Information Science, volume4(1999): nr 20, February 2000. http://www.ep.liu.se/ea/cis/1999/20/.

[Unia] Universita di Verona, Dipartimento di Informatica. Anoverview on vhdl2sc 1.0. available for download athttp://bear.ces.cwru.edu/ecmp 488/VHDL to SystemC.pdf.

[Unib] University of Cincinnati, FTL Systems Inc. AIRE/CE AdvancedIntermediate Representation with Extensibility/ Common Environment:Internal Intermediate Representation (IIR) Specification, 4.6 edition.http://www.ececs.uc.edu/paw/aire/iirUS.pdf.

[WJH+] W.Muller, J.Ruf, D. Hoffmann, J.Gerlach, Th. Kropf, and W. Rosenstiehl.The Simulation Semantics of SystemC. Technical report, Universitaten vonPaderborn und Tubingen, Paderborn/Tubingen, Deutschland.

[Zim03] Stefan Zimmermann. Report Chipdesign: Test, 1, 2, 3, Test, Test - Entwurf,Verifikation und Test integrierter digitaler Schaltungen. c’t magazin fur Com-putertechnik, (18):78–83, August 2003.