03 process domain

122
173-Prdef Process Domain Chapter 3

Upload: syed-shakeeb-sadiq

Post on 18-Apr-2015

27 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 03 Process Domain

173-Prdef

Process Domain

Chapter 3

Page 2: 03 Process Domain

174-Prdef

Modeling Concepts

Page 3: 03 Process Domain

175-Prdef

Modeling Concepts

IntroductionP

rocess D

om

ain

Prdef.1 Introduction

Process models are used to specify the behavior of processor and queuemodules which exist in the Node Domain. OPNET process models can be used toimplement a wide variety of hardware and software subsystems, includingcommunication protocols, algorithms, shared resources such as disks or memory,operating systems, queuing disciplines, specialized traffic generators, customstatistic collectors, and so on.

This chapter is divided into two major sections. The first section,

Prdef.2Process Model Operation

, defines the process modeling constructs provided byOPNET and describes their features and applications. The second section,

Prdef.3Process Model Development Methodology

, presents a generally-applicablemodeling methodology that guides you through the steps of creating a processmodel.

Prdef.2 Process Model Operation

OPNET node objects are used to represent devices that can be connectedtogether to form networks. Devices may range from simple traffic sources tocomplex switches or computers running multiple applications. Nodes are createdas

instances

of node models, meaning that a node model is the “blueprint” for allof the individual nodes of a particular type. Node models are defined as acollection of modules representing distinct functional areas of the node. Certainmodules are limited in the types of behavior they can represent: generators aresimple traffic sources provided for convenience; and the various transmitters andreceivers represent interfaces to links defined in the network domain. Two types ofmodules, called

processors

and

queues

, support fully general behavioral modeling.

These modules offer essentially the same capabilities with regard to theirgeneral behavior and most of their physical resources. However, queue modulesprovide special support for organized packet storage by allowing users to defineinternal subqueues in which packets can be inserted and sorted, and from whichpackets can be extracted according to a general, user-defined method. For thepurposes of most of the material in this chapter, queues and processors can betreated identically since they rely on the same process modeling technology torepresent their behavior. Therefore, in order to simplify general discussion, theterm

QP

will be used to represent these modules.

Prdef.2.1 Process Environment

Individual processes or groups of processes are defined to implement aparticular task when placed within a QP. A process is an

instance

of a processmodel defined with the Process Editor. In other words, each process model may beassigned to many QPs within a single system. All individual process instances aredefined to have similar characteristics but may operate in different environments.

Process models perform one of two functions, depending on the QP. A processmodel typically represents a behavioral model of a process, as explained below.

Page 4: 03 Process Domain

176-Prdef

Process Model Operation

Modeling Concepts

This section describes in general terms the context in which processes performtheir functions.

Prdef.2.1.1 Interrupt-Driven Execution

Like all other subsystems in OPNET models, processes are driven by events.When an event is actually delivered to a process, it is termed an

interrupt

, asdefined in the

Modeling Framework

chapter of this manual; the process is said tobe interrupted which means that it is

invoked

to allow it to take some action inresponse to the interrupt.

The reasons for which a process may be interrupted vary widely from processto process, and most processes themselves expect several types of interruptssignifying different conditions to which they must respond. Therefore, one of thefirst actions that is generally taken by a process upon being interrupted is todetermine what type of interrupt has occurred. Subsequently, more detailedattributes of the interrupt might also need to be analyzed. Depending on theinterrupt type, these attributes might be the input stream or statistic, the esys portthat has a new value, the source module that caused the interrupt, or possiblyapplication-specific information contained in an Interface Control Information(ICI). The

Modeling Framework

chapter presents a detailed discussion of interruptprocessing.

A process follows an alternating cycle of invocation and rest periods.Invocations may occur on an arbitrary basis depending on the timing of externallyand internally generated events. A process always begins the simulation in aresting mode, waiting to be invoked; a process that is waiting in this conditions issaid to be

blocked

. Invocation allows a process to resume execution and to performnew actions. Once these actions are completed, the process must again block,returning control to the Simulation Kernel so that other events in the system maybe executed. Because these subsequent events may be scheduled for arbitrarilynear future times, and even for the same time as the current event itself, theinvocation must occur without allowing any time to elapse. In other words, thesimulation time observed (e.g. by calling the KP

op_sim_time()

) at the start and atthe end of an event, must always be identical. Note that this requirement does notimply that processes cannot model actions that consume time; only that modelingsuch actions can sometimes require multiple events. The requirement for zero-delay execution of events and techniques for delay modeling are explained in detailin the

Modeling Framework

chapter. The following diagram depicts the alternatingsequence of blocking, invocation, activity, and back to blocking.

Page 5: 03 Process Domain

177-Prdef

Modeling Concepts

Process Model OperationP

rocess D

om

ain

Prdef.2.1.2 Dynamic Processes

At the moment when a simulation begins, each QP hosts only one process thatis automatically created by the Simulation Kernel. This process, termed the

rootprocess

, is an instance of the process model designated in the QPs

process

model

attribute. The root process model can be designed to manage even very complexsets of tasks, and so depending on the application, the root process may besufficient to provide the QP module with its intended functionality. However, inmany modeling situations, it is possible to take advantage of the capability of a QPto host multiple processes in order to improve the modularity and reduce thecomplexity of a design.

New processes become associated with a QP module when the processes thatare already present within it request their creation via the KP

op_pro_create()

. Asingle QP may be the host to any number of processes that cooperate to implementits function within the surrounding node model. Processes that are created by otherprocesses (as opposed to the root processes created by the Kernel) are referred toas

dynamic processes

. There are two principal cases in which a QP generallymakes use of dynamic processes:

1) At least part of the QPs functionality requires it to manage tasks that aregenerated on a dynamic basis (i.e., their exact timing or number are notknown in advance). In such cases, a new process can be generated tocorrespond to each task as it arises. The process can then be destroyedwhen the task is complete. Because there is no upper limit on the num-ber of processes allowed in a QP, any number of concurrent tasks canbe handled in this manner. A typical example of this of application ofdynamic processes is the implementation of a circuit-oriented protocolsuch as X.25, where new circuits are opened and closed based on in-coming requests whose patterns are unpredictable. Each circuit can bemanaged by an independent OPNET process, and all circuits can flowthrough the same QP module, allowing a single module to represent thefunctionality of the protocol within the node.

Blocked Active

Process performsactions wheninvoked

Process becomes blocked again; timeis still T

Interrupt causes invocation of process at time T

Process Blocking/Activity Cycle

Page 6: 03 Process Domain

178-Prdef

Process Model Operation

Modeling Concepts

2) The activities of the QP are conveniently represented as multiple asyn-chronously running processes. The required processes may all be creat-ed when the QP configures in the beginning of the simulation and mayremain the same throughout the simulation afterwards, each processimplementing a subset of the overall QPs functionality and perhaps co-operating with other processes to support their activities as well. Gen-erally this approach is used when a QP is required to manage severaltasks in parallel, each of which is substantially independent of the oth-ers.

Process Hierarchy

Since dynamic processes are always created by other processes, the rootprocess must be involved in originating them. The first generation dynamicprocesses (i.e., those generated by the root) may then in turn create new processes,which would be referred to as second generation. With respect to a process thatcreates it, a dynamic process is referred to as a

child process

; conversely, thecreating process is referred to as the

parent process

. Since all processes have thecapability to create others, the processes within a QP form a tree structure with thebranches representing parent-to-child relationships. The root process is theultimate “grandparent” of all processes. The following diagram illustrates theconcept of a QPs process hierarchy:

Since processes can be destroyed as well as created, the process hierarchy mayshrink as well as grow. In addition, there is no requirement that a process’ childrenmust all be destroyed before it can itself be destroyed; thus “holes” may appear atcertain levels within in the process hierarchy, corresponding to the fact that certainprocesses have no active parent processes. Note however that the root process

number of processes may scaledynamically as demand requires

Root Process

First GenerationChild Processes

Second GenerationChild Processes

Third GenerationChild Processes

Typical Process Hierarchy within a QP

Number ofGenerationsis not limited

Page 7: 03 Process Domain

179-Prdef

Modeling Concepts

Process Model OperationP

rocess D

om

ain

plays a special role in handling interrupts for each QP, and that it is the onlyprocess that may not be destroyed. The role of the root process is addressed in asubsequent section on interrupt steering.

Note that a process is capable of creating child processes of any type (i.e.,based on any process model), including its own or the type of its parents; however,a complete list of child process models that it intends to instantiate must bedeclared prior to simulation as part of the process model definition. Attempting tocreate a process based on a process model that is not declared may result in anerror during simulation. The Process Editor provides an operation called DeclareChild Process Models that supports menu-based editing of the potential childprocess list. Refer to the

System Menus

chapter of the Editor Reference manual formore information on this operation.

Promoted attributes of a child process are promoted along with those of theparent process, and therefore appear in the attribute lists of queues and processorsat the node level. The child process’s attributes are prefixed with the name of theprocess model in order to differentiate them from other similarly-named attributes.

Shared Memory Architecture

When a QP relies on multiple processes to implement its functionality, theseprocesses often require some form of communication between them in order tocooperate in managing the QPs tasks. The Simulation Kernel therefore providesthree communication mechanisms that allow multiple processes to shareinformation. These mechanisms may be used individually or combined.

QP-level shared memory

: This form of memory, also referred to as

module memory

, allows all process in a QPs process hierarchy to com-municate information to each other by placing this information in acommon area. Each QP maintains a single memory address that pro-cesses can assign or obtain by calling the Kernel Procedures

op_pro_modmem_install()

and

op_pro_modmem_access().

The various processes that use this mechanism must agree on the for-mat of the data that is pointed to by the shared memory pointer. In gen-eral this is done by defining a data structure that can be referenced byall processes. To make certain that all processes use a consistent formof the data structure, even when it is changed, the definition should bekept in an external definition file that is included in each process’ head-er block; in the C language, definitions files are named with a “

.h

” suf-fix.

Page 8: 03 Process Domain

180-Prdef

Process Model Operation

Modeling Concepts

Initially, the Simulation Kernel provides no shared memory for a QP(the Kernel Procedure

op_pro_modmem_access()

returns a NIL valueto indicate that this is the case); it is up to the processes within the QPto decide how much memory is necessary and when it should becomeavailable. The processes are therefore responsible for allocating theblock of shared memory, after which it can be installed by calling

op_pro_modmem_install()

. Memory allocation is generally performedby calling

op_prg_mem_alloc()

.

It is possible for a shared memory block that has been installed to bereplaced by another. The KP that supports installation simply allows anew memory address to take the place of the existing one, without pro-tecting against loss of the data that was previously installed. Thereforeprocess architectures that perform multiple installations are responsiblefor any required memory deallocation.

Process models that use shared QP-level memory reference common structure definition via #include statement in their header block.

Processes set/get the shared memory area’s address via the KPs op_pro_modmem_install(), op_pro_modmem_access().

Coordination of QP-Level Shared Memory

typedef struct{int n;double x;char s [16];} shared_mem;

Shared memory block is organized according to structure definition in external definitions file.

/* sharedmem.h */

Any of the processes in a QP, regardless of type, may communicate via a single shared memory area.

sharedmemory

QP

QP process hierarchy

definitions file

Page 9: 03 Process Domain

181-Prdef

Modeling Concepts

Process Model OperationP

rocess D

om

ain

In practice, a shared memory block is usually installed only once andthis installation is performed by the root process when it is invoked forthe first time. This allows other processes in the hierarchy to simply as-sume that the memory is available. Once QP-level shared memory hasbeen installed, processes may communicate information to each otherby writing data into the common memory space. This is generally doneby assigning values to the members of the installed data structure. Otherprocesses then examine the contents of the data structure and make useof this information as required. Communication between the processesusing module memory can be on an active basis or on a passive basis.Active communication involves modifying the shared memory con-tents and then invoking the process that is to receive the new informa-tion (invocations between processes are performed with the KP

op_pro_invoke()

). Passive communication simply involves modifyingthe shared memory contents, but relies on the destination process to au-tonomously examine the shared memory, perhaps at a later simulationtime.

Parent-to-child shared memory

: in many cases, the communicationthat must take place within a QPs process hierarchy is between process-es and their parents. This is due to the fact that child processes are oftencreated to handle parts of a parent process’ work and that results mustbe reported back to the parent. The Simulation Kernel provides specificsupport for this type of communication by allowing a private sharedmemory area to be set up at the time that a child process is created. Oth-er processes do not have access to the memory, although they may re-serve their own parent-to-child memory. The Kernel maintains anindependent shared memory block for each parent-child pair in the sys-tem.

As is the case with all inter-process memory mechanisms, parent-to-child memory is optional and may exist only between certain parent-

Parent-to-Child Shared Memory Organization

Each parent-child pair can establish an independent block of memory for two-way communication

The memory address NIL is installed when parent-child shared memory is not used

Root Process

NIL

Page 10: 03 Process Domain

182-Prdef

Process Model Operation

Modeling Concepts

child pairs. Unlike QP-level shared memory, however, parent-to-childmemory may only be installed once for each parent-child pair, when thechild process is created with the Kernel Procedure

op_pro_create()

. Re-placement of the memory block is not possible, although it may be deal-located when it is no longer necessary. A process may obtain theaddress of the memory that it shares with its parent process by callingthe KP

op_pro_parmem_access()

. However, since a parent process mayhave many child processes, and since it must supply the addresses ofparent-child shared memory, it is responsible for keeping its ownrecords of such addresses (e.g., by storing them in state variables).

In general, parent-to-child shared memory is allocated by calling theKP

op_prg_mem_alloc()

. The format of the shared memory is transpar-ent to the Simulation Kernel, which only manages the memory block’saddress. However, as in the case of QP-level shared memory, the parentand child processes must agree on the memory format and this is usu-ally accomplished by referencing a common definition of a C or C++data-structure to allocate and access the shared memory. Once theshared memory block is established (i.e., when the child process is cre-ated), both the parent and the child may communicate information witheach other by modifying and/or examining the memory contents. If ap-plicable, they may choose to actively invoke each other to provide no-tification of changes to the shared memory area by calling the KernelProcedure

op_pro_invoke()

.

Argument memory

: communication between processes is often re-quired at the time that one process transfers control to another by invok-ing it with the Kernel Procedure

op_pro_invoke()

. In order to supportthis type of information passing,

op_pro_invoke()

accepts a generalmemory address as an argument and makes this address available to theinvoked process. As with the other two memory mechanisms, the mem-ory address points to a block of memory whose format is user-definedand the two processes must be designed to agree on how its contents areorganized. The invoked process obtains the memory address by callingthe KP

op_pro_argmem_access()

. It may then use the memory to obtainparameters that affect its behavior, and/or modify the memory to returnstatus information to the process that invoked it.

Note that unlike the other two memory mechanisms, argument memoryis not persistent. This means that each new invocation of a process re-quires that an argument memory address be passed again, even if it isthe same as the address supplied for a previous invocation between thesame two processes.

Each of the mechanisms described above supports communication ofinformation via an abstract data object in the sense that the Simulation Kernel doeshave knowledge of the structure or contents of the shared information. The

Page 11: 03 Process Domain

183-Prdef

Modeling Concepts

Process Model OperationP

rocess D

om

ain

memory address is manipulated as a general pointer and the process logic isrequired to “cast” or “coerce” the type of the pointer so that it becomes a pointer toan appropriate data structure, as agreed upon by the various communicatingprocesses. Also note that each memory mechanism supports two-waycommunication of information since all processes that have access to a memoryblock may both insert and extract information from it. For further information onprocess shared memory mechanisms, refer to the

Process Package

chapter of the

Simulation Kernel

manuals.

Operations on Dynamic Processes

All interactions between dynamic processes are performed via the KernelProcedures (KPs) of the Process package. In addition, several KPs in the Interruptpackage provide capabilities that indirectly affect the operation of processes.Complete information on these procedures is presented in the appropriate chaptersof the

Simulation Kernel

manual. The general capabilities provided by these KPsand related process model design issues are reviewed in this section.

As mentioned earlier, only one process initially exists in each QP, and this isthe root process specified in the QPs

process

model

attribute. Additionalprocesses may be spawned when the root process (and subsequently otherprocesses) calls the KP

op_pro_create()

. When a process model is created, it isimplicitly incorporated into the process hierarchy of the process that created it.There is no way to create a process in another QP than that of the current process.

In order to create a child process, its process model should be declared in thespecification of at least one of the existing processes. Declaration is performed viathe

declare

child

process

models

operation in the Process Editor. While it issufficient for the created process’ model to be declared in the models of any of theQPs processes, it is generally a good practice of modular design to declare as partof each process model, the names of all the processes that it is capable of creating.In this manner each process is responsible only for declaring the process that itdirectly creates, and new process models can always be included in a processhierarchy without concern for their own potential use of dynamic process creation.

When a process is created, a special data item called a

process handle

isreturned by

op_pro_create()

. The data type used to declare a process handlevariable is

Prohandle

. Process handles uniquely identify a process, not onlywithin a process hierarchy, but within the entire modeled system (i.e., across allQPs). Process handles are required by most KPs in the Process package and sothey are commonly used by models that employ dynamic processes. Generally, aprocess uses process handles declared as state variables to retain access to theprocess handles that it obtains when it creates child processes. This allows it tolater perform fundamental operations on its children, such as invocation ordestruction. Process handles may also be obtained by several other KPs including

op_pro_self()

,

op_pro_parent()

, and

op_pro_root()

.

Two other forms of process identification are provided, but neither is necessaryto use the Kernel Procedures that affect processes.

Process ID

s are unique integer

Page 12: 03 Process Domain

184-Prdef

Process Model Operation Modeling Concepts

numbers that are automatically assigned to processes when they are created. Aprocess ID may never be changed, nor can it recur within the same simulation.Process IDs are used to represent processes in informative output issued by theOPNET debugger (ODB) or by user-developed reporting statements. A process’ IDmay be obtained by calling the KP op_pro_id(). A process tag is a user-suppliedstring that may be assigned to a process at any time. The content of the string istransparent to the Simulation Kernel and is currently used only to identifyprocesses or report special information about them as part of the output of the ODBcommand promap.

Certain dynamic processes are created to manage activities whose time-spansare limited, and their usefulness therefore expires when such activities complete.To avoid buildup of inactive processes, all dynamic processes (e.g., all processesbut the root) may be removed from their QPs process hierarchy by application ofthe KP op_pro_destroy(). This KP may be applied to other dynamic processes orby a dynamic process to itself when it has determined that is no longer needed.Note that process “self-destruction” in this manner should generally be the finalaction that a process attempts to perform, since use of op_pro_destroy() strips aprocess of several important resources, including its state memory.

In many cases, it is important for a parent process to be aware of thedestruction of one of its child processes. This allows the parent to keep itsknowledge of its child processes up to date and to deallocate any memory relatedto its relationship with the child, including parent-to-child shared memory installedwhen the child was created. If the child process performs its own destruction, theparent may be informed by modification of a flag in the parent-to-child sharedmemory. The parent may then check the flag when the child returns frominvocation (if the parent invoked it). Alternatively, a child process may request thatits parent destroy it via similar arrangement based on a semaphore within theshared memory area.

Regardless of the method by which a dynamic process is destroyed, theSimulation Kernel always provides it with an opportunity to perform a sequence offinal actions. This is done by executing a special section of the process model,called the termination block, prior to deallocating the process’ state memory.Typically the termination block contains statements that deallocate dynamicallyallocated memory that is referenced within the process state variables. Otheroperations that may be performed at termination include recording of final valuesof collected statistics and notification of other processes that may be affected.

The contents of the termination block are placed into a specially createdfunction by the Proto-C compiler; therefore no functions should be defined withinit, nor should local variables be declared. However, the statements within thetermination block do have access to state and temporary variables. In addition,prior to invoking the termination block of a process, the process is made active as ifinvoked, so that KPs that are context-dependent such as op_id_self() orop_stat_write() may be called.

Page 13: 03 Process Domain

185-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

If the occurrence of an interrupt does not directly invoke the process that isresponsible for its handling, or if the interrupt requires that several of a QPsprocesses take action, then process-to-process invocation is required. Thismechanism is supported by the KP op_pro_invoke() and allows one process thatcurrently controls the thread of execution to cause another process to temporarilytake control. An invoking process is suspended until the invoked process releasescontrol by blocking (i.e., the invoked process must enter an unforced state).Processes invoked by means of op_pro_invoke() may in turn use the KP themselvesto invoke other processes. The dynamic of this mechanism therefore resembles thatof function calls in stack-oriented languages such as C or C++. Note however, thatprocess invocation does not support recursion; this means that a process that issuspended, due to having called op_pro_invoke(), may not itself be invoked againuntil it has resumed control of the thread of execution and subsequently blocked.Another way of viewing this is that op_pro_invoke() may only be applied to fullyblocked processes. This limitation on recursion applies only to process instancesand not to process models. In other words, it is possible for distinct instances of thesame process model to invoke each other.

During an invocation, the invoked process can access any of the resources inthe QP, including, for example, packets or statistic values that were received tocause the interrupt of the invoking process. Note however, that if the invokingprocess has already consumed or modified such resources (e.g., removed a packetwaiting in an input stream), they will no longer be available to the invoked process.In other words, the invoked process should be thought of as performing a task onbehalf of the invoking process. It can therefore can be considered an integral partof the invoking process’ thread of execution, as if its actions were directlyspecified among the actions of the invoking process.

A distinction must be made between a parent process and an invoking process,although in many cases these may be the same. A process’ parent is the processthat created it and each process may therefore have only one parent (except theroot process, which has none). On the other hand, each process (including the root)may be invoked by any other process in the same process hierarchy, and differentprocesses may even invoke it during the same event. Note also that the two types ofrelationships between processes support different information sharingmechanisms. A process and its parent share memory on a persistent basis withparent-to-child shared memory, whereas invocation supports a temporary form ofshared memory to pass arguments (i.e., parameters) from invoking process toinvoked process.

Interrupt Steering

When an interrupt occurs for a QP, the Simulation Kernel must make adecision concerning which process will first be invoked to handle it. For mostinterrupt types, the Kernel has no knowledge concerning the tasks required by aninterrupt, and therefore its selection must be based on information supplied by theQPs processes themselves. Self and process interrupts are an exception to this rulesince they are implicitly directed toward particular processes. For other interrupt

Page 14: 03 Process Domain

186-Prdef

Process Model Operation Modeling Concepts

types, the Kernel therefore provides several KPs that allow processes to specifyhow the selection should be made. If none of these KPs are used by the processesof a QP, then the Kernel makes a default decision, which is to invoke the rootprocess.

The most general way to manage situations where interrupts must receiveinitial handling by different processes is to create a “dispatcher” process thatdecides which process to invoke. Typically, the dispatcher process would be theroot process, since it receives interrupts by default. Part of (or possibly all of) thelogic of the root process would be devoted to analyzing the attributes of anincoming interrupt in order to decide which of the QPs processes should beinvoked to actually perform the handling of the interrupt. The advantage of thisgeneral approach is that arbitrarily complex decisions can be made based on anynumber of properties of the interrupt. For example, attributes that might factor intoprocess selection include values of packet fields, origin of interrupt, port of arrival,time of arrival, and even state information accumulated while responding toprevious interrupts.

Complex steering of interrupts is best handled by an interrupt-dispatchingprocess as described above. However, KPs provided by the Simulation Kernel’sInterrupt package provide convenient and efficient support that is sufficient for

Using the Root Process as a Dispatcher

SimulationKernel

The Kernel provides all interrupts to the root process (except for self, process, and procedure types).

Process A

Process C

Process B

/* Based on interrupt properties, invoke appropriate child */ /* process. Start with packet-stream arrivals */if (op_intrpt_type()== OP_INTRPT_STRM)

{/* Obtain the packet and use packet class to determine *//* which process should handle it. */pk = op_pk_get ();op_pk_nfd_get (pk, "class", &class);switch (class)

{case PACKET_CLASS_A:

op_pro_invoke (process_a_handle, pk);break;

case PACKET_CLASS_B: op_pro_invoke (process_b_handle, pk);break;

case PACKET_CLASS_C: op_pro_invoke (process_c_handle, pk);break;

}

The root process invokes the process that is appropriate based on its analysis of the interrupt; in this case the “class” field of the received packet determines which process should be invoked.

Page 15: 03 Process Domain

187-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

certain simple situations. By using the provided mechanisms, any process mayregister itself or another process as the direct recipient of appropriate interrupts.

Specifically, two KPs are provided to request that the Kernel automaticallyinvoke a particular process based on the type of interrupt or based on the input onwhich an interrupt arrives. Steering based on interrupt type is supported by the KPop_intrpt_type_register(), and all interrupt types except for self, process, andprocedure are supported. For stream and statistic interrupts, the KPop_intrpt_port_register() provides additional specificity with regard to the inputstream or input statistic associated with the interrupt. When both mechanisms areused and are applicable, port registration has precedence over type registration.Automatic interrupt steering is discussed in detail in the Modeling Frameworkchapter of this manual.

Prdef.2.1.3 Local Process Resources

OPNET processes always operate within the context of a QP. The QP objectprovides the processes that it contains with certain resources that are implicitly partof each process’ environment. These resources are described in this section.

Input and Output Streams

Packet streams are objects that exist in the Node Editor and are used to connectmodules together. The packet streams support error-free transfer of packetsbetween modules, and can also delay the arrival of the packet at the destinationmodule. Packet streams connect to constructs in the source and destinationmodules which are called output and input streams respectively.

An input stream of a QP is capable of receiving packets from external sources.The packets are automatically queued within the input stream in first-in-first-outorder and are provided to any process within the QP upon request. Input streamsaccept packets from two sources: packet stream objects and the remote deliveryservice provided by op_pk_deliver() and related Kernel Procedures. A QP mayhave any number of input streams that are physically attached to packet streamobjects. In addition, input streams are dynamically allocated as necessary tosupport packet deliveries, since the Simulation Kernel has no prior knowledge ofthe range of input streams that will be delivered to or accessed.

Page 16: 03 Process Domain

188-Prdef

Process Model Operation Modeling Concepts

When packets are received on an input stream, one of the processes in thereceiving QP is usually invoked with a stream interrupt. The process maydetermine which input stream received the new packet by calling the KPop_intrpt_strm(). Input streams are referenced using non-negative integer indices.Processes may obtain the earliest arriving packet that remains in an input stream oftheir QP by calling the Kernel Procedure op_pk_get() and referencing theappropriate input stream index. The KP op_strm_pksize() can be used to determinethe number of packets still remaining in the input stream.

The opposite side of a packet stream attaches to an output stream construct.Output streams support communication of packets via the Kernel Proceduresop_pk_send(), op_pk_send_delayed(), op_pk_send_forced(), andop_pk_send_quiet(). Like input streams, output streams are referenced bynonnegative indices; however only output streams that are actually physicallyconnected to outgoing packet stream objects in the node domain are valid.

Output and input streams may also be referenced when the stream accessingmechanism is used. A QP can use stream accessing in order to signal to another QPthat it should forward a packet on one of its output streams. Assuming that moduleS is the source of a packet stream and D is its destination, the sequence ofoperations is typically as follows:

1

0

4

10

Queue/Processor Input Streams

Input streams contain internal FIFOs that can hold packets until they are extracted.

Processes are responsible for collecting packets from the input streams. Multiple processes can access the same input stream.Additional streams may be automatically

allocated to receive packets that are “delivered” to the QP. These may originate anywhere, including outside this node.

node boundary

Queue or Processor Boundary

Page 17: 03 Process Domain

189-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

1) D calls the KP op_strm_access(), in order to request that S send a packetto it over the stream that connects them. When calling the KP, D speci-fies the index of the input stream on which it wishes to receive the pack-et.

2) As soon as D calls op_strm_access (), a forced interrupt is generated forS. This means that D’s execution is temporarily suspended to allow S torespond (see the Framework chapter of this manual for more informa-tion on forced interrupts). The type of this interrupt is an access inter-rupt. S calls op_intrpt_strm() to determine on which output stream thepacket is being requested. S then responds to the access interrupt bysending a packet on that output stream, if it so chooses. In order to sendthe packet, S must use op_pk_send_quiet() because it has to avoid caus-ing an interrupt for D which is in a suspended state. Note that S couldtake other actions if desired, as well. S blocks in an unforced state.

3) D regains control immediately when S blocks and resumes executionimmediately after the point where it called op_strm_access(). D checksits input stream to determine if one or more packets have arrived, typi-cally using the KP op_strm_pksize(). If any packets are present, it mayretrieve them from its input stream using the KP op_pk_get ().

Input Statistics and Local Output Statistics

Input statistics are constructs that are internal to QPs and that accept numericvalues sent by other modules (not necessarily QPs) in the same node. Inputstatistics are generally used to monitor performance metrics or status signalsgenerated by other modules. The values are conveyed by statistic wire objects thatconnect the source and destination module. A destination module’s input statistic iscapable of retaining only the last value that it receives (i.e., no buffering of valuesis provided). This latest value is always available to any process in the QP bycalling the KP op_stat_local_read().

Each QP has exactly 100 input statistics, each of which can be connected to anynumber of statistic wires.The input statistics are referenced by integer indices inthe range 0 to 99. These indices correspond to the “dest stat” attribute of thestatistic wire object in the Node Domain. When multiple statistic wires areconnected to a single input statistic, the latest value of the most recently updatedstatistic is the one that is stored in the input statistic at any given time (note that astatistic may be updated without necessarily changing its value).

Changes in the statistics associated with the statistic wires always result instatistic events for the destination module. Each event may then result in thegeneration of a statistic interrupt for one of the processes in the receiving QP,depending on the interrupt-generation criteria imposed by the statistic wire (see theNode Domain chapter of this manual for more information on the operation ofstatistic wires). Upon receiving a statistic interrupt, a process may determine

Page 18: 03 Process Domain

190-Prdef

Process Model Operation Modeling Concepts

which of the QPs input statistics has received a new value by calling the KPop_intrpt_stat().

Local output statistics and input statistics form opposite ends of a statistic wirethat connects to QPs. The “Local” qualifier is used to distinguish these outputstatistics from global statistics that can be shared by multiple QPs across thesystem model. Local output statistics provide the ability to report user-definedstatistics that are private for each QP.

A local statistic can be tapped by statistic probes to contribute to a simulation’soutput file, as well as by a statistic animation probe to generate an animated viewof the statistic as it changes over the course of the simulation. Local statistics canalso be connected via statistic wires to the input statistics of other QP modules inthe same node, allowing values to be dynamically communicated to the destinationmodules as they are updated. Processes can update local output statistics by callingthe KPs op_stat_write() or op_stat_write_t (). Each local output statistic can feedmultiple statistic wires and probes in any combination. As the statistic’s value isupdated, each destination separately receives appropriate notification.

Each QP can maintain any number of local output statistics. If multipleprocesses coexist within the QP, the output statistics are shared by all of theseprocesses. In other words, any of the processes may update any of the outputstatistics, if needed. Processes must declare the local output statistics they intend touse; the Process Editor provides the edit local statistics operation for thispurpose. This operation is fully documented in the Editor Reference manual. Eachlocal output statistic may be dimensioned or undimensioned. An undimensionedstatistic is simply an individual statistic, which is the most common case. Adimensioned statistic is actually an array of statistics, containing any pre-determined number of individual statistics. The individual statistics aredistinguished by their index and can be updated and used independently.Dimensioned statistics provides a more convenient way of handling a large numberof similar statistics and are typically used in cases where a process manages ascalable number of entities, such as connections or neighbors. Often, in caseswhere child processes are used, each child process is responsible for updating oneof the output statistics in an array of local output statistics.

In order to gain access to a statistic in order to update it, a process must firstobtain a corresponding statistic handle. The KP op_stat_reg() allows the process toobtain this handle, which it may then retain (usually as a state variable) forsubsequent use. Refer to the Simulation Kernel manual for more information onop_stat_reg() and op_stat_write().

Global Statistics

Local statistics are ideal for reporting activity that is private to a particular QPat a given location in the system model. However, in many cases, modelers areinterested in obtaining quantitative information about the system as a whole. Forexample, in a network model, we may wish to measure the average end-to-enddelay experienced by all packets transmitted between applications, regardless of

Page 19: 03 Process Domain

191-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

the particular source or destination. Another common statistic of interest isnetwork throughput, which is a measure of the total amount of data the networkdelivers during a chosen time interval. Often, global statistics are simply averagesof local output statistics across many components in the system model. It iscommon to collect both types of statistics in the same simulation.

Global statistics can be used to feed values to two types of statistics collectionprobes: global statistic probes and statistic animation probes. Global statisticprobes transfer statistic values to the simulation’s output files, allowing them to beanalyzed in the Analysis Tool after simulation. Statistic animation probes allowdynamic viewing of the statistic during simulation.

OPNET provides similar, but separate support for local and global statistics. Aswith local output statistics, each process model is expected to declare the globalstatistics that it expects to update during simulation. This is done using the ProcessEditor’s edit global statistics operation which is fully documented in the EditorReference manual. Global statistics are accessed via a statistic handle which isobtained via the KP op_stat_reg(). In order to obtain the handle, the name andgroup of the statistic is specified; if different processes elsewhere in the systemmodel specify the same name and group when calling op_stat_reg(), then they willobtain the same statistic handle, providing a “rendez-vous” mechanism based onthe statistic name. The separate processes may then use the handle when callingop_stat_write(); the values provided by all of the processes are merged into a singleseries of values in the simulation’s output file, or in the statistic’s animation. Referto the Simulation Kernel manual for more information on working with globalstatistics.

Subqueues

Queue modules may be configured within the node domain to contain anynumber of subqueues that allow packets to be stored in an organized manner. Allprocesses within a queue module have equal access to the subqueues and mayinsert and extract packets as required to implement a particular queuing policy. TheQ and Subq packages of Kernel Procedures support processes that operate onsubqueues. See the Simulation Kernel manual for detailed information on theseKernel Procedures. Also refer to the Node Domain Definitions chapter of thismanual for a detailed explanation of how queues and subqueues are structured.

Attributes

Like all OPNET objects, QPs have a set of attributes that specify some of theirfundamental characteristics. All processes within a QP may modify and obtain thevalues of these attributes by calling the KPs op_ima_obj_attr_set() andop_ima_obj_attr_get(), respectively.

Built-in attributes are predefined and similar for every QP, though their valuesare assigned independently on a per-QP basis. Model attributes can be declared bythe modeler in order to support modeling of application-specific object

Page 20: 03 Process Domain

192-Prdef

Process Model Operation Modeling Concepts

characteristics. The Process Editor’s edit model attributes operation isprovided for this purpose (refer to the Editor Reference manual for moreinformation on this operation).

Model attributes are inherited by QPs from their assigned process models. Thisset of attributes is formed from the process model attributes of the root process aswell as from those of its child process models. To avoid attribute naming conflictsbetween the various processes, attribute names are prefixed with the name of theprocess models that define them (except in the case of the root process).

Model attributes have a scope that is local to each QP. That is, for each QP thatuses a process model, private copies of the process model’s attribute are created forthe QP and appended to its attribute list. They appear together with the QPs built-inattributes and can be treated in an identical manner. Changes to the attribute in oneQP have no effect on the same attributes in any other QP.

OPNET also provides process models with a globally scoped attributemechanism. These attributes, called simulation attributes, are declared by eachprocess model that requires them. Unlike process model attributes, simulationattributes are read-only. Their purpose is to provide a parameterization mechanismat the system level, rather than at the level of system building blocks. In otherwords, if the designer of a process model wishes to create a parameter which is tobe shared by many entities in the system model, it can declare a correspondingsimulation attribute. If multiple process models declare the same simulationattribute (i.e., using identical names), OPNET will detect this and create only oneattribute which is implicitly shared by all the process models. Simulation attributevalues can be set at simulation run time to complete the specification of the systemmodel. Different values may be specified for each new simulation, providing amechanism for automatically iterating the system model through a series ofexperiments.

Declaration of simulation attributes is performed using the edit simulationattributes operation, which is described in detail in the Editor Referencemanual. When processes wish to obtain the value of a simulation attribute, theymust call the KP op_ima_sim_attr_get() and refer to the attribute using theappropriate declared name. If the simulation attribute’s value has not yet beenspecified as part of the simulation’s environment attributes, thenop_ima_sim_attr_get() will cause the Simulation Kernel to prompt for anassignment from the user. Since simulation attribute values do not change once asimulation starts, processes usually obtain these values once and store them in statevariables if they need to use them again at a later time. Refer to the SimulationKernel manual for more information.

Since simulation attributes, and attributes in general, are essentially “inputs” tothe system model and the simulation, they are often of interest to record as part ofa simulation’s output file. This allows the simulation “inputs” and “output” (i.e.,recorded statistics) to be viewed together and dependences between them to beanalyzed. OPNET provides a special probe, called an attribute probe, for this

Page 21: 03 Process Domain

193-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

purpose. Attribute probes record attribute values as scalar statistics. Refer to theSimulation Design chapter of this manual for more information on attribute probes.

Prdef.2.2 Process Model Components

Process models are specifications for the dynamic behavior of processes. To becomplete, a process model must describe the actions that a process will implementunder all circumstances that it will potentially encounter. In many cases, processesthat are executing within OPNET simulations represent a real-world equivalentprotocol or algorithm; the formal specification of such a protocol or algorithm is ahigher-level specification that stipulates the requirements that must be met by aprocess implementation in order to be used in a standardized fashion. Todifferentiate such a specification from a model specification developed in OPNET,the formal specification will be referred to as a standard. In other words, astandard describes the requirements that apply to real world processes, andtherefore also to the models of those processes. Some examples of standards arethe IEEE 802 local area network protocol standards, or the RFC documents for theTCP/IP protocol suite. The academic description of an algorithm such as Bellman-Ford Routing would also be considered a standard according to this definition. Infact, any set of requirements that apply to the actions and interactions of a processcan be called a standard for the implementations of that process.

OPNET process models are developed to represent real-world existing orplanned systems and therefore may at some level be considered to beimplementations, or partial implementations, of the same standards as their real-world counterparts. Strictly speaking, processes that are representing existing andknown real-world counterparts, are models of those implementations, rather thanimplementations of the standard. Thus, a good model of an existing real-worldprocess should replicate any flaws that the real-world process has relative to thestandard that it implements. This would allow it to predict behavior that resultsfrom the flaw.

In some cases, process models are developed to represent hypotheticalprocesses that could occur in the real world. The modeler may be interested, forexample in predicting the performance of a proposed protocol for which no real-world implementations may yet exist. In these cases, process models canthemselves be considered to be implementations of the standard from which theyare derived. Similarly, a process model may be developed to provide a genericimplementation of a standard for use as a basic library component. Such a processwould also be considered a direct implementation of a standard, since it is notpatterned off of any existing real-world implementations. Most example modelsprovided with OPNET that have to do with standards, such as X.25, Ethernet,ATM, TCP/IP, etc., fall into this category.

Regardless of whether a process model strives to represent a real-worldimplementation or a standard, the actions that it is required to implement and thetiming that underlies these actions may be quite complex and may varysignificantly from application to application. Thus, if a single representationconvention, or language, is used to define all such process models, it must be

Page 22: 03 Process Domain

194-Prdef

Process Model Operation Modeling Concepts

extremely versatile. Currently OPNET supports one language for developingmodels of processes. This language, called Proto-C, is supported by the ProcessEditor which is integrated into the OPNET application. Proto-C provides apowerful and efficient method for describing the behavior of discrete eventsystems; it offers the following major features:

• Based on state transition diagrams (STDs): also referred to as finitestate machines (FSMs). This is the prevailing description method fordiscrete-event systems that maintain state information (i.e., informationaccumulated over the past). It is used in specifying and developing awide range of software and hardware systems because of its simplicity,its propensity for intuitive graphical representation, and its ability to ef-fectively break down complexity.

• Combined graphical/textual representation: Proto-C process modelsdepict state-transitions in a graphical format to support visualization oftop-level control flow. However, because graphical representationsgenerally do not efficiently or intuitively describe detailed actions ordecision-making, Proto-C supports textual specifications of these as-pects of a process. Textual specification occurs within the states and onthe transitions of the diagram and is based on a powerful library of sim-ulation and distributed-system related procedures, described in the Sim-ulation Kernel manual. In addition, the full general computationalcapability of the C and C++ languages is retained by Proto-C in orderto guarantee sufficient flexibility for all discrete-event applications.

• Ability to represent general state information: the state informationof a process is the set of data that has been generated by or provided tothe process, and that the process has decided to retain. Traditional state-transition diagrams represent the complete state of a system by identi-fying which of a limited set of states is occupied at any given time; thisis impractical for systems with complex state, and insufficient for sys-tems with dynamically expanding state. Proto-C therefore uses state oc-cupancy representation only to represent high-level modes of a system,and provides a more powerful mechanism to describe general state in-formation. Models may declare any amount of state information asvariables whose datatypes are provided by OPNET, the C and C++ lan-guages, or custom definitions. The state variables may be given generalnames and referenced symbolically throughout the process model. Inaddition, variables can be assigned to dynamically allocated memory inorder to store state information that grows over time.

• Dynamic process creation: processes may be created dynamically topartition interrupt handling or to provide additional independent con-texts as new tasks arise.

Page 23: 03 Process Domain

195-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

• Efficient execution: Proto-C diagrams and the logic contained withinare translated to the C and C++ languages with minimal overhead, al-lowing them to execute extremely efficiently. In particular, state infor-mation access, and control-flow statements (e.g., if statements withconditional clauses, and for loops that sequence through multiple op-erations) are implemented in a direct manner to avoid any loss of per-formance.

Prdef.2.2.1 State Transition Diagrams

Proto-C models consist of two basic component types: states and transitions,hence the name state transition diagram (STD). States are generally used torepresent the top-level modes that a process can enter. Transitions specify thechanges in state that are possible for the process. STDs are graphically depicted inthe Process Editor.

There are other important aspects of Proto-C process models that are notrepresented graphically. These include actions associated with each state, variableand attribute declarations, and common definitions of expressions and functions.This section provides detailed information on the capabilities and applications ofthese features.

Forced and Unforced States

In a general sense the word state refers to the information that a process mayhave accumulated over the time that it has existed. The process’ state may notinclude all information to which the process has had access, but only that which ithas chosen to retain. State information may be continually updated as new eventsoccur and data becomes available. In terms of a state transition diagram (STD), theword state refers to an object that corresponds to one of the primary modes orsituations that a process may find itself in. States are mutually exclusive andcomplementary, meaning that a process is always in exactly one state: more thanone state may never be occupied at a time. The process can move between states inresponse to the interrupts that it receives. The transitions that depart from a stateindicate which states may be occupied next, and the condition that each changerequires.

Specifications of actions may be associated with each Proto-C state. In Proto-Cterminology, actions are called executives. The executives of a state are split intotwo sections, called enter executives and exit executives. As the names indicate, astate’s enter executives are executed when a process enters the state, and its exitexecutives are executed when the process leaves to follow one of the outgoingtransitions.

Proto-C defines two types of states, called forced and unforced, that differ inexecution-timing. In Proto-C diagrams, forced states are graphically represented asgreen circles, and unforced states are drawn as red circles. On monochromedisplays and hard copy, forced states are dark and unforced states are light.

Page 24: 03 Process Domain

196-Prdef

Process Model Operation Modeling Concepts

Unforced states allow a pause between the enter executives and exit executives,and thus can model true states of a system. Once a process has completed the enterexecutives of an unforced state, it blocks and returns control to the previouscontext that invoked it. This context may be another process that invoked this oneby calling the KP op_pro_invoke(); or if the process was invoked by the SimulationKernel, blocking signifies the end of the current event and the Kernel may select anew event in order to begin its execution. At this point, the process remainssuspended until a new invocation causes it to progress into the exit executives of itscurrent state. The following diagram depicts the flow of execution through theunforced states of an STD as interrupts cause the process to advance.

Graphical Representation of Forced States and Unforced States

Forced StateUnforced State(Red on color display) (Green on color display)

Page 25: 03 Process Domain

197-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

The diagram clearly shows the starting and stopping points of a process’invocation. In all cases (except the initial invocation), when a process is invoked, itis poised to begin executing the exit executives of its current state. It thenprogresses until it completes the enter executives of an unforced state where itagain blocks. Therefore if only unforced states are involved, the cycle is as follows:

Execution Flow through Unforced States

Blocked(waiting for invocation)

Enter Executives

Exit Executives

Blocked(waiting for interrupt)

Enter Executives

Exit Executives

Blocked(waiting for interrupt)

Enter Executives

Exit Executives

Once an invocation occurs, the process executes the exit executives and pro-ceeds immediately to the next state to also complete the enter executives there, and then blocks again. These actions comprise a complete process invoca-tion and require no time delay.

The process completes the enter executives immediately upon entering an unforced state and then blocks until a new invocation occurs.

Transitions guide the process to a new state or possibly back to the same one, depending upon the applicability of their condi-tions.

start of invocation

end of invocation

end of invocation

start of invocation

Page 26: 03 Process Domain

198-Prdef

Process Model Operation Modeling Concepts

1) exit executives of current state

2) transition to next state

3) enter executives of next state

Forced states are so called because they do not allow the process to wait. Theytherefore cannot be used to represent modes of the system that persist for anyduration. In other words, the exit executives of a forced state are executed by aprocess immediately upon completion of the enter executives. Therefore the exitexecutives of a forced state are generally left blank, since they are equivalent to thesame statements placed at the end of the enter executives. Because forced statescannot represent actual system states, they are not generally used as much asunforced states. However they are useful in certain cases to graphically separateactions or control flow decisions that are common to several unforced states;graphically separating out definitions of decisions and/or actions in this mannercan sometimes provide better modularity of specification, as well a more visuallyinformative state transition diagram.

The introduction of forced states causes only a minor adjustment in theexecution flow depicted in the above diagram. Unforced states still represent thestarting and stopping points of invocations; however any number of forced statesmay be traversed between them. This is illustrated in the following figure.

Initial State

One special state, called the initial state, must be designated in each processmodel. An existing state may be assigned this role at any time by using the setinitial state operation of the Process Editor. Graphically, the initial state isidentified by a large arrow located at its immediate left, as shown below:

Execution Flow through Combination of Unforced and Forced States

Invocation starts at topof exit executives ofunforced state

Any number of forced states may betraversed between unforced statesduring an invocation

Invocation ends at bot-tom of enter executivesof unforced state

Page 27: 03 Process Domain

199-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

The initial state is the point at which execution begins on the first invocation ofthe process. It has no special significance for any subsequent invocations, and mayotherwise play the role of a normal state. However, since this state usually containsexecutive statements performing initializations that should occur only once, mostmodels do not include transitions that lead back to it.

Upon receipt of the first interrupt, entry into the initial state takes place at thebeginning of the enter executives. Some models devote this state only toinitialization actions, and expect that a begin simulation interrupt will be providedexclusively for the purpose of completing these actions at time zero. The issue ofwhether or not such an interrupt is expected and the related issue of whether theinitial state should be forced or unforced must be treated carefully to avoidmishandling the first interrupt. There are several possible approaches, which arediscussed in this section. In describing these approaches, interrupts other thanbegin simulation interrupts are referred to as mainstream interrupts.

1) The initial state is forced, and a begin simulation interrupt is expect-ed. Since the initial state is forced, the process necessarily proceeds toa second state as soon as initializations are complete. The enter execu-tives of this second state must not perform actions related to the pro-cessing of mainstream interrupts since these actions would be(incorrectly) executed at initialization. Typically, the second state is anunforced state that acts as a “ready” position for the process to handlesubsequent mainstream interrupts. This approach makes sense for caseswhere the first unforced state entered after initialization is also reen-tered for later mainstream processing. Were this not the case, the initialand second state could simply be collapsed into one unforced initialstate.

arrow indicating the initialstate

Graphical Representation of Initial State

Page 28: 03 Process Domain

200-Prdef

Process Model Operation Modeling Concepts

2) The initial state is forced, and a begin simulation interrupt is not ex-pected: As in the previous case, the process will proceed to a secondstate immediately after the initial state has completed; however, sincethe initial interrupt is a mainstream interrupt, it is correct to process thisinterrupt by performing additional actions. Thus, the conditional transi-tions out of the initial state may guide the process into several possiblesecond states, where processing of the interrupt can take place. Notethat the limitation presented by this scheme is that initializations are notperformed until the first mainstream interrupt occurs, which may bewell after time zero.

3) The initial state is unforced, and a begin simulation interrupt is ex-pected: In this configuration, initialization statements placed in the en-ter executives will complete at time zero, after which the process willblock until the arrival of the first mainstream interrupt. Therefore theexit executives of the initial state should be appropriately specified forhandling of a mainstream interrupt; they may simply be empty in whichcase the interrupt handling code must be in the enter executives of thestate that follows or in the transition executives. Like the previous ap-

Initialization Strategy 1: Forced Initial State / Begin Sim. Interrupt

no initialization code here

process flow eventu-ally returns to firstunforced state

all initializations here

other general mainstream processing

Initialization Strategy 2: Forced Initial State / No Begin Sim. Interrupt

no initialization code hereinitial invocation can leadto several states

all initializations here

other general mainstream processing

Page 29: 03 Process Domain

201-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

proach, this organization makes sense when the first mainstream inter-rupt may lead the process into several different states; however notethat it accomplishes initialization at time zero, rather than waiting for amainstream interrupt. Note also, that this approach is usually not appro-priate if the initial state is to be reentered during processing of latermainstream interrupts, since the initialization statements in the enterexecutives would be executed repeatedly.

4) The initial state is unforced, and a begin simulation interrupt is notexpected: This is an unusual approach since it requires a mainstreaminterrupt to perform initializations, and yet has the process block with-out proceeding on to other states. Thus, any processing associated withthe first mainstream interrupt must be embedded in the enter executivesof the initial state; if this processing is generic and appears elsewhere inthe model (i.e, for steady-state processing of the same sort of interrupt),then it may need to be redundantly specified.

Note that begin simulation interrupts are controlled within the node domain byassigning the appropriate value to the begsim intrpt attribute of processor andqueue modules. Also, begin simulation interrupts cannot be enabled fordynamically created processes (i.e., the begsim intrpt attribute applies only tothe root process of a QP); however, their effect can be emulated for such processesby having the parent process perform an invocation via op_pro_invoke()immediately after creation via op_pro_create(). Thus the above approaches toorganizing a process’ initialization stages is applicable to dynamic processes aswell.

Improper configuration of the initialization stages can result in serious logicalerrors for a process. In particular, if a process that expects a begin simulationinterrupt (or equivalent invocation) does not receive it (e.g., because the begsimintrpt attribute is not enabled), it may misinterpret the first mainstream interruptas the interrupt it expected. Typically in such cases, initialization is still performed

Initialization Strategy 3: Unforced Initial State / Begin Sim. Interrupt

first mainstream interrupt canlead to several states

all initializations here

other general mainstream processingat time zero

Page 30: 03 Process Domain

202-Prdef

Process Model Operation Modeling Concepts

correctly since the process simply assumes it has received the expected indicationto perform initializations. However, the mainstream interrupt is likely to beignored by the process, which can lead to loss of critical information and/oromission of critical early actions that should have been taken by the process.

One particular example of this problem occurs when the first mainstreaminterrupt that occurs is a stream interrupt, indicating the arrival of a packet at oneof the QPs input streams. If the process assumes a begin simulation interrupt hasoccurred instead, the arriving packet is likely to be ignored and will remain in theinput stream. Subsequent stream interrupts that are correctly interpreted will causethe process to try to acquire the arriving packets from the input stream; howeverthe ignored packet will be obtained instead, since streams queue packets in a first-in-first-out order. Thus, models that exhibit this error can be identified by a “shift”in the packet processing. Paradoxically, one of the effects of this shift is thatprocesses that receive packets infrequently tend to forward them with greaterdelay, since each packet must wait for the following one to trigger its processing;this behavior is counterintuitive for some simulation studies that measurecumulative delay of packets through a system, since in general less frequentarrivals correspond to a lightly loaded system, which in turn implies lower delaythrough the system.

Transitions

Transitions describe the possible movement of a process from state to state andthe conditions under which such changes may take place. There are fourcomponents to a transition’s specification: a source state, a destination state, acondition expression, and an executive expression. The specification may be readas follows: when in the source state, if the condition is true, implement theexecutive expression and transfer control to the destination state.

In the Process Editor, transitions are specified graphically. Each state may haveany number of outgoing and incoming transitions depicted as directed arcs with thearrow pointing toward the destination state. The condition and executiveexpressions appear in a combined label next to the arc. The tool always places thecondition expression within parentheses and precedes the executive expression bya forward slash (‘/’) to separate the two components. Transitions that have non-empty condition expressions are depicted as dashed arcs; those without conditionsare depicted as solid arcs, as shown in the following diagram.

Page 31: 03 Process Domain

203-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

A transition’s condition is evaluated as a boolean expression in order to decidewhether or not the process should enter the transition’s destination state. A processevaluates outgoing transitions once the exit executive statements of the source statehave completed. For forced states, enter and exit executives are executed inimmediate succession, and so both executive blocks and the transition evaluationcan be viewed as a single logical series of actions (although exit executives areusually empty for forced states). For unforced states, a pause occurs between theenter and exit executives, and so only the latter can be grouped with the transitions.

Transition condition expressions may be complex combinations of criteria thatinvolve state variables of the process, attributes of the current interrupt, and otherinformation stored in shared or global memory. It is also possible for conditions tobe based on computations of any complexity by calling a user-defined procedurethat returns a boolean value (typically, such a procedure would be placed in thefunction block of the process model). Alternatively, computations that supportcondition expressions may be placed at the end of the exit executives of atransition’s source state, since these are executed immediately before theconditions are evaluated.

All transitions that depart from a state are evaluated before a process mayprogress to any transition destination. This allows the detection of two types oferrors and assures that behavior is independent of the order in which the transitionconditions are evaluated. If none of the conditions have a TRUE value (a nonzerovalue as a C or C++ language expression), then an error message to this effect willbe generated by the process, since it is impossible for it to continue execution.Similarly, if more than one transition condition has a TRUE value, an error messagewill be issued. Both of these errors are considered sufficiently serious to cause thesimulation to halt. It is therefore important that the transitions that emanate from astate should collectively be mutually exclusive at the time they are evaluated (notwo can simultaneously be true), and complementary (at least one is necessarilytrue). The following equivalence between an STD fragment and a pseudo-codefragment illustrates the logic that is applied in order to evaluate multiple outgoingtransitions.

non-empty conditions appear as dashed arcs

empty conditions appear as solid arcs

Representation of Transitions

transitions can return to same state

Page 32: 03 Process Domain

204-Prdef

Process Model Operation Modeling Concepts

A special condition called default is provided to represent the complement ofthe conditions associated with the defined transitions leaving a state. Each stateshould have at most one outgoing default transition. This is a useful mechanism torepresent complementary conditions when they are complex, and ensures that theprocess will not encounter an error at the state of interest due to a missing TRUEtransition. Default transitions succeed only if all other transitions conditions arefalse, as shown by the pseudo-code example below:

As a final note on condition expressions, transitions that are configured with anempty condition attribute are equivalent to transitions whose conditions alwaysevaluate true. These are referred to as unconditional transitions. It follows from theprevious discussion that if a state has an unconditional transition departing from it,that it may support no other outgoing transitions.

if (PACKET_IS_DATA)jump_to_state (S1)

else if (PACKET_IS_ACK)jump_to_state (S2)

else error (NO_TRUE_TRANSITION)

Pseudo-Code Equivalent of Multiple Transition Configuration

if (PACKET_IS_DATA)jump_to_state (S1)

else if (PACKET_IS_ACK)jump_to_state (S2)

else jump_to_state (S3)

Pseudo-Code Equivalent ofMultiple Transition Configuration with Default

Page 33: 03 Process Domain

205-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

Each transition incorporates an attribute that supports the specification of anexecutive statement. A transition’s executive is carried out at the time that aprocess decides to traverse the transition. In other words, once all outgoingtransitions have been evaluated, the process selects one of them, implements itsexecutive statement if there is one, and advances to the enter executives of itsdestination state. This sequence is described below in the form of pseudo-code fora simple pair of transitions.

Transition executives are useful in order to associate an action with a state, butonly when it is entered or exited for a particular reason. Actually incorporating theaction into the state’s enter or exit executives instead would cause it to be executedregardless of the reason for which the state was entered/exited, which may beundesirable in some cases.

Prdef.2.2.2 Using Macros to Define Complex or Recurring Expressions

In the examples above, condition and executive expressions consist only of“English-like” text, and at first sight do not appear as C language programmaticexpressions. The technique used in these examples, and typically used in mostprocess models, is to define macros whose names represent underlyingexpressions. Proto-C simply “passes through” the macro definition capability ofthe C language to support this practice.

Almost all macros used by a Proto-C model are defined in its header block. Theheader block is a free-form area for C or C++ language code, similar to the topportion of a C or C++ file. Macros are generally used to represent constants,transition conditions, transition executives, or commonly performed operations.

Macros defined directly within the header block begin with the #define C andC++ preprocessor directive. Macros may also be defined in external definitions

Pseudo-Code Equivalent of Transitions with Executives

if (QUEUE_EMPTY){SET_TIMERjump_to_state (S1)}

else if (QUEUE_NOT_EMPTY){SEND_ONE_PACKETjump_to_state (S2)}

else error (NO_TRUE_TRANSITION)

Page 34: 03 Process Domain

206-Prdef

Process Model Operation Modeling Concepts

files (files with a “.h” suffix in C and C++) and included through the header blockby using the #include preprocessor directive. The external file inclusion methodis useful when multiple process models must share a consistent set of definitions;this avoids having to enter and maintain identical definitions in each process’header block. The following header block fragment provides an example of typicalProto-C macro definitions.

Page 35: 03 Process Domain

207-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

conditional and executiveexpressions for transitionsare defined in header block

Macro Definitions within Process Model Header Block

Page 36: 03 Process Domain

208-Prdef

Process Model Operation Modeling Concepts

Prdef.2.2.3 Variables

Proto-C processes have access to several forms of memory to storeinformation. Each form of memory has different properties that make itappropriate for particular uses. Some of these memory forms allow information tobe declared and manipulated directly as ordinary names; these forms of storage arereferred to as variables. Proto-C processes can make use of three distinct categoriesof variables called state variables, temporary variables, and global variables. Thefollowing table shows these types of variables and the sections of code where theycan be accessed.

Variable Components

All variables, regardless of their category, have a name, a datatype, and a value.The name and datatype of a variable remain fixed throughout the life of a process;the value component is the only one that may change.

• Name: unlike attributes, variables can be accessed without the use ofany Kernel Procedures. Instead, an ordinary reference to a variable’sname implicitly signifies a reference to its value. Variable names aredefined as part of a mechanism called declaration; each of the threevariable categories uses a slightly different declaration mechanism inorder to indicate to the process compiler what category applies. Thenames that are selected can be general alphanumeric character sequenc-es respecting the following rules:

Type of Variable Visibility

State executives Functions in function block

Functions in external files (.ex.c files)

temporary X

state X X

global (as defined in external header files or in the Header Block)

X X X(as long as “extern”

is used)

Page 37: 03 Process Domain

209-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

• Datatype: the datatype of a variable specifies the kind of informationthat it is capable of storing. OPNET provides a number of specialdatatypes that are predefined for common modeling purposes. Some ofthe essential datatypes are summarized in the following table. Refer tothe Simulation Kernel manual for a complete listing of predefineddatatypes and their usage.

Rules for Variable Naming

Names must consist of alphanumeric characters only; the underscore char-acter (‘_’) is also allowed. Both upper and lower case are acceptable and are considered distinct.

Names must begin with letter characters (i.e., not numbers or ‘_’).

Each name must be used in only one declaration (i.e., the same variable name should not be used for more than one of the variable categories in a given process).

Essential OPNET Predefined Datatypes for Variables

Datatype Description

Distribution Loaded Probability Density Function.

Evhandle Handle providing access to a scheduled event (e.g., supports cancellation).

Ici Group of attributes used to associate additional user-defined information with an event.

Objid Unique identifier of a simulation object; used in most operations on objects.

Packet Structured group of data fields representing a mes-sage that can flow over packet streams (node domain) and over links (network domain).

Compcode Status value returned by many kernel procedures to indicate success or failure.

List Linked list construct provided by the Prg package of KPs. Useful for managing lists of general user-defined data structures.

Stathandle Handle provided when a local or global statistic is reg-istered. Used to write updated values to the statistic.

Page 38: 03 Process Domain

210-Prdef

Process Model Operation Modeling Concepts

In addition, Proto-C provides completely general data storage by sup-porting datatypes from the C and C++ languages. This includes not onlybuilt-in C and C++ datatypes such as int, double, and char, but alsoarrays and complex data structures formed from any combination ofother datatypes.

Custom data types are usually specified in the header block of a processor in an external definitions file that is included via a #include state-ment in the header block. In general the C typedef and struct mech-anisms are used as shown in the examples below. Consult a C or C++language reference for complete information on the use of these con-structs.

Variables are declared in slightly different formats depending upon theircategory, and each particular declaration mechanism will be explained in thesections on each category in this chapter. However, in all cases, declarationrequires that the data type and name of a variable be specified. Additionally, avariable may be modified so that it is actually an array of one or more dimensionsof its particular data type. In general, the declaration format is as follows:

• Value: this term refers to the actual contents of the memory that is as-sociated with a variable. For simple variables this may be an individual

Definition of Custom Datatypes in Header Block

User-defined structurescan include OPNET pre-defined datatypes

Evhandletimer_handle_table[10];

(Datatype)(Name)(optional

array dimension)

Page 39: 03 Process Domain

211-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

number or string of characters; for compound data structures many suchitems could be involved. The specific nature and organization of a vari-able’s contents are specified by its datatype. These contents maychange over time in order to store new or updated information, as re-quires by the process model, hence the name variable.

Operations on Variables

Proto-C variable values are manipulated within the condition and executivestatements of states and transitions. The basic operations that can be performed ona variable, regardless of its type, are to obtain its value or to modify its value. Notethat the datatype and name of a variable are immutable.

Depending on how a variable name is used in a statement, its value can eitherbe obtained or modified. In general, all variable manipulations follow theconventions of the C language; most C textbooks should therefore provide in-depthcoverage of this topic. Briefly, there are two basic forms that support modificationof a variable value. The first, and most common is an assignment using the equals(‘=’) operator, several examples of which are shown below:

A second method of assignment is designed to allow a procedure to modify avariable’s value rather than modifying it in the local context. This is accomplishedby informing the procedure of the memory location at which the variable’s value isstored. Thus, the procedure can modify the contents of the memory locations andupon returning, the assignment has already been performed. A number of KernelProcedures use such an interface in order to support modification of multiplevariables in a single call (C and C++ functions cannot otherwise return multiplevalues), or to compute results of several different data types. In the C and C++languages, the memory location of a variable’s value is obtained by applying the &operator to the variable’s name, as shown in the following examples.

Assignment of Variable Values with the ‘=’ Operator

time = op_sim_time();

next_trans_time = time + packet_size / data_rate;

num_bits_sent += packet_size;

num_packets++;

assignment from return value of a procedure

assignment from expression combining othervariables

shorthand notation “var = var + increment”

shorthand notation “var = var + 1”

Page 40: 03 Process Domain

212-Prdef

Process Model Operation Modeling Concepts

Obtaining the value of a variable is very simple, since a variable’s nameactually is a symbol representing its value. In other words, by simply mentioning avariable, the C/C++ language automatically substitutes its current value in thesurrounding expression. Note however, that this is true also for modification of avariable using the = operator, as shown above. What differentiates an assignmentfrom an obtainment has therefore more to do with the placement of the variablenames relative to the operators in an expression. When the = operator is used, thevariable value on the left side of the operator is modified, whereas variable valueson the right side are simply obtained (that is, their current values are substituted inthe locations where their names appear).

Other commonly performed operations on Proto-C variables includecomparison operators such as == (is equal to), != (not equal to), > (greater than), <(less than), >= (greater than or equal to), <= (less than or equal to). Note thedifference between the equality test operator which has two side by side ‘=’characters and the assignment operator represented by just one such character. Theconfusion between the two is a source of common errors in process behavior.

In addition, arithmetic operations such as +, -, *, and / are supported, as are allother C/C++ language features. Once again, please refer to a C or C++ languagereference for an in-depth treatment of these and other operators.

State Variables

Variables that are used to represent the information accumulated and retainedby a process are referred to as state variables. This name is due to the fact thatthese variables, together with the current position of a process within its statetransition diagram, represent the complete state of a process at any time. Note thatprocesses may generate or have access to much information over time that does notbecome encoded into their state; therefore state refers only to the information thatthe process itself decides to retain by recording it into state variables.

State variables are declared in a dedicated area of a Proto-C model, referred toas the state variable block. New state variables can be declared, or old ones

Assignment of Variable Values by Passing Addresses to Procedures

op_pk_nfd_get (pk, “type”, &pk_type);op_pk_nfd_get (pk, “start_time”,

&time_sent);

op_ima_obj_pos_get (objid, &la, &lo,&al, &x, &y, &z);

op_ici_format (ici_ptr, format_name);

same procedure assigns variables of severaldifferent datatypes.

single procedure call modifies multiple variables(six in this case).

arrays (such as strings which are character arrays)do not require ‘&’ operator since their variablenames already refer to their memory location.

Page 41: 03 Process Domain

213-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

modified by choosing State Variables from the Code Blocks menu of the ProcessEditor. For details on using this operation, refer to section Pr.6.4 State Variables inthe Editor Reference manual.

State variables are persistent, meaning that from the perspective of eachprocess, they retain their value over time. They can only be modified by explicitassignment statements that are executed by the process itself. This implies that thevalues of the state variables of a process are “frozen” when it blocks (i.e., haltsexecution after completing the enter executives of an unforced state), and foundunchanged by the process when it resumes execution at its next invocation (notethat, although it is rarely used, the KP op_ima_obj_svar_get() allows thistraditional property of state variables to be altered).

An important property of state variables that is necessary for persistence is thatthey are maintained in a manner that is private for each process. This means thatindividual instances of the same process model, even if they exist within the samequeue or processor, are able to independently store information in their variableswithout conflict, even while referring to them with the same names. In other words,changes made to state variables in one process do not affect the values of variablesheld by another.

State variables have no particular initial values when a process is invoked forthe first time. Since these variables constitute part of the state of a process, it is theresponsibility of the process itself to assign consistent initial values to them duringthe first invocation. In fact, this is usually one of the principal activities conductedin the executive statements of the initial state. Note that in contrast to temporaryand global variables, it is not possible to incorporate an automatic initialization ofstate variables into their declaration.

An important warning applies when selecting names for state variables due tothe underlying method by which they are implemented. Although state variablenames can be general, it is important to avoid naming conflicts with symbols usedelsewhere in the process model. In particular, temporary and global variables,function names, function argument names, structure fields, and local variables offunctions that appear elsewhere in the model must not be identical to the namesused for state variables, or compilation errors will occur.

Temporary Variables

A process may declare temporary variables in order to store information thatdoes not require persistence. Temporary variables are not guaranteed to have anyparticular set of values when a process model is invoked. In particular, the valuesthat were assigned to these variables by the same process during its previousinvocation may have been changed.

Since they have no persistence, temporary variables are useful only as“scratch” storage to facilitate computation of complex expressions or to holdinformation within the time frame of a single process invocation. For example, aninteger variable used as the index of a loop would generally be a temporary

Page 42: 03 Process Domain

214-Prdef

Process Model Operation Modeling Concepts

variable; a packet that is obtained, examined, modified, and sent again all in oneinvocation, would also be a temporary variable. In order to decide if a processmodel should declare a variable under the state or temporary category, thedeveloper should determine if there are cases in which the variable needs to retainits value from one invocation to the next. If this is the case, then a state variablemust be used; otherwise a temporary variable may be used. If there is doubtconcerning a variable’s declaration, state variables may always safely be used; notehowever that a state variable requires a memory allocation of corresponding sizethat will last as long as the process exists, whereas a temporary variable requires noadditional memory.

Temporary variables are declared in an editor pad that appears as a result ofusing the edit temporary variables operation. An example of temporaryvariable declarations appears below. Declaration of any predefined C/C++ andOPNET datatypes as well as user-defined datatypes is possible. Note that thebackslash character (‘\’) does not precede the variable name as it does in the caseof state variables.

Automatic initialization of temporary variables is possible by incorporating anassignment into the declaration, as shown in the example below. This initializationtakes place each time that a process is invoked.

Global Variables

Global variables provide a means for multiple processes in different modules,including processes of different types, to store information in a common location.This is a feature provided directly by the C and C++ languages, which also refersto these types of variables as globals.

Temporary Variable Declarations

automatic initializationmay be part of declaration

Page 43: 03 Process Domain

215-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

Global variables may make use of any C or OPNET predefined datatype aswell as custom datatypes. Declarations should be entered into a process model’sheader block via the edit header block operation of the Process Editor. Eachglobal variable should have one principal declaration within the header block ofthe process model with which it is most closely associated. If other process modelsalso share access to the variable, their header blocks must include an externaldeclaration. There may be any number of process models with externaldeclarations to a global variable, but only one should include a principaldeclaration. External declarations are identified by the keyword extern, as shownbelow.

Declaration of Global Variables in Two Process Header Blocks

principal declarations ofglobal variables are withone process

other processes mustuse external form ofglobal declaration

Page 44: 03 Process Domain

216-Prdef

Process Model Operation Modeling Concepts

As with temporary variables, global variable initializations can be performedby making assignments within the declaration statements. This is possible onlywithin the principal declaration. Initialization takes place before the simulationbegins. Additional initializations of globals that are a function of simulation inputor model configuration are generally performed by designated processes duringtheir initial invocations.

Note that global variables should be used with care since their use createsdependencies among processes. In other words, when a process modifies a globalvariable, the change may have an impact on the operation of other processes. Inaddition, global variables that are shared across physical boundaries (e.g, across anentire network model) do not always correspond to realistic representations ofactual systems. The same data that can be represented by globals in an OPNETmodel might be implemented as distributed storage in an actual system; or ifcentralized storage is used, delays would be incurred when accessing the data. Themodel developer must make a judgement regarding the appropriateness of theglobal variable approach and possibly make corrections for unrealistic effects itintroduces.

Prdef.2.2.4 Process Model Attributes

Process model designers frequently specify characteristics of a process thatrequire the flexibility to adapt to a variety of situations. For example,communication protocols may provide various options to their users, such as time-out durations, maximum number of retransmissions, window sizes, etc. Similarly,a computer operating system model may offer multiple alternatives for virtualmemory size, maximum number of concurrent tasks, etc. Rather than designsimilar process models that differ in just these features, it is preferable to designparameterized process models. Those characteristics of the process that requirevariability can be viewed as parameters of the model.

As discussed in the Modeling Framework chapter of this manual, OPNETprovides model attributes for the purpose of developing parameterized models.Process models are the models that typically make most use of this capability,since ultimately, it is user-defined code that must in some way interpret the valuesof customized attributes in order to implement variable behavior (in contrast, thevariable behavior of standard OPNET objects is configured via built-in attributes).It is often most appropriate to define the model attributes in the same model as thecode that uses them.

Model attributes can be declared for a process model by using the edit modelattributes operation of the Process Editor. Each model attribute is defined byspecifying a unique name, and properties. The properties allow control over theattribute’s default value, symbol map, numerical range if appropriate, and severalother characteristics. Refer to the Modeling Framework chapter of this manual formore information on model attributes and attribute properties.

Page 45: 03 Process Domain

217-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

.

During simulation, process model attributes appear simply as attributes ofqueues and processor modules. They may be accessed both to modify and to obtaintheir value by using the KPs op_ima_obj_attr_set() and op_ima_obj_attr_get(),respectively. However, in most cases, process model attributes are never changedduring the simulation but instead serve only as parameters that the process uses toconfigure itself when the simulation begins. Typically, each process that usesmodel attributes performs these configurations in its initial state, where it loads thevalues of attributes into a corresponding set of state variables. The state variablesare used thereafter since they are more convenient and efficient to access thanattributes. A typical example of model attribute loading appears below.

Process Model Attribute Declaration

Page 46: 03 Process Domain

218-Prdef

Process Model Operation Modeling Concepts

Attribute Interfaces

Each process maintains a set of attribute interfaces which is distinct from itsmodel attributes. As discussed in the Modeling Framework chapter, the attributeinterfaces contain attributes promoted from objects within the model, as well asspecifications for attributes of the object that will use the model. In the case of aprocess model, none of the objects within the model (e.g., states and transitions)are able to promote attributes, and the object that will use the model is a queue orprocessor. Therefore, the attribute interfaces consist simply of queue and processorattributes. By using the attribute interfaces, the process model developer canspecify in advance the values and properties of a queue or processor that will usethis model.

Loading of Process Model Attributesinto State Variables at Initialization

Page 47: 03 Process Domain

219-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

Process model attribute interfaces are frequently used to ensure that queues andprocessors are properly configured to act as hosts to a given process model. Ingeneral attributes that are not relevant to the process model are placed in thehidden status in order to simplify the QPs menu. In many cases, this includesattributes such as “intrpt interval”, “failure intrpts”, “recoveryintrpts”, “super priority”. The process model designer generally knowswhether or not the process requires a begin simulation interrupt and whether itsupports and end simulation interrupt; the “begsim intrpt” and “endsim

intrpt” attributes can be set accordingly and hidden.

Process model attribute interfaces also provide the capability to associatecomments with the process model in order to provide guidance and backgroundinformation to users of the process model. Refer to the Modeling Frameworkchapter of this manual for more information on model attribute interfaces.

Prdef.2.2.5 Modularizing Computations

Certain process models make recurring use of an identical computation insupport of a decision or action. Identical does not necessarily mean that the resultis always the same, simply that the form of the computation (i.e., the steps intowhich it can be decomposed) is invariant. However, the data that the computationmanipulates may change each time that it is executed. This data is called the inputof the computation and each individual data item that comprises the input isreferred to as a parameter of the computation.

Specification of Process Model Attribute Interfaces

Queue/Processor attributes whose values can be enforced by the process model developer are assigned a value and given the hidden status

Page 48: 03 Process Domain

220-Prdef

Process Model Operation Modeling Concepts

The most straightforward approach to realizing a process model that hasrecurring use of the same computation is to simply repeat the specification of thecomputation in detail at each location where it occurs (i.e., in various executiveblocks and on each transition that executes it). However, this approach presentsseveral significant disadvantages:

• It requires redundant entry, lengthening the time required to completea model’s specification.

• It requires redundant maintenance, meaning that if the computationneeds to be changed, in order to enhance or update the functionality ofthe model for example, then identical changes must be made in multipleparts of the process model.

• For complex computations, the size of the model may increase appre-ciably, in turn affecting the total memory requirements of a simulation.

• Process model logic is not streamlined, requiring someone studying theprocess model (e.g., to understand or upgrade its functionality) to ex-amine or verify significantly more statements.

There are two principal techniques used in Proto-C to streamline recurringspecification of identical computations. In both cases, the objective is toencapsulate the specification of the computation into a form that can be reusedwhenever the result of the computation is needed. Proto-C dynamic processes andC/C++ functions both support this modular computation approach since they cancontain general calculations that operate on variable inputs called arguments.Arguments are the parameters of a computation.

Modularizing Computations with Dynamic Processes

Dynamic processes are discussed in depth in earlier sections of this chapter, aswell as in the Modeling Framework chapter of this manual. A brief description oftheir use for modularizing a computation is presented here.

1) A dynamic process that contains all the logic of the computation of in-terest must be specified. This process should make use of argumentmemory obtained via the KP op_pro_argmem_access(), to representthe computation’s parameters. In addition, this process should be state-less; this means that it should define no state variables and include onlyone unforced state in order to assure that only the arguments of invoca-tion affect each outcome. In other words, there should be no internallyaccumulated information that can create dependencies between sepa-rate invocations.

Page 49: 03 Process Domain

221-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

2) A process requiring the computation to be performed on a recurring ba-sis creates a dynamic process of the appropriate type, by calling the KPop_pro_create() and retaining the process handle that is returned. Thismust be done at some time prior to the computation’s first use—usuallyin the parent process’ initial state.

3) Each time that the parent process requires the computation to be per-formed, it must set up appropriate argument memory and invoke thechild process using the KP op_pro_invoke() and the earlier obtainedprocess handle. If required, the child process may return results bymodifying the argument memory.

Modularizing recurring computations is not the main application of dynamicprocesses. Processes are primarily designed for modeling ongoing threads ofexecution. These threads normally have state memory and therefore do not behaveidentically on each invocation. However, the dynamic process approach outlinedabove is followed in some cases as an alternative to using C or C++ functions(described later in this section), because it allows graphical decomposition of acomputation's flow of control. Forced states represent simple actions, anddecisions about which actions should be performed are encoded in the transitionsbetween states. As shown below, representation of a computation in this mannerstrongly resembles the flowcharting approach used as a first step in somecomputer-program design methods.

Control Flow of Dynamic ProcessImplementing Modular Computation

The process always returns tothis state when computationcompletes. This is where thenext invocation will begin.

Multiple outgoing transitionsdepict the process’ decisions.

Page 50: 03 Process Domain

222-Prdef

Process Model Operation Modeling Concepts

Modularizing Computations with Function Calls

The most common and straightforward approach to modularizing recurringcomputations is to make use of the function call mechanism provided by the C andC++ languages. Functions (also referred to as procedures) are specifications ofcomputations that may accept parameters, referred to as arguments. Argumentsmay be of any datatype provided by C, C++, OPNET, or the user’s customdefinitions. Depending on the service that is required of them, functions mayprovide return values that result from their computations or simply perform aseries of actions and return no result. Please refer to a C or C++ reference text formore information on defining functions.

In Proto-C, any number of functions may be specified within a section calledthe function block of a process model. The function block’s contents can be editedby using the edit function block operation of the Process Editor. All normalsyntactic rules of the C/C++ programming language apply within this section ofthe model. However, note that the text that is entered in the function block willappear after that of the header block, allowing the use of data types and macrosthat are defined therein.

Each function represents a “package” of capability that the logic embeddedwithin the state transition diagram (STD) may call upon. This simplifies theappearance of the STD and allows it to exercise the same functionality in multiplecircumstances with minimal additional specifications. For example, an STD mayrequire the same exact series of actions to be applied to a packet while in differentstates and upon traversing several transitions; by implementing these actionswithin a function in the function block, the required logic can be developed onlyonce and invoked from each part of the model that requires its execution.

Functions specified within the function block are generally for the use of theprocess model that they are associated with. However, a function defined in thefunction block of one process may be called from the STD or even from thefunction block of another. However, this practice creates dependencies betweenprocess models such that the process that actually contains the function’s definitionmust always be present within a model that also includes the process that callsupon the function. If this rule is not followed, an error relating to the missingfunction will result when attempting to generate simulations.

A simple solution to the dependencies created by cross-calling of functions isto ensure that each process model is self-sufficient by incorporating all functioncalls that it requires within its own function block. However, two important caveatsapply to this technique: first, if a function appears in the function blocks ofmultiple process models, then it must have a different name in each one, or thefunction will be considered to be “multiply defined”, and a corresponding errorwill occur when attempting to create a simulation executable that includes theconflicting processes. One possible approach to avoiding this problem is to alwaysprefix the names of functions defined within the function block with the name ofthe process itself. For example, a function that schedules a timeout event for aprocess called X25 could be called x25_schedule_timeout. Second, redundantly

Page 51: 03 Process Domain

223-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

specifying capability by replicating a function in the function blocks of severalprocess models defeats one of the important purposes that suggests the use offunctions in the first place; namely, the redundant maintenance andsynchronization of the multiple instances can complicate development andmaintenance efforts and lead to inconsistencies among the versions.

External Object Files

As an alternative to this approach, the model developer may wish to considerdefining functions in external object files that are linked into the simulationexecutable. This allows each function to be developed and maintained in acentralized fashion and still be shared by all process models that require it. It does,however, create a dependency between the process models and the external filesthat contain the functions. This prevents the process model from being “stand-alone”, which can cause minor complications when sharing the model with otherusers, for example.

OPNET allows the user to specify those external object files that a modelrequires at two separate modeling levels. The list of external object files may bespecified as part of a network model if desired. However, this approach requiresthat the user have knowledge of the external files that are implicitly relied upon bythe node models that are present. This is not always possible or desirable,particularly when the network level user is not the same individual who developedthe embedded process models. This is particularly a problem for IT DecisionGuruand Modeler XE users, who merely manipulate node and link models and are notintended to have any knowledge concerning these models’ internal composition. Inorder to circumvent this problem, and also to provide a more solid associationbetween the external files and the code that relies upon them, OPNET allows eachprocess model to formally declare the external object files on which it depends.This can be done using the declare external object files operation of theProcess Editor, which is documented in the Editor Reference manual. Declaringexternal object files allows OPNET to automatically construct the list of externalfiles that are required to construct a complete simulation, thus providingtransparency to network-level users. Please also refer to the Simulation Designchapter of this manual for more information on external object files.

Declaring Functions

If functions return values that are not integers (i.e., are of datatypes other thanint), these functions should be declared prior to their use. If they are used withinthe STDs executive and condition statements, corresponding function declarationsshould be placed in the header block, to ensure that they appear in the proper order.The purpose of a function declaration is to inform the compiler what type of valuewill be returned. Declaration syntax is illustrated by the following example.

Page 52: 03 Process Domain

224-Prdef

Process Model Operation Modeling Concepts

Functions defined within the function block have access to variables on aslightly different basis than the process model with which they are associated.Global variables are available in an identical manner with declarations (eitherprincipal or external) required in the header block. Temporary variables of theprocess are not usable within the function block’s functions. However, eachfunction may of course declare its own local variables. State variables are availableto a function block function, but use of direct references to these variables willpreclude calls to the function from other processes. In other words, state variablesmay be accessed only if they belong to the associated process model (i.e., the onein which the function block is included) and in addition, that process model is theone currently executing. Misuse of state variables in the function block can lead tocomplex simulation errors and should therefore be considered very carefully. Asimple way to avoid this issue is to pass the values of state variables to a functionas arguments, rather than allowing it to access them directly; similarly, if a callingfunction would modify state variable values, then the state variables may be passedby address as arguments to the function, or assignments may be performed byhigher level code, once the function has returned.

Prdef.2.2.6 Diagnostic Capabilities

OPNET simulations automatically incorporate a sophisticated “debugger”called ODB that allows the user to interactively monitor the progress of asimulation and the state of its objects. ODB’s capabilities are exercised from a

Header-Block Declaration of Functions

no arguments necessary here

data types must agree

Page 53: 03 Process Domain

225-Prdef

Modeling Concepts Process Model OperationP

rocess D

om

ain

command line. Most of these capabilities are entirely provided by the SimulationKernel and require no customization on the part of the developer. However,because processes are user-defined and can store information in proprietary datastructures, and because the Simulation Kernel is not capable of knowing whichparticular information within a process is interesting to report, ODB provides twospecial commands that can be applied to processes. These commands, calledprodiag and proldiag, allow useful reports to be printed about the current stateof a user-defined process.

The prodiag and proldiag commands require an argument, which is theprocess ID of the process of interest. Process IDs can easily be obtained via thepromap command of ODB. Prodiag and proldiag then execute a series of user-provided statements that have been specified in a special section of the processmodel, called the diagnostic block. The diagnostic block of a process can bemodified by using the edit diagnostic block operation of the Process Editor.

Before executing the statements of a process’ diagnostic block, ODBtemporarily makes the process active, as if it has been invoked, so that KernelProcedures such as op_id_self() and op_pro_self() can be used. In addition, statevariables of the process may be accessed normally.

General Proto-C logic may be defined in the diagnostic block, although ingeneral, the statements of the diagnostic block are quite simple, since their purposeis simply to report the information that constitutes the state of the process. In somecases, for or while loops are required in order to report the contents of lists; ifstatements are also sometimes used to report only information relevant to a givensituation. An example of a process model’s diagnostic block appears below.

Page 54: 03 Process Domain

226-Prdef

Process Model Operation Modeling Concepts

Note from the example that the KPs op_prg_odb_print_major() andop_prg_odb_print_minor() are used to print information rather than the C libraryfunction printf(). These two KPs standardize the format of the information that isprinted in order to better integrate it with other output issued by ODB. The examplealso shows that the diagnostic block is not itself a function and therefore cannotdeclare local variables. However, it may make use of variables declared in theprocess model’s temporary variable section.

A more sophisticated version of the prodiag command, called proldiag, isalso provided by ODB. Proldiag differs from prodiag in that it temporarilyactivates a debugger label, which can be used to selectively perform operations inthe diagnostic block. For more information on this topic, please refer to ODBdocumentation in the External Interfaces manual and to the information providedon the KP op_prg_odb_ltrace_active() in the Simulation Kernel manual.

Typical Process Model Diagnostic Block

• state and temporary variables are accessed directly• code is entered directly—no function should be set up• no local variables are defined (use temporary variables instead)• supported KPs are used for printing

Page 55: 03 Process Domain

227-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3 Process Model Development Methodology

The previous sections of this chapter provide information about the capabilitiesof the Proto-C language and the specification features of the Process Editor. Itshould be clear from these sections that Proto-C provides a flexible platform thathas the ability to model a wide range of systems. The language provides specificsupport by adopting a state-transition approach which is well-suited to discreteevent systems, and by supplying a number of Kernel Procedures (KPs) that areoriented toward network and distributed systems modeling. At the same timehowever, Proto-C preserves generality by incorporating all the capabilities of theC/C++ programming language.

Due to the generality of Proto-C and the flexibility of the state-transitionparadigm, most systems can be accurately represented by many different Proto-Cmodels. The diversity of possible implementations results from the power of thetool but can also present some disadvantages; namely, the model designer mayexperience hesitation at the start of a model’s development effort, as the merits ofeach approach are considered. This is particularly true in the case of a beginningOPNET user. In addition, the models that a single developer creates over time mayvary in approach rather than converge on a single consistent style; this addsdifficulty to the future task of maintaining the models, particularly if differentdevelopers are involved.

In order to reduce problems related to the variability of potential approaches,this section provides a single development methodology that is applicable toprocess models of all types. The goal of the methodology is not to limit the extentto which Proto-C’s capabilities are used, but rather to lend structure to thedevelopment process so that the full set of capabilities are used in a consistent andappropriate manner. It is particularly recommended that beginning users followthis methodology in order to quickly advance to the point of developing complexmodels. Advanced users may wish to continue practicing this methodology so thatdevelopment becomes a consistent and therefore routine process.

Note that use of the methodology presented here is not mandatory; theinformation in the first part of this chapter is sufficient to serve as the basis fordevelopment of process models in Proto-C. This methodology presented here ismerely a suggested approach that developers may wish to consider.

Prdef.3.1 Description of Example Systems

Since this section of the chapter describes a methodology that applies toprocess model design in general, many of the procedures that are prescribed arestated in terms that may at times seem abstract. In order to give these procedures amore concrete form, several simple examples of processes will be used throughoutthe section.

Page 56: 03 Process Domain

228-Prdef

Process Model Development Methodology Modeling Concepts

Pay Telephone System

This example process is responsible for managing the usage of a simple coin-operated telephone. The process must respond to the actions of both the telephoneuser and the network to which it is connected. In particular, it is responsible for thefollowing:

1) Providing a dial tone to the user once a minimum amount of money hasbeen deposited and the network has acknowledged the request for useof the line.

2) Informing the network of the amount of money that has been deposited.

3) Relaying a dial tone signal from the network to the user.

4) Relaying the user’s phone numbers into the network if a dial tone hasbeen established (otherwise keystrokes are ignored).

5) Warning the user when money runs out and informing the user whenthey are finally disconnected (the network provides the process with anotification Warning_Time seconds before the user’s time has run out).

6) Returning money to the user if the network indicates the call is toll-freeor the user hangs up before the destination party answers.

The process resides in the telephone unit itself and therefore manages at mostone phone call at a time.

Automatic Bank Teller System

The process of interest manages the transactions requested by a single user viaa keypad. The supported transactions are deposits, withdrawals, and balanceverification. In all three cases, the user must insert a magnetic card andauthenticate the card’s usage by entering an identification number on the keypad.

The bank teller process controls five physical devices: (1) the card reader;(2) the deposit door; (3) a text-oriented display to convey information to the user;(4) the cash dispenser; (5) the report printer.

In addition, the process has the ability to communicate with another processrepresenting the bank. This remote process supports the following set oftransactions:

1) authenticate_request: expects the card’s serial number and the user’spersonal ID number to be passed and either sends back a rejection indi-cation, or an account handle that can be used for transactions.

Page 57: 03 Process Domain

229-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

2) withdrawal_request: the bank returns an authorization code if the with-drawal is allowed.

3) deposit_indicate: informs the bank that a deposit has taken place.

4) balance_request: the bank returns the user’s current balance.

Medium Access System

A simple medium access method is used by the multiple transmitters that sharea channel. Each transmitter must abide by the following rules when trying totransmit a message over the medium:

1) A transmission may not begin until the medium has been idle forGap_Time seconds, where Gap_Time is a parameter whose value is tobe defined.

2) If during a transmission, the transmitter unit detects that another mes-sage is present on the medium, then the transmission is immediatelyaborted and attempted again not before R seconds, where R is a uni-formly distributed random number between zero and Backoff_Time.The same rules of transmission (e.g., idle-time restrictions) apply to re-peat attempts as to initial transmissions.

3) If otherwise unrestricted, a transmission necessarily begins after themedium has been idle for Gap_Time seconds.

4) There is no limit on the number of times a message may be retransmit-ted.

5) Transmission requests that are submitted to the process are transmittedin a first-in-first-out order. The process’ queue of messages that awaitservice is considered infinite.

Data Link Control System

A single outgoing transmission line contains N logical channels, where N is anumber that may change dynamically. Each logical channel is equipped with a datalink layer protocol that ensures the proper reception of transmitted messages.Reception is guaranteed by using an acknowledgment-based scheme whichoperates according to the following:

1) Each message is transmitted repeatedly every Timeout seconds until anacknowledgment message that specifically identifies it is received fromthe destination.

Page 58: 03 Process Domain

230-Prdef

Process Model Development Methodology Modeling Concepts

2) If Max_Attempts transmissions have failed, the message is discarded.

3) Messages are processed in a first-in-first-out order and the messagequeue is considered to have infinite capacity.

This data-link protocol operates independently for each logical channel.

Prdef.3.2 Stage 1: Defining the System’s Context

In almost all cases, process models describe the behavior of a singlecomponent within a larger system model, consisting of many components. Therole of the process model can then generally be described by the interactions that ithas with the other components in the system. From the point of view of theremainder of the system, only the external “black-box” behavior of the process isof concern, not its internal implementation. It is therefore an important first step inthe development of a process model to identify the other system components that itwill interact with.

Prdef.3.2.1 Identifying Interdependent Modules

Since processes operate within modules in the node domain, the termcomponents refers to other modules. In order to refer to these components ingeneral, the term interdependent modules is used. If the interdependent modulesare processors or queues, then their behavior is also determined by a processmodel.

Because processes are event-driven, all modules that generate events for theprocess of interest should be considered interdependent; in addition, all modulesthat receive information from or store information for the process of interestshould also count as interdependent, since they play a role in the evolution of theprocess over time. Note that interdependent modules are not limited to physicalneighbors of the process’ module. For example, modules that are not connected, oreven those that are in different nodes, may communicate by delivering packets orsending remote interrupts to each other. See the Communication Mechanismschapter in this manual for more information on these types of interaction.

In some cases, interdependent modules are not all known in advance at the timethat a process is designed. In fact, some processes may be designed to handleinteractions with an unlimited number of other modules. In such cases one or morerepresentative modules should be included in the design.

Before beginning the actual design of the process of interest, all of theinterdependent modules, including the module whose process is under design,should be placed together in a diagram. Modules need not be identified by theirname, but rather by their function relative to the process of interest. For modulesthat may appear in variable numbers, ellipses can be used to represent a group.

The following sketches depict the physical contexts of the four examplesystems. Note that at this stage of the design, such diagrams may be developed

Page 59: 03 Process Domain

231-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

manually, or within the Node Editor. Ultimately, however, the physical context ofthe process is always defined by a node model diagram created with the NodeEditor.

Prdef.3.2.2 Selecting Communication Mechanisms

Having established which other modules a process would interact with, thedeveloper may proceed to decide the communication mechanism that will be usedon each interface. A number of communication methods are available; the mostcommonly used ones are briefly reviewed here. Refer to the Communication

Pay-Telephone System

Telephone User

Network

Bank TellerSystem

BankCustomer

Account Manager System

Medium Access System

Message source

Message source

PhysicalTx/Rx

System

Interdependent Modules of Medium Access System

Interdependent Modules of Bank Teller System

Interdependent Modules of Pay-Telephone System

Data LinkSystem

Message source

Interdependent Modules of Data Link Control System

PhysicalTx/Rx

System

Page 60: 03 Process Domain

232-Prdef

Process Model Development Methodology Modeling Concepts

Mechanisms chapter of this manual for more complete information on theseoptions.

• Packet communication. Packets are messages whose contents are for-matted into individual fields that carry information. This is the mostcommon form of interface between modules since it naturally corre-sponds to the message-based communications that occurs in many net-works and distributed systems.

Packet communication is a sensible choice for any interfaces that trans-fer messages in the actual system being modeled. In addition, sincepackets can store arbitrary user-specified information, they can be usedto represent general transactions such as commands between proces-sors, requests for resources, tasks with associated parameters, etc. Notehowever, that other supported forms of communication may be moreappropriate than packets, depending on the application.

Packets may be sent to other modules in the same node via connectingpacket stream objects, or they may be sent to modules anywhere in amodel with packet delivery (see the documentation on op_pk_deliver()and related KPs in the Simulation Kernel manual.

• Remote interrupt. This is a lightweight form of communications sinceit does not necessarily transfer a data structure with it, as packet com-munication does. Remote interrupts may be sent to modules within thesame node or in others to indicate simple information such as the statusof a semaphore, or value of a variable. In addition, ICIs, which are for-matted groups of values, can be associated with remote interrupts to al-low them to convey general information to a destination process. Thismakes remote interrupts suitable for modeling transactions such as re-quests and indications, parameterized commands, etc.

Packets can also be used for many of the same types of tasks as theremote interrupts / ICI combination since they can contain general da-ta. However, ICIs incur less overhead and are generally more appropri-ate if the data that traverses the interface is confined to the two modulesof interest (i.e., does not later progress to other destinations). Note,however, that packets have the additional flexibility of supportingtransfer over physical packet streams which implicitly guide the data toa destination that is determined by the configuration of the surroundingnode model; this allows the process model to be developed in a moreabstract fashion where data is sent out via ports without specific knowl-edge of which modules will be the destination.

• Access interrupt: This communication mechanism is used in conjunc-tion with packet communication since it requires the presence of a

Page 61: 03 Process Domain

233-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

packet stream object. Like a packet being sent, an access interrupt isissued by specifying the index of a packet stream, without necessarilyhaving specific knowledge about the object that is connected. However,access interrupts travel backwards on streams, generally to request thata stream’s source request a packet. The interrupt is commonly used inconfigurations where a queue module is a stream source, and thestream’s destination module requests packets from the queue; this is re-ferred to as a passive queue configuration and should be used when aprocess is not able to asynchronously accept packets.

• Statistic communication: Statistic wires can be placed between mod-ule output statistic ports and the input statistic ports of processors andqueues. They provide processes in the destination module with a capa-bility to perform “live” monitoring of the output statistic value. In ad-dition, statistic wires provide triggers which allow asynchronousinterrupts to be generated for the destination module when certain pat-terns of change occur in the monitored statistic. Statistic wires are gen-erally used to alert processes of situations that need attention (such as aqueue approaching overflow), or to allow processes to make use of up-to-date performance and behavioral information in adaptive algo-rithms.

When designing a module’s process models, any combination of the abovecommunication mechanisms may be used with one or more other modules. Threeof the four described interface types above make use of physical ports belonging tothe module whose processes are under design. If any of these physical interfacesare employed, each port should be assigned a name for reference in later stages ofthe design. It is generally helpful to depict all interfaces to and from the module ofinterest, whether physical or abstract, in the node-level diagram that contains theinterdependent modules. The names of the physical interfaces should be placednear the associated input and output ports.

Prdef.3.2.3 Application to Examples

This section uses each of the four example systems defined earlier in thischapter to illustrate the definition of the physical contexts of processes.

Pay Telephone System

In the case of the pay-telephone system, packets are the only necessary form ofcommunicated data. ICIs with remote interrupts could be used, but this wouldrequire assumptions concerning the outgoing interface to the network, since thepay-telephone process would have to know where the network process is located inorder to schedule interrupts for it. By using packets, the pay-telephone processmay rely on the outgoing packet stream labeled Network_Transactions_Out tosomehow guide the packet to the network process. This packet stream may lead toa process in the same node or to a transmitter that uses a link to reach the network

Page 62: 03 Process Domain

234-Prdef

Process Model Development Methodology Modeling Concepts

process in another node; the details of this are not of concern to the pay-telephoneprocess. In addition, the process can receive packets representing actions taken bythe user (e.g., coin-deposit, phone number entry) over the packet stream labeledUser_Transactions_In. The on-hook or off-hook status of the phone is representedinstead by a statistic wire since it is a simple boolean variable; note however, thatuse of the statistic wire relies on the assumption that the user process is in the samenode as the pay-telephone process and that this assumption could be avoided if theon-hook status information were simply incorporated into the packets arriving viaUser_transactions_In. Responses and status information from the network arriveover the packet stream Network_Transactions_In. The use of a stream here issymmetric with the outgoing interface to the network and preserves the flexibilityof placing the network process anywhere. Finally, Line_Status is an outgoingstatistic wire that indicates information to the user process such as whether the lineis available, and the call-nearly-over warning.

Bank Teller System

For the bank teller process, it is assumed that the actions having to do withoperation of the various physical devices can be communicated to the customerprocess via a single packet stream interface called Customer_Transactions_Out.Packets would contain information identifying the affected device and anyassociated parameters (e.g., device = DISPLAY, text = “please enter transactiontype”). All other incoming and outgoing interfaces are also based on packetcommunication to allow placing the processes in arbitrary locations that areselected when the modules are deployed (e.g., the processes could be in differentnodes).

Pay-Telephone System

Telephone User

Network

Physical Context of Pay Telephone System

User_Transactions_In Network_Transactions_Out

Network_Transactions_In

On_Hook_Status

Line_Status

Page 63: 03 Process Domain

235-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Medium Access System

The medium access system can receive packets submitted for transmissionover any number of stream interfaces labeled Src_Traffic_In_0 throughSrc_Traffic_In_N. When the process decides to send a packet onto the medium itcan do so via the outgoing packet stream interface labeled Phys_Traffic_Out. Theprocess also needs to be apprised of two types of status information for themedium. The Medium_Busy_In statistic wire allows the process to determine if themedium is currently carrying any transmissions; the Collision_Status_In statisticwire informs the process if two or more transmissions are simultaneouslyoccurring on the medium.

Data Link Control System

The multiple channels of the data-link control system are logical channels sothe assumption is made that the messages arrive over one physical interface labeledSrc_Traffic_In in the form of packets. The packets must therefore carry someinformation allowing the process to determine which logical channel they belongto. The mechanism by which packets are actually placed on a particular logicalchannel is left to the transmission subsystem to which packets are sent by using the

Account Manager System

Physical Context of Bank Teller System

Customer_Transactions_In Bank_Transactions_Out

Bank_Transactions_In

BankCustomer

Bank TellerSystem

Customer_Transactions_Out

Collision_Status_In

Medium Access System

Message source

Message source

Physical Tx/Rx System

Physical Context of Medium Access System

Src_Traffic_In_N

Src_Traffic_In_0

Phys_Traffic_Out

Medium_Busy_In

Page 64: 03 Process Domain

236-Prdef

Process Model Development Methodology Modeling Concepts

output stream labeled Link_Traffic_Out. Packets arriving from the link are expectedon an incoming packet stream labeled Link_Traffic_In.

Prdef.3.3 Stage 2: Process Level Decomposition

As described in previous sections of this chapter, each queue or processormodule may contain multiple processes, and the number of processes may vary asa simulation progresses. The purpose of this stage of the design procedure is todetermine if the behavior of the module of interest should be implemented by asingle process model or by multiple process models, and in the latter case, what thefunction of and relationship between the process models would be.

Prdef.3.3.1 Decomposition Techniques

It is always possible to implement the desired behavior of a module by meansof a single process. However, there are many modeling situations that are greatlysimplified and more intuitively approached by applying Proto-C’s dynamic processparadigm. In general, multiple processes should be used when:

1) The number of processes in the module must scale in response to dy-namic requirements.

2) The module must manage multiple tasks that operate asynchronously.

3) A top-down approach is required to reduce complexity or to defer de-tailed implementation.

Replication of Identical Processes

This is a common situation in communications systems where a single physicaldevice may be involved in processing a large number of identical ongoing threads.A thread is an ongoing activity that maintains state. Common examples are atelephone call, a virtual circuit in a packet-switched network, or a session of atransport-layer protocol. In modeling computing systems, threads may appear as

Data LinkSystem

Physical Tx/Rx

System

Message source

Physical Context of Multi-Channel Data Link Control System

Src_Traffic_In

Link_Traffic_Out

Link_Traffic_In

Page 65: 03 Process Domain

237-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

programs that are run under a multitasking operating system, or as sub-tasks ofthose programs.

The requirement that a module should execute a dynamic number of processesof the same type is generally quite clear from the specification of a modelingproblem. The key system feature associated with this type of scenario is the factthat a variable number of users of the module receive service on an essentiallyindependent basis. A user is not necessarily another module, but should be a sourceof activities for the module. For example, a single traffic source could generatemultiple packets representing initiated telephone calls and attribute them todifferent users by placing a user identification in a field of the packet. Each callwould then be processed independently when it is received by the module ofinterest. Thus, even though there is only one source module, it acts as a model ofmultiple users that generate activity for the module being designed.

The approach for this type of module is to create a process model thatimplements a single thread. A higher level process, usually the root, detectsconditions that require the initiation of new threads (e.g., a new telephone callrequest is received) and uses the KP op_pro_create() to create processes torepresent them. If a thread evolves to a point where it is no longer needed (e.g. thetelephone call parties hang up), it can be terminated with the KP op_pro_destroy(),either by itself or by a master process.

Asynchronous Cooperating Tasks

Certain processes can be broken down into several smaller processes thatoperate asynchronously but cooperate to accomplish a common goal.Asynchronous operation refers to the fact that the processes have separate event-processing threads that are driven by differing sequences of events. The processesmay depend on one another for information and may even generate events for eachother; however to be considered asynchronous, at least part of the processes’timing should be independent. If instead, all processes are executed in lock-step(i.e., at the exact same times), then they can easily be subsumed into a singleprocess that manages all of their activities.

Using dynamic processes, Proto-C provides a very natural way to address themodeling of this type of system. The developer must divide the activities of themodule of interest into separate functional areas, keeping in mind the guidelinethat each functional area should have not only different responsibilities, butdistinct timing as well. Each functional area can then be implemented by a distinctdynamic process with its own state. The processes may also share information,using the various process hierarchy memory mechanisms described earlier in thischapter.

This approach requires delimiting the functional areas by assigning names tothem and listing the activities for which each one is responsible. In addition, therelationships between the processes should also be defined in a general fashion atthis point to ensure that the functional boundaries that have been selected arefeasible.

Page 66: 03 Process Domain

238-Prdef

Process Model Development Methodology Modeling Concepts

Top-Down Implementation for Complexity Reduction

In general, system designs begin specification with abstract components thatrepresent more detailed functionality to be defined later. While the general purposeof an abstract component is characterized, the internal organization andmechanisms that it uses to accomplish its function is the subject of a later designphase. This design approach is referred to as top-down, and is a natural methodbecause of the fact that system specifications generally begin with capability andperformance requirements. Subsystems that operate together to implement thesecapabilities and meet these performance requirements can then be defined in orderto subdivide the design problem. Each subsystem can then be designedindividually to meet its own set of requirements.

In contrast to design, the activity of modeling assumes that a detailedspecification or a reference implementation already exists. The approach ofproceeding in a top-down fashion is less critical since there is already knowledgeof lower level parts of the system. In addition, if the system model is to beoperational (i.e., a simulation of it can be executed) then even the lowest levels ofthe system must be represented in at least a simplified manner. This implies thatthe complete deferral of lower level implementation is not possible if meaningfulsimulations are to be executed.

However, top-down implementation can often be an effective tool for reducingcomplexity by spreading the detail of the model over several levels. For processesbased on state transition diagrams (STD), the top-down approach requires theability to represent lower level STDs within the states of higher level STDs. InProto-C this hierarchical structure can be supported by invoking a lower-levelprocess model within the executives of an unforced state. The higher-level processmust then block until it receives a signal from the lower-level process that theoperation for which it was invoked has completed. Proto-C supports a dynamichierarchy, meaning that the choice of whether a lower-level process or even whichlow-level process would be invoked can be determined as a function of informationthat changes over time. This is in contrast to a static hierarchy which would alwaysimplement a higher level state using the same lower-level STD.

In the methodology presented in this chapter, the top-down approach is used inlater steps having to do with decomposition of a process into states and definitionof the actions associated with each state. The approach simply suggests that whendefining the states of a process, that these states should represent high-level modesof the process and that within them, other processes should be used to implementmore specific sub-modes.

Prdef.3.3.2 Application to Examples

In order to illustrate the applicability of process decomposition, this sectionexamines which techniques would best apply to each of the four example systemsdescribed earlier in this chapter.

Page 67: 03 Process Domain

239-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Pay Telephone System

The pay telephone system has only one user at a time and interfaces to thenetwork to service the requests of the user. The number of activities that it managestherefore does not vary over time and it does not meet the criteria of having tocreate dynamic contexts to meet a variable demand.

The pay telephone system is also quite simple with regard to distinct activitiesthat it manages. One possible decomposition into multiple processes would have aprocess managing interactions with the user and another managing interactionswith the network. However, there is never any interaction with the network while aphone call is not in progress; in addition, most of the interaction with the networkis tightly interwoven with the user interaction, since the pay telephone actsessentially as an intermediary between the two parties. A decomposition would bepossible along these lines but would probably result in more coordination overheadthan simplification of the system since the two processes would not really beasynchronous. Since no other asynchronous subsystems are readily identified,decomposition into several processes does not seem appropriate. Furthermore,since the system is extremely simple, no large subtasks can be encapsulated intolower-level processes. Therefore the best solution appears to be to represent thissystem as a single process.

Bank Teller System

As in the case of the pay telephone system, at most one thread is ongoing at atime. As a result, the use of a variable number of identical processes is notnecessary. Also like the pay telephone, the system acts as a go-between two othersystems and the interactions with each are closely related; therefore decompositioninto two asynchronous processes on this basis would not be beneficial.

However, a natural breakdown does appear in this process for the three types ofsupported transactions; namely withdrawals, deposits, and balance verifications.Therefore a high-level process can be constructed that is responsible forauthenticating use of the card, and determining the transaction type. Actualimplementation of the individual transactions can then be done by invoking theappropriate subprocess. The diagram below shows the basic relationship betweenthese processes.

Page 68: 03 Process Domain

240-Prdef

Process Model Development Methodology Modeling Concepts

In this organization, the process labeled Auth is the most appropriate to act asthe root process in the module, since it must always be present to begin newtransactions. It would be possible to create the three child processes dynamically tomanage transactions as they occur and then to destroy them; however, since onlyone transaction may occur at a time, there is no need to repeatedly incur theoverhead associated with these mechanisms. The approach selected here is to havethe Auth process create the three remaining processes as part of its owninitialization and to continually reuse the same process instances as required tohandle transactions requested by the user.

Medium Access System

Due to the fact that the system handles medium access for one packet at a time,there is no need for a variable number of identical processes to be created.However, several clearly distinct functional areas appear among the system’sactivities.

1) Acceptance and queueing of arriving messages.

2) Transmission management for the earliest enqueued message.

3) Monitoring the medium to determine appropriate times for transmis-sion.

These three activities have some relationship to each other and must thereforebe determined to operate asynchronously in order to form an appropriatedecomposition of the system. If the system is idle (i.e., no packet is waiting toaccess the medium) then the queue-management process must inform the

Process that manages authentication and determination of transaction typeAuth

Withdrawal Deposit Verify

Processes invoked to manage three types of transactions

Invocations performed once transaction type is selected

Hierarchical Process Decomposition for Bank Teller System

Page 69: 03 Process Domain

241-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

transmission management process immediately when a packet arrives. Thetransmission management process must also receive information from themedium-monitoring process whenever a collision occurs so that it can abort itstransmission. In addition, the status of the medium’s usability must be available atall times to the transmission management process in order to decide when toinitiate transmission attempts.

Note that the medium-monitoring process must be running at all times,independently of the other processes, in order to be able to accurately determinethe times at which the medium becomes usable. In addition, the queue-management process may be required to accept and enqueue many packets duringthe period required for the transmission process to successfully transmit just onepacket; this queueing activity is a background task that has no effect on thetransmission process except under one special circumstance noted above. Thethree activities therefore seem loosely coupled enough that they form a properdecomposition of the system into three asynchronously operating processes. Thisdecomposition appears in the following diagram.

Any of the three processes could play the role of root. However, note that theMedium_Mon process must be present from the beginning in order to compute theusability of the medium which must be available at all times. If this process startedlater then it may not be known if the medium was busy in the early moments of thesimulation, making it impossible to determine exactly at what time it shouldbecome usable for transmission. Also, the Q_Mgr process should be present at alltimes in order to handle the arrival of the first message. Only the Tx_Mgr process

Q_Mgr

Tx_MgrMedium_Mon

Medium_Mon notifies Tx_Mgr when appropriate changes in medium status occur

Q_Mgr notifies Tx_Mgr when new packet arrives, if Tx_Mgr is idle

Tx_Mgr is responsible for successfully complet-ing the transmission of a message

Q_Mgr is responsible for enqueueing newly arriving messages

Medium_Mon must determine at what times the medium becomes usable and unusable

Asynchronous Cooperating Process Decompositionfor Medium Access System

Page 70: 03 Process Domain

242-Prdef

Process Model Development Methodology Modeling Concepts

stands out as not being necessary in the initial moments since it can easily becreated by the Q_Mgr once the first message arrives. Therefore, either Medium_Monor Q_Mgr should be used as the module’s root process. The approach selected hereis to use the Q_Mgr process as root and to create the Medium_Mon processimmediately. Subsequently, the Tx_Mgr process will be created by Q_Mgr uponreceipt of the first message for transmission.

Data Link Control System

This system may involve the management of activities for a number of logicalchannels and this number may change over time. Furthermore, each logicalchannel can be considered to exist as a thread in the sense that it maintains state(e.g., the packet that has to be retransmitted) and requires activities to be continuedover a period of time. Each logical channel can therefore be managed by anindependent but identical process that is concerned only with the events that affectits channel.

A process is also required to accept new messages that are submitted fortransmission and to receive acknowledgments from the remote destination sincethere is not a priori reason to route these directly to any particular process. Sinceall of the channel-management processes play a symmetric role, and since a singleprocess acts as a dispatcher of messages to the channel-management processes, itis a natural decision to appoint the dispatcher process as root. This process can inaddition be responsible for creating the channel-management processes when arequest is submitted for a channel that is not yet known. The organization of theseprocesses is shown in the diagram below:

Dispatcher invokes (and first creates if necessary) appropri-ate Channel_Mgr process to handle arriving messages and acknowledgments.

Dispatcher

Channel_Mgr Channel_MgrChannel_Mgr

Decomposition of Data Link Control Systeminto a Scalable Number of Dynamic Processes

Channel_Mgr processes perform the required protocol for packets assigned to their respective logical channels. They do not interact with each other.

Page 71: 03 Process Domain

243-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3.4 Stage 3: Enumeration of Events

This stage of the design methodology is performed for each process defined inthe process decomposition stage, rather than for the system as a whole. Generally,a process assumes some or all of the functions of the system in which it is locatedby performing actions and modifying state information in response to logicalevents. A logical event (as opposed to an ordinary OPNET event) is an occurrencethat requires the intervention of the process. The purpose of the event enumerationstage is to construct a complete list of the logical events that can affect the processof interest. The actual actions that are taken in response to these interrupts are thetopic of a later stage in the methodology.

Prdef.3.4.1 Identifying Logical Events

A process may be called upon to respond to an interrupt either directly by theSimulation Kernel or by another process within the same process hierarchy. In bothcases, however, an event must first occur for the module that encompasses theprocess. The Simulation Kernel then chooses a process to receive the interruptdirectly (the technique used to control which process is invoked directly is calledinterrupt steering and is described in detail the Modeling Framework chapter ofthis manual). This process may in turn cause other processes to be invoked bycalling the Kernel Procedure (KP) op_pro_invoke().

The first goal of this stage is simply to determine which logical events aprocess must be prepared to receive. The actual type of the correspondinginterrupts or the way in which they are communicated is not important at this time;rather the causes of the interrupts and the sources from which they came must beidentified. Each logical event should be assigned a descriptive name and placed ina list.

Logical events may be generated from three types of sources: (1) modulesoutside the local system; (2) other processes within the same module; (3) theprocess itself. Unfortunately, there is no general method for determining theinterrupts of a process; however, the activities of the encompassing system as awhole and the interactions of the system are a good starting point. Not all of theinterrupts that affect the encompassing system will necessarily affect the processof interest, but the irrelevant interrupts can easily be sorted out.

The developer should take into account interrupts that cause a direct invocationof other processes, provided that these processes directly or indirectly invoke theprocess of interest. In particular, other processes may generate interrupts forthemselves and in handling those interrupts, invoke the process by callingop_pro_invoke(). Of course, self interrupts generated by the process for itself mustalso be identified, and the event of creation is also important for some processes(for root processes, this event occurs at the beginning of the simulation).

Page 72: 03 Process Domain

244-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.4.2 Determining Event Implementation Methods

The previous section identified the significance of the events; this sectiondiscusses the manner in which the logical events are actually implemented in thesimulation model. The logical events that affect a process must manifestthemselves as interrupts delivered to the process by the Simulation Kernel, or asinvocations of the process by other processes within the same surrounding module.In both cases, an interrupt must have been delivered to one of the processes in themodule for a logical event to occur.

While the significance of events varies widely and is dependent on themodeling application, OPNET supports only a small, finite set of interrupt typeswith which to implement these events. As a result, it is generally quite simple toselect an appropriate type of interrupt to represent each logical event expected by aprocess. In addition, certain decisions made in the initial stage of this modelingprocess provide information that is helpful here. Namely, the context definitionstage suggests communication mechanisms that should be used for the interactionsthat the system has with other module and the choice of a communicationmechanism usually implies a particular interrupt type (e.g., packet-basedcommunication indicates stream interrupts are used). Also, certain types of logicalevents are usually represented using particular types of well-suited OPNETinterrupts. The following table provides a general correspondence between somecommonly encountered types of logical events and OPNET interrupt types. See theModeling Framework chapter of this manual for a comprehensive description ofeach interrupt type and possible uses.

Common Logical Eventsand Usual Corresponding Interrupt Types

Logical Event Interrupt Type

Creation of process begin simulation interrupt for root process; general for others

Expiration of timer self interrupt

Receipt of message stream interrupt

Receipt of command to perform an action

remote interrupt or stream interrupt, depending on how command is represented

Change in status of other module statistic interrupt or remote interrupt, depending on whether the other module is in the same node

Request to forward a packet to neighboring module

access interrupt

Change in operability status of a network-level object (node or link)

failure interrupt, recovery interrupt

Page 73: 03 Process Domain

245-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3.4.3 Application to Examples

This section discusses the application of the event enumeration stage to thefour example systems described earlier in this chapter.

Pay Telephone System

Most events can be easily extracted from the system definition, since most ofthe action descriptions depend on the occurrence of particular conditions. In thecase of the pay telephone system, the events that are apparent include indicationsof actions taken by the user and signals sent by the network. In addition, note thatthe network provides a warning some time before the call must be disconnected,but no final disconnect signal; this event must therefore be generated internally(e.g., as a self interrupt). All the anticipated events of the process appear in thefollowing table together with the interrupt types selected for their implementation.

Bank Teller System

The description of the bank teller system does not make the set of events asclear as in the case of the previous example. However, some of the events areimplicit in the activities that are described. For example, if the customer can selectbetween three transaction types, there must be an event which corresponds to thecustomer completing a selection. Also, insertion of the bank card and identificationnumber correspond to two separate events. The account manager also generatesevents for authentication of the card and ID number, and approval of each

Logical Events for Pay Telephone Process

Event Name Event Description Interrupt Type

User_Pickup User takes handset off hook statistic

User_Hangup User replaces handset on hook statistic

User_Add_Fare User deposits money stream

User_Tel_Num User dials telephone number stream

Net_Dial_Tone Network provides dial tone stream

Net_Connect Network indicates call has gone through and whether call is toll-free

stream

Net_Fare_Low Network warns that money has nearly run out

stream

Disconnect Money has completely run out and call must be terminated

self

Page 74: 03 Process Domain

246-Prdef

Process Model Development Methodology Modeling Concepts

transaction. In addition, an event must be generated to allow a customer to cancel atransaction in progress.

Since this system uses four processes, each process’ logical events must beenumerated separately. The following tables summarize the logical eventsexpected by each process and the interrupt types that are used to implement them.

Logical Events for Auth Processof Bank Teller System

Event Name Event Description Interrupt Type

Cust_Card_Ins Card has been inserted by customer

stream

Cust_ID_Entered Customer has typed in per-sonal identification number

stream

Cust_Trans_Sel Customer has selected one of three transaction types

stream

Cust_Trans_Cancel Customer has decided to cancel transaction (may hap-pen at any time)

stream

Bank_Auth Bank has authorized use of card based on ID number

stream

Bank_Reject Bank has denied use of card based on ID number

stream

Cust_Trans_Over Customer transaction has completed

invocation by corre-sponding child pro-cess

Logical Events for Withdrawal Processof Bank Teller System

Event Name Event Description Interrupt Type

Cust_Amount_Entered Customer has entered an amount needed for with-drawal transaction

stream

Bank_Trans_Approval Bank has authorized comple-tion of transaction

stream

Cust_Trans_Cancel Customer has decided to cancel transaction (may hap-pen at any time)

stream

Page 75: 03 Process Domain

247-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Medium Access System

This system relies on three processes, each of which is driven by a separate setof logical events. The root process is Q_Mgr, which is responsible for insertingnewly arriving packets in the queue, where they will wait to be processed by theTx_Mgr process. Q_Mgr’s logical events appear in the table below.

Logical Events for Deposit Processof Bank Teller System

Event Name Event Description Interrupt Type

Cust_Amount_Entered Customer has entered an amount needed for deposit transaction

stream

Cust_Deposit_Inserted Customer has inserted deposit documents through deposit door

stream

Cust_Trans_Cancel Customer has decided to cancel transaction (may hap-pen at any time)

stream

Logical Events for Verify Processof Bank Teller System

Event Name Event Description Interrupt Type

Bank_Balance_Rcvd Balance information has been received from bank

stream

Cust_Trans_Cancel Customer has decided to cancel transaction (may hap-pen at any time)

stream

Logical Events for Q_Mgr Processof Medium Access System

Event Name Event Description Interrupt Type

Process_Create Initial event provided to allow initialization of process

begin simulation

New_Message A message has been submit-ted to the module for trans-mission onto the medium

stream

Page 76: 03 Process Domain

248-Prdef

Process Model Development Methodology Modeling Concepts

The Medium_Mon process is responsible for determining the usability of themedium based on the activity of the recent past. It must therefore be notified eachtime that a change in the medium’s status occurs. In addition, the processes mustbe notified once the medium has been idle for Gap_Time seconds. Its logical eventsare shown below.

The third and most complex process in this system is the Tx_Mgr process,which must manage, across repeated attempts if necessary, the transmission of themessage onto the medium. This process may be invoked to begin transmission of anew message, or for various events that may occur during the transmission of acurrent message. Note that the process must use a self interrupt to know when itsown transmission has completed so that it can begin another, if required. Thecomplete set of logical events for Tx_Mgr appear in the following table:

Logical Events for Medium_Mon Processof Medium Access System

Event Name Event Description Interrupt Type

Process_Create Initial event provided to allow initialization of process

invocation by Q_Mgr process

Busy_High The medium’s status has changed from free to busy

statistic

Busy_Low The medium’s status has changed from busy to free

statistic

Gap_Elapsed The medium has been free for Gap_Time seconds, meaning that it has become usable for transmission

self

Logical Events for Tx_Mgr Processof Medium Access System

Event Name Event Description Interrupt Type

Process_Create Initial event provided to allow initialization of process

invocation by Q_Mgr process

New_Message New message has been sub-mitted for transmission

invocation by Q_Mgr process

Medium_Usable The medium has been free for at least the required gap time between messages, meaning that a transmission may begin

invocation by Medium_Mon process

Page 77: 03 Process Domain

249-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Data Link Control System

This system uses two processes, with the root acting essentially as a dispatcherby routing arriving messages to the appropriate Channel_Mgr child process. Theroot process uses the model Dispatcher and responds to message arrivals from themessage source and to acknowledgment messages returned from the remote sitevia the link. No events are generated internally, since dispatching is assumed totake no time to perform and this is the only activity. The logical events ofDispatcher are shown below:

Because the Dispatcher process has no other function than to create and invokechannel manager processes, the events in the table above also appear in the eventtable of the Channel_Mgr process. In addition, each Channel_Mgr must internallygenerate timer events to initiate retransmissions of unacknowledged messages, asshown below.

Tx_Complete Current transmission has completed without a collision

self

Tx_Collided Current transmission over-lapped with another transmis-sion on the medium

statistic

Backoff_Elapsed The random backoff period following a collision has elapsed, allowing a new transmission attempt

self

Logical Events for Dispatcher Processof Data Link Control System

Event Name Event Description Interrupt Type

Process_Create Initial event provided to allow initialization of process

begin simulation

Src_Message_Arrival Message has arrived from traffic source to be queued for transmission with appropri-ate channel manager

stream

Link_Message_Arrival An acknowledgment has been received from one of the channels, to be handed to the appropriate channel manager

stream

Logical Events for Tx_Mgr Processof Medium Access System (Cont.)

Event Name Event Description Interrupt Type

Page 78: 03 Process Domain

250-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.5 Stage 4: State-Level Decomposition of Processes

This stage of the methodology is performed for each process that has beendefined within a system. State decomposition forms the basis of a state transitiondiagram (STD) that represents a Proto-C process.

Prdef.3.5.1 Criteria for Defining States

The goal in this stage is to define a set of discrete states that will later beconnected with transitions to form an STD. At this point only the states need beidentified and if possible, the specific conditions for transitions should beexamined in a later stage of development. The following guidelines should be usedin selecting states:

• A state should correspond to a mode of the process in the sense thatonly particular sequences of events are able to bring the process intothat state.

• A state is characterized by the fact that events are handled a particularway as a result of the process being located in that state.

• The combination of states should form a mutually exclusive, comple-mentary set, such that the process always occupies exactly one of thestates.

• A state should represent a “resting place” for a process, meaning thatthe process should be able to wait in the state for new interrupts to oc-

Logical Events for Channel_Mgr Processof Data Link Control System

Event Name Event Description Interrupt Type

Process_Create Initial event provided to allow initialization of process

invocation by Dis-patcher process

Src_Message_Arrival Message has arrived from traffic source to be queued for transmission

invocation by Dis-patcher process

Link_Message_Arrival An acknowledgment has been received from remote process

invocation by Dis-patcher process

Ack_Timeout Timer has expired while wait-ing for acknowledgment mes-sage from destination in order to support retransmission

self

Page 79: 03 Process Domain

251-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

cur. This implies that the states that are defined in this step of the meth-odology should not be used simply to specify actions, and therefore arenot the forced states of the process. Forced states are a convenient fea-ture for graphically representing control-flow and are considered at alater stage.

Note that, as its name implies, a state represents part of the “memory” of aprocess since it reflects the path that the process has taken to reach it. However, notall of the memory of a process need be reflected by the state that it occupies, due tothe fact that Proto-C provides state variables. Thus, states can be used to representlogical modes of the system that are distinguished primarily by differences in theevents that are expected and the way events are processed.

Prdef.3.5.2 Application to Examples

Other than the criteria for state definition provided in the previous section,there is no general method that always yields an efficient set of states of a process.In some modeling problems, processes are already described as STDs in thesystem specification, making the selection of states straightforward. However, ifthis is not the case, the developer must try to select a set of states by analyzing theactivities of the process and the events that occur.

When state selection is not obvious, one possible approach is to begin analysiswith an initial state where the process would be located when it is created. Possibleevents that could occur while the process is in this state should then be consideredone at a time; each event may lead to a new state that reflects its occurrence, unlessa state already exists that represents an appropriate response to the event. In thisway new states are defined, and event analysis can be performed again for the newstates until there is no need to create additional states.

This section illustrates state decomposition by enumerating possible state setsfor the processes of the four example systems defined earlier in this chapter.

Pay Telephone System

This system is implemented as a single process which must therefore respondto all possible events received by the system. These events were identified in theprevious stage of the methodology. Examining the events suggests that the processfollows a direct path through a predictable sequence of actions, as follows:(1) process is in idle state; (2) user picks up phone; (3) user deposits money;(4) network provides dial-tone; (5) user dials telephone number; (6) networkestablishes connection and indicates if fare is free; (7) conversation takes place;(8) user hangs up or money runs out; (9) call disconnected.

This sequence of actions does not represent the states of the process butprovides a good starting point for discovering them. The key is to recall that statesshould represent intervals of time for the process between actions; this leads to thefollowing set of states based on the above sequence:

Page 80: 03 Process Domain

252-Prdef

Process Model Development Methodology Modeling Concepts

Bank Teller System

The bank teller system is composed of four processes for which states must bedefined. The root process is called Auth and is responsible for the initial phases ofa customer’s transaction with the teller. Specifically, Auth must obtain the user’scard and ID number and have them validated by the bank; then it must determinethe type of transaction the user desires and start the appropriate child process tomanage that transaction. These phases correspond to the states listed below.

States for Pay Telephone Process

State Name State Description

Idle Waiting for phone call to be initiated by a user.

Deposit_wait Waiting for deposit to be made.

Tone_wait Waiting for dial-tone to be provided by network so that user can begin dialing.

Dial_wait Waiting for user to complete dialing so that connection can be established.

Connect_wait Waiting for a connection to be established and for indication of whether call is toll-free.

Connect_estab Connections has been established and conversation is ongoing; waiting for the user to terminate by hanging up or for the network to notify that money has almost run out.

Disc_ct_down The warning has been received that money has nearly run out. A count down towards a disconnect is occurring; the user may avert this by depositing more coins.

States for Auth Process of Bank Teller System

State Name State Description

Idle Waiting for customer to engage automatic bank teller by inserting card.

ID_wait Waiting for customer to enter personal identification number.

Auth_wait Waiting for authorization and account handle to return from bank.

Select_wait Waiting for user to select transaction type.

Trans_compl_wait Waiting for selected transaction to complete or to be canceled.

Page 81: 03 Process Domain

253-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

The transaction management processes Deposit, Withdrawal, and Verify aresimple processes that sequence a small number of events. Note that twoapproaches can be selected with regard to the creation of these processes: they maybe created when the system initializes and be viewed as permanent resources, likesubroutines in a program; or they may be created dynamically for each transactionand then destroyed when the transaction completes. In the former case, theprocesses would need an additional state which they would occupy while waitingfor a transaction to begin. The second approach is selected in this case, therebyallowing the processes to assume that they are in the midst of handling atransaction. The states for the three processes appear in the following tables.

Medium Access System

The medium access system makes use of three asynchronously operatingprocesses called Q_Mgr, Medium_Mon, and Tx_Mgr to control transmissions. Oncecreated, the Q_Mgr process expects only one type of logical event representing amessage arrival. Each arriving message is processed independently of the previousones, so the process has only one mode, as shown in the following state table:

States for Withdrawal Process of Bank Teller System

State Name State Description

Amount_wait Waiting for user to enter amount to be withdrawn from account.

Auth_wait Waiting for bank to approve withdrawal of specified amount.

States for Deposit Process of Bank Teller System

State Name State Description

Amount_wait Waiting for user to enter amount to be deposited to account.

Insert_wait Waiting for customer to physically deposit envelope through deposit door.

States for Verify Process of Bank Teller System

State Name State Description

Balance_wait Waiting for bank to acknowledge transaction and simulta-neously return balance information.

Page 82: 03 Process Domain

254-Prdef

Process Model Development Methodology Modeling Concepts

The Medium_Mon process is responsible for determining when the mediumbecomes usable and when it ceases to be usable. In order to do this, the processmust time the silent periods on the medium and when a fixed silent interval hasoccurred, the medium can be declared to be usable. The logical events used in thisdecision process are the medium going busy, the medium going idle, and thesilence interval elapsing, as described in the event enumeration stage of themethodology. These three events suggest a natural decomposition into three states,as follows:

Initially, the Tx_Mgr process has no messages to transmit and may later returnto this condition after having completed transmissions if its input queue is empty.Thus, a state to represent this idle mode is required. Once a transmission begins, itcan move through several phases: waiting for a usable medium; waiting todetermine the status of a transmission; and if a collision has occurred, waiting forthe random backoff timer to expire. These lead to the following state table:

States for Q_Mgr Process of Media Access System

State Name State Description

Message_wait Waiting for a message to be submitted to the media access system.

States for Medium_Mon Process of Media Access System

State Name State Description

Medium_usable Medium is usable for new transmissions due to having been idle for at least Gap_Time seconds.

Medium_busy Medium is currently busy (and therefore not usable for new transmission).

Gap_elapse_wait Medium has changed from busy to free within last Gap_Time seconds and therefore is still not usable.

States for Tx_Mgr Process of Media Access System

State Name State Description

Idle No transmissions are in progress; input queue is empty.

Medium_wait Waiting for medium to become available, at which point a transmission can be initiated.

Page 83: 03 Process Domain

255-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Data Link Control System

The multichannel data link control system uses a Dispatcher process to routearriving messages to the appropriate child process, which is of type Channel_Mgr.The routing is performed based on each message’s logical channel ID,independently of previous messages. The Dispatcher process has only one modewhich is to wait for the next arriving message, process it and wait again. Its statetable appears below.

The Channel_Mgr process is more complex since each message that is handledfollows a progression including a transmission phase, possible retransmissions,and an acknowledgment phase. In addition, queueing of new messages must beperformed on an asynchronous basis (a second process might have been definedfor this purpose as was done for the media access system; however, here thisactivity is simply performed as a background task in each state of the channelmanager). A possible state table that supports these phases is shown below:

Tx_status_wait Waiting to learn if transmission was successful or if a collision occurred.

Backoff_wait A collision occurred and the backoff interval is cur-rently counting down; waiting for this interval to com-plete so that the transmission may be reattempted.

States for Dispatcher Process of Data Link Control System

State Name State Description

Message_wait Waiting for a message to be submitted to the data link control system, either from the source or from the link.

States for Channel_Mgr Process of Data Link Control System

State Name State Description

Idle No messages are available to transmit and no acknowledgments are pending; the process is waiting for a new message to arrive from the traffic source.

Ack_wait A message has been transmitted and an acknowledg-ment is awaited; a timer may expire to indicate need for retransmission.

States for Tx_Mgr Process of Media Access System (Cont.)

State Name State Description

Page 84: 03 Process Domain

256-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.6 Stage 5: Developing the State Transition Diagram

At this milestone, the states of each process have been defined. In addition, theset of logical events that require a response on the part of each process have beenidentified. The purpose of this stage is to combine these two sets of data in order toform the basic state transition diagram (STD).

Prdef.3.6.1 Determining the Feasible Events of a State

For most process models, it is only possible for a subset of the logical events tooccur while the process is located in a given state. This is generally due to the factthat the involvement of the process itself is required in the interactions that result inthe event. For example, the authorization process of the Bank Teller System cannotexpect the user to select a transaction type while it occupies the state where thecard’s insertion is awaited, because the menu of possible transactions has not beenpresented yet.

To avoid including infeasible transitions in the STD, this methodologycharacterizes each event with respect to each state, using three categories:infeasible, suppressed, and feasible.

• Infeasible events are those that have no possibility of occurring due tothe particular circumstance that the process finds itself in when occupy-ing a given state, such as the Bank Teller System example mentionedabove.

• Suppressed events are those that would have the physical possibility ofoccurring but that provide no useful information to the process. In theinterest of efficiency and simplification, invocations of the processshould be avoided for these state-event combinations. Various suppres-sion mechanisms for interrupts are available and are discussed in othersections of this chapter. What is relevant at this stage in the methodol-ogy is not how to suppress these events, but simply to make the assump-tion that they will not occur. It is useful to sort them out now in orderto support the work that will later be required in order actually imple-ment their suppression.

• Feasible events are those that are not only possible to receive, but thatthe process may have a use for while occupying a particular state. Theseevents form the basis for the definition of transitions in the STD.

The first step of this stage consists in constructing a table that maps logicalevents against states of the process. By systematically listing each logical event foreach state, the developer can ensure that no important events will be ignored in thedesign of the STD (ignoring an event can later lead to simulation errors). For eachstate-event combination, one of the three feasibility categories above should beassigned. The following table provides an example of such a table for the case of

Page 85: 03 Process Domain

257-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

the media access system’s Tx_Mgr process. The feasible events are highlightedsince these are the principal ones of interest in the subsequent steps of this designstage.

Prdef.3.6.2 Constructing an Event Response Table

Processes are driven by the occurrence of logical events. Once a logical eventis received, the process has the opportunity to carry out a sequence of five steps asfollows:

Feasible Events for States of Tx_Mgr Process

State Name Logical Event Feasibility

Idle New_Message feasible

Medium_Usable suppressed

Tx_Complete infeasible

Tx_Collided suppressed

Backoff_Elapsed infeasible

Medium_wait New_Message suppressed

Medium_Usable feasible

Tx_Complete infeasible

Tx_Collided suppressed

Backoff_Elapsed infeasible

Tx_status_wait New_Message suppressed

Medium_Usable suppressed

Tx_Complete feasible

Tx_Collided feasible

Backoff_Elapsed infeasible

Backoff_wait New_Message suppressed

Medium_Usable suppressed

Tx_Complete infeasible

Tx_Collided suppressed

Backoff_Elapsed feasible

Page 86: 03 Process Domain

258-Prdef

Process Model Development Methodology Modeling Concepts

1) Actions may be performed by the exit executive statements of the un-forced state that is currently occupied.

2) The condition statements are evaluated for all of the outgoing transi-tions of the currently occupied state.

3) Actions may be performed by the executive statement of the transitionthat is selected (i.e. the one that evaluates to a TRUE boolean value).

4) The process follows the transition and occupies a (possibly) new state.

5) Actions may be performed by the enter executives of the new state.

At this stage of model development, only unforced states of the STD have beenconsidered. Forced states can be introduced later to improve model appearance, orconsolidate redundantly specified actions; however, they do not alter thefundamental structure and timing of the model, which are provided by theunforced states and their transitions. Since transitions from unforced states alwayscorrespond to the occurrence of an event, the state-event combinations serve as agood starting point for defining the STDs transitions. Only feasible events need beconsidered since other events are assumed never to occur while in particular states.

The suggested approach to determining the STDs transitions is to generate atable, known as an event response table, that describes the process’ possiblecourses of action for each feasible state-event pair. The table lists every feasiblestate-event pair in the two left columns. For each such pair, at least one transitionwill be defined; in addition, it is possible that several transitions would beapplicable provided that they are differentiated by additional requirements in theircondition statements (recall that the conditions of all transitions departing from astate must be mutually exclusive). If the process must have the ability to transitiondifferently or to perform substantially different actions, based on the fulfillment ofcertain conditions at the time the event occurs, then these conditions must becharacterized in the table; general “English-like” statements of these conditionsshould be entered in the third column of the table, called condition.

The next column, labeled Action, represents any activity that must beperformed as a result of the transition taking place. Depending on the exact natureof the action, it could be implemented as part of the current state’s exit executivestatements, as part of the transition’s executive, or in the next state’s enterexecutives; this issue is addressed in later stages and does not need to be specifiedin the table. Finally, the Next State column specifies which state the process shouldoccupy next due to the occurrence of the event and the condition being true. Theresulting table for the Tx_Mgr process of the Media Access System appears below.

Page 87: 03 Process Domain

259-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3.6.3 Defining Transitions

This section introduces methods for defining transitions that will be used in thesubsequent section where construction of the STD begins. No diagrams or tablesneed be generated from the information presented here.

As mentioned earlier, each logical event that is feasible in a given state must behandled by at least one outgoing transition of that state. One possible approach todefining the transitions of the STD is to consider each row of the event responsetable and to create a transition that matches its specifications. For example,consider a row defined as follows:

Then a transition could be defined between two states to express the following:if the current state is S0, and the logical event E occurs, and the condition C holds,

Event Response Table for Tx_Mgr Process

Current State Logical Event Condition Action Next State

Idle New_Message medium is usable begin trans-mission

Tx_status_wait

medium is not usable

Medium_wait

Medium_wait Medium_Usable begin trans-mission

Tx_status_wait

Tx_status_wait Tx_Complete queue is empty Idle

queue is not empty and medium is usable

begin trans-mission

Tx_status_wait

queue is not empty and medium is not usable

Medium_wait

Tx_Collided abort trans-mission; begin backoff

Backoff_wait

Backoff_wait Backoff_Elapsed medium is usable begin trans-mission

Tx_status_wait

medium is not usable

Medium_wait

Current State Logical Event Condition Action Next State

S0 E C S1

Page 88: 03 Process Domain

260-Prdef

Process Model Development Methodology Modeling Concepts

then the process should move to occupy state S1. In Proto-C, as in the C and C++languages, the operators && (two ampersand characters) and || (two vertical bars)are used to express the logical operations AND and OR, respectively. Therefore, thetransition would appear as follows in a Proto-C diagram.

All transitions in an STD could be represented in this straightforward mannerin order to encode all of the control-flow information in the event response table.However, there need not always be a one-to-one correspondence between logicalevents and transitions at a given state. There are two general forms that can beextracted from the event response table to express transition conditions:

1) A single transition may handle a union of multiple logical events. Ifin a given state of a process there are multiple feasible logical events,then it is possible for several of these events to cause a transfer to thesame destination state. Proto-C supports the use of multiple transitionobjects to represent such situations; however, in order to reduce thecomplexity of STD, this methodology recommends using a single tran-sition with a condition statement that represents a union of the individ-ual logical events and conditions. Thus if three separate logical eventsE0, E1, and E2 cause a transfer to the same state, and each one has an as-sociated condition C0, C1, and C2, respectively, then a single transitioncan be defined, triggered by the condition (E0 && C0) || (E1 && C1) ||(E2 && C2). This example is depicted below.

Representation of a Generic Transition in an STD

The expression “E” represents the occurrence of logical event E

Transition Formed from the Union of Logical Events

Page 89: 03 Process Domain

261-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

2) Handling of a single logical event may be split between multipletransitions. The format of the table makes it clear that occurrences ofthe same logical event while in the same state may be differentiated bycondition statements which are evaluated at the time of the event. Foreach condition statement, a different next state may be specified, there-by implicitly defining multiple transition objects. A situation of thistype is depicted below for generic states, events, and conditions.

The Tx_Mgr process provides a good illustration of the use of conditionsto subdivide the handling of a single logical event. For instance, the ta-ble shows that in the Tx_status_wait state, the process may handle thereceipt of a Tx_Complete event in three different ways, depending onthe emptiness of the queue and the status of the medium.

Prdef.3.6.4 Assembling the STD

Once the event response table is defined, the STD can easily be assembled inOPNET’s Process Editor. First, the states must be created and assigned namesfrom the left column. The location of the states is not important, but depending onwhich transitions exist between them, certain arrangements can result in a cleanerlooking diagram. Also, abbreviated state names are usually used because the stateshave only a small display window.

Current State Logical Event Condition Action Next State

S0 E0 C0 None S1

C1 None S2

C2 None S3

Logical Event Handled by Multiple Transitionswith Differing Conditions

Page 90: 03 Process Domain

262-Prdef

Process Model Development Methodology Modeling Concepts

Once the states have been placed, transitions may be drawn between thembased on the methods presented in the previous section. When a transition iscreated, it has an empty condition statement, which is indicated graphically by asolid path (as opposed to a dashed path for transitions with non-empty conditions).Since variables have not been defined at this point and logical events are stilltreated conceptually (i.e., their specific method of implementation has not beendecided), macros should be used to express the condition statements. The macroscan be English-like text strings (no whitespace or special characters, exceptunderscore) that provide descriptive labels for the transitions. The underlyingdefinitions of the macros, which ultimately must implement the conditionstatements, can be provided in the process’ header block at a later time. Theresulting STD for the Tx_Mgr process appears below.

State Transition Diagram for Tx_Mgr Process

Page 91: 03 Process Domain

263-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Note that even when there is only one outgoing transition from a state, as in thecase of the state MEDIUM, that transition still has an associated condition. Thiscondition is not strictly necessary since the process could assume that the correctevent always occurs; however, including the condition allows the simulation toprovide a warning if for some reason an unanticipated event occurs and thecondition is false. This is preferable to falsely interpreting such an event.

Prdef.3.6.5 Application to Examples

This STD stage of the methodology was applied to the Tx_Mgr process of theMedia Access System in the previous sections in order to illustrate the constructionof an event response table and the derivation of the STD. This section presentscomplete tables and STDs for the remaining example models that were definedearlier in this chapter.

Pay Telephone System

The STD for this process reflects the serial nature of the user’s progressionthrough the various phases of call establishment. There is a loop between theCall_Estab and Disc_Ct_Down state, due to the fact that the phone user canalways add change to continue the call. Also, every state has a transition back tothe Idle state, reflecting the fact that the user may hang up the phone at any time.Most transitions are based on simple logical events; only the transition back toIdle from Disc_Ct_Down is driven by the union of two events (i.e., either canoccur to cause this transition to be traversed).

Transition Condition Macros for Tx_Mgr STD

Macro Meaning

NEW_MSG A new message has arrived

MEDIUM_USABLE The medium is usable (i.e., it has been unused for Gap_Time sec.)

TX_OK A transmission has completed successfully (no colli-sions)

Q_EMPTY There are no messages waiting to begin the transmis-sion process

TX_COLLIDED The current transmission has experienced a collision

BKOFF_OVER The backoff period has elapsed

Page 92: 03 Process Domain

264-Prdef

Process Model Development Methodology Modeling Concepts

Event Response Table for Pay Telephone Process

Current State Logical Event Condition Action Next State

Idle User_Pickup None None Deposit_wait

Deposit_wait User_Hangup None None Idle

User_Add_Fare None send indication of deposited amount to network

Tone_wait

Tone_wait User_Hangup None refund deposit Idle

Net_Dial_Tone None None Dial_wait

Dial_wait User_Hangup None refund deposit Idle

User_Tel_Num None relay telephone number to network

Connect_wait

Connect_wait User_Hangup None refund deposit; relay cancellation to network

Idle

Net_Connect None None Connect_Estab

Connect_Estab User_Hangup None relay cancellation to network

Idle

Net_Fare_Low None start timer for dis-connect

Disc_Ct_Down

Disc_Ct_Down User_Hangup None relay cancellation to network

Idle

Disconnect None relay cancellation to network

Idle

User_Add_fare None send indication of deposited amount to network

Connect_Estab

Page 93: 03 Process Domain

265-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Bank Teller System

The Auth process of the Bank Teller System has a flow that strongly resemblesthat of the pay telephone system process described above. This could be expectedsince in both cases, the process guides the user through a series of data entries inorder to get to a phase where a transaction is established. This process also offersthe possibility of cancellation by the user at any time, which is reflected by thetransitions to the Idle state from all other states

.

Event Response Table for Auth Process of Bank Teller System

Current State Logical Event Condition Action Next State

Idle Cust_Card_Ins None prompt user for ID number

ID_wait

ID_wait Cust_Id_Entered None send card info and ID to bank for authentication

Auth_wait

Cust_Trans_Cancel None return card Idle

Auth_wait Bank_Auth None prompt for trans-action type

Select_wait

Bank_Reject None return card Idle

Cust_Trans_Cancel None return card Idle

State Transition Diagram for Pay Telephone Process

Page 94: 03 Process Domain

266-Prdef

Process Model Development Methodology Modeling Concepts

The Withdrawal, Deposit, and Verify processes are very simple, requiring atmost one action to be taken by the user to progress to their final state. Note thatsince these processes destroy themselves when receiving an event in their finalstate, departing transitions need not be defined. Also, the Cust_Trans_Cancel eventalways leads to destruction of the process, and therefore is not implemented by anytransitions.

Select_wait Cust_Trans_Sel None invoke appropri-ate transaction process

Trans_compl_wait

Cust_Trans_Cancel None return card Idle

Trans_compl_wait Cust_Trans_Over None return card Idle

Cust_Trans_Cancel None return card Idle

Event Response Table for Withdrawal Processof Bank Teller System

Current State Logical Event Condition Action Next State

Amount_wait Cust_Amount_Entered None send request to bank

Auth_wait

Cust_Trans_Cancel None notify parent that transaction is over; destroy pro-cess

none (process is destroyed)

Event Response Table for Auth Process of Bank Teller System (Cont.)

Current State Logical Event Condition Action Next State

State Transition Diagram for Auth Process

Page 95: 03 Process Domain

267-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Auth_wait Bank_Trans_Approval None disburse cash;notify parent that transaction is over; destroy pro-cess

none (process is destroyed)

Cust_Trans_Cancel None notify parent that transaction is over; destroy pro-cess

none (process is destroyed)

Event Response Table for Deposit Process of Bank Teller System

Current State Logical Event Condition Action Next State

Amount_wait Cust_Amount_Entered None open deposit door Insert_wait

Cust_Trans_Cancel None notify parent that transaction is over; destroy process

none (process is destroyed)

Insert_wait Cust_Deposit_Inserted None close deposit door; notify parent that transaction is over; destroy process

none (process is destroyed)

Cust_Trans_Cancel None notify parent that transaction is over; destroy process

none (process is destroyed)

Event Response Table for Withdrawal Processof Bank Teller System (Cont.)

Current State Logical Event Condition Action Next State

State Transition Diagram for Withdrawal Process

Page 96: 03 Process Domain

268-Prdef

Process Model Development Methodology Modeling Concepts

Medium Access System

The Q_Mgr process is exceedingly simple, operating in a continuous one-stateloop driven by message arrivals. At each arrival, a decision is made about whetherto enqueue the message, or invoke the Tx_Mgr process; however the transition isalways back to the same state.

Event Response Table for Verify Process of Bank Teller System

Current State Logical Event Condition Action Next State

Balance_wait Bank_Balance_Rcvd None display balance; notify parent that transaction is over; destroy process

none (process is destroyed)

Cust_Trans_Cancel None notify parent that transaction is over; destroy process

none (process is destroyed)

Event Response Table for Q_Mgr Processof Medium Access System

Current State Logical Event Condition Action Next State

Message_wait New_Message Tx_Mgr is han-dling a message

Enqueue mes-sage

Message_wait

New_Message Tx_Mgr is idle Invoke Tx_Mgr to process mes-sage

Message_wait

State Transition Diagram for Deposit Process

State Transition Diagram for Verify Process

Page 97: 03 Process Domain

269-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

All transitions of the Medium_Mon process correspond to simple logical events.The Gap_Elapsed event has two separate conditions associated with it when theprocess is in the Gap_elapse_wait state, but in both cases, the next state isMedium_usable; therefore only one transition is necessary. The fact that differentactions that are to be performed for each condition should not necessarily lead tothe definition of multiple transitions. Even if transition executive statements areused to implement these actions, a single statement can include conditional clauses(i.e., if statements) within it to handle each case appropriately.

Event Response Table for Medium_Mon Processof Media Access System

Current State Logical Event Condition Action Next State

Medium_usable Busy_High None None Medium_busy

Medium_busy Busy_Low None start timer to measure gap

Gap_elapse_wait

Gap_elapse_wait Busy_High None reset gap timer Medium_busy

Gap_Elapsed Tx_Mgr is waiting for medium to become usable

notify Tx_Mgr of new status of medium

Medium_usable

Tx_Mgr is not wait-ing for medium to become usable

None Medium_usable

State Transition Diagram for Q_Mgr Process

Page 98: 03 Process Domain

270-Prdef

Process Model Development Methodology Modeling Concepts

The Tx_Mgr process is not described in this section since it already appears asan example in the previous section.

Data Link Control System

The Dispatcher process receives messages from the link and from the trafficsource. Messages from the link are acknowledgments sent by a destinationprocess. Regardless of the received message type, the process always returns to thesame state; this process is therefore another one-state loop, like the Q_Mgr of theMedia Access System.

Event Response Table for Dispatcher Processof Data Link Control System

Current State Logical Event Condition Action Next State

Message_wait Src_Message_Arrival channel manager exists for this channel

invoke channel man-ager process and pass message

Message_wait

channel manager does not exist for this channel

create channel man-ager and invoke with message

Message_wait

Ack_Arrival channel manager exists for this channel

invoke channel man-ager process and pass acknowledg-ment

Message_wait

channel manager does not exist for this channel

discard acknowledg-ment

Message_wait

State Transition Diagram for Medium_Mon Process

Page 99: 03 Process Domain

271-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

The Channel_Mgr process is simple in the sense that it has only two states;however there are six possible event-condition pairs departing from the Ack_waitstate. The transition to the Idle state represents the logical union of twoconditions, and the transition to the Ack_wait state represents four conditions.These conditions are not explicitly entered in the transition statements becausethey would be too long; instead a macro is used, as shown in the followingdiagram. Note that one of the transition’s condition statements could be replacedwith the expression default since it is the complement of the other. However, thisexpression should only be used after thorough verification that all transitionconditions are complementary; otherwise a missing transition that may have beenoverlooked in completing the event response table could be masked duringsimulation (i.e., no error can be reported).

State Transition Diagram for Dispatcher Process

Page 100: 03 Process Domain

272-Prdef

Process Model Development Methodology Modeling Concepts

Event Response Table for Channel_Mgr Processof Data Link Control System

Current State Logical Event Condition Action Next State

Idle Src_Message_Arrival None start acknowledg-ment timer; begin transmission

Ack_wait

Ack_wait Src_Message_Arrival None enqueue message for later transmis-sion

Ack_wait

Ack_Arrival no messages enqueued

reset timer Idle

at least one mes-sage enqueued

start acknowledg-ment timer; begin transmission

Ack_wait

Ack_Timeout fewer than Max_Attempts transmissions have been made

retransmit Ack_wait

Max_Attempts transmissions have been made and at least one message enqueued

discard current message; start acknowledgment timer; transmit next message

Ack_wait

Max_Attempts transmissions have been made and no messages enqueued

discard current message

Idle

Page 101: 03 Process Domain

273-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3.7 Stage 6: Specifying Process Actions

Process models perform actions to modify their state memory, communicatewith other modules, control their own timing, gather statistics, etc. Actions areperformed by statements called executives, which respect a C syntax. Executivescan make use of any C language operators and constructs, the process’ state,temporary, and global variables, and may include function calls to SimulationKernel procedures.

Prdef.3.7.1 Selecting Locations for Executive Statements to Represent Actions

Executive statements may be associated with states and with transitions. Thereare three types of locations in which executive statements can be placed to definethe actions of a process:

• Exit executives. Any number of Proto-C statements may be inserted inthis section of a state in order to model actions that take place immedi-ately after receiving a new event, and before evaluating transitions.

• Transition executive. A single line of Proto-C code may be associatedwith each transition in order to associate an action with a particulartransfer of control from one state to another. Note that this executivecan be a compound statement or a macro if a complex action is re-quired. Also, function calls may be included within this statement.

• Enter executives. Any number of Proto-C statements may be inserted inthis section of a state in order to model actions that take place after atransition, upon entering a new state.

State Transition Diagram for Channel_Mgr Process

defined as: (ACK_ARRIVAL && Q_EMPTY) || (ACK_TIMEOUT && LAST_ATTEMPT && Q_EMPTY)

defined as: SRC_MESSAGE_ARRIVAL || (ACK_ARRIVAL && !Q_EMPTY) || (ACK_TIMEOUT && !LAST_ATTEMPT) || (ACK_TIMEOUT && LAST_ATTEMPT && !Q_EMPTY)

Page 102: 03 Process Domain

274-Prdef

Process Model Development Methodology Modeling Concepts

These three sets of executives are executed without interruption in the orderpresented above whenever a process traverses a transition. The following diagramdepicts this execution flow:

The following set of guidelines can be used in deciding which type ofexecutive statements should implement actions:

• Transition support. Complex transition requirements sometimesmake it difficult to develop boolean expressions for the associated con-ditions. This is particularly true if transition conditions depend upon re-sults of a multistep algorithm. Since transition conditions are evaluatedafter the completion of the exit executives of a transition’s source state,these executives provide an appropriate location to place computationsthat support the evaluation of outgoing transitions.

A typical example of transition support in the exit executives is shownbelow. In this case, a stream interrupt has been received due to the ar-rival of a packet, and several outgoing transitions are possible. The con-ditions of the transition depend on values to be extracted from thepacket. To evaluate the transition conditions without using the exit ex-ecutives of the source state would require that the condition statementbe a procedure call where values would be extracted from the packetand computations would be performed to return a boolean result. Thistype of solution can be cumbersome and may require coordination be-tween procedures representing alternative conditions. Using the exitexecutives generally provides a simpler solution, with manipulation ofthe packet occurring in only one location.

Executive Statements

1

2

3

Page 103: 03 Process Domain

275-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

• Actions not directly related to transition conditions. When an eventoccurs, the process may be required to perform a number of actions thatare either unconditional, or that depend upon conditions that are notidentical to those of any of the outgoing transitions of the current state.In such cases, the transition executives are not an appropriate locationto implement these actions. In addition, since the actions are not relatedto the destination state that will eventually be chosen, the enter execu-tives of the destination states are not appropriate either. The exit exec-utives of the current state do provide the proper context for theseactions since they are executed prior to the evaluation of transitions.

As an example of this type of situation, consider a process that allocatesjobs to servers. The process has two states, one representing the casewhere servers are available, and the other the case where all servers are

Transition Support Statements in Exit Executives

/* Pkt has just been received: get it from input strm. */pk = op_pk_get (op_intrpt_strm ());

/* Assume pkt will be rejected, then test to override. */pk_accepted = OPC_FALSE;

/* Test if the packet has the expected protocol type. */op_pk_nfd_get (pk, “protocol type”, &pro_type);if (pro_type == expected_protocol_type)

{/* Extract the encapsulated data packet. */op_pk_nfd_get (pk, “data packet”, &data_pk);

/* Test that it is not too old to be accepted. */op_pk_nfd_get (pk, “orig_time”, &orig_time);if (op_sim_time () - orig_time <= MAX_DATA_AGE)

pk_accepted = OPC_TRUE;}

Page 104: 03 Process Domain

276-Prdef

Process Model Development Methodology Modeling Concepts

busy. When a new job arrives, say in the form of a packet, the processmust enqueue the job with all other jobs that are waiting for service;then if a server is available, it may invoke the server to begin processingthe job. If the invoked server happens to be the last one available, thenthe process must move to the state that indicates saturation of servers;otherwise it can self-transition back to the state that indicates serversare still available. However, the action of queueing the packet that rep-resents the job is independent of which transition will be followed.Therefore, this action should be performed in the exit executives of theservers_available state. Relevant parts of this example process ap-pear below:

Note that conditional actions may be implemented within the exit exec-utives as well by making use of C language if statements. For example,if the queue had a limited job-holding capacity, the process could testwithin the exit executives that there is sufficient room in the queue, pri-or to attempting to insert the job packet.

Use of Exit Executives to Implement Actions Independent of Transitions

/* Test if the event is a new job pkt that has arrived. *//* This logical event is the only one implemented as a *//* interrupt, so simply test the interrupt type. */if (op_intrpt_type () == OPC_INTRPT_SELF)

{/* Place the job pkt in the job queue; this is done *//* whether or not the system becomes saturated. */new_job = op_pk_get (JOB_STREAM);op_subq_pk_insert (JOB_QUEUE, new_job, OPC_QPOS_TAIL);

/* Increment the number of busy servers. */num_busy_servers++;

/* Invoke a server to begin processing the job. */start_new_job ();}

Page 105: 03 Process Domain

277-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

• Actions and transitions dependent on identical conditions. Certainactions performed in response to an event are conditional on additionalprerequisites, as explained earlier. This is also true of transitions. Incases where exactly the same conditions are required for a transitionand for an action, the action may be implemented in the executive state-ment of the transition, provided that: (1) the action is not required tocomplete before the transitions are evaluated; and (2) the action is notalso performed for all other transitions sharing the same destinationstate; and (3) the action is conveniently represented in the single lineprovided for a transition executive. Note, with regard to the third re-striction, that by using macros or procedure calls, any set of actions canbe represented in a transition’s executives; however it may be moreconvenient to implement certain complex actions in the exit executivesof the current state.

The principal advantage of implementing actions in transition execu-tives, when possible, is that the action and the transition are closely as-sociated and that this association is visible in the process modeldiagram. The tight coupling of the action and the transition show clear-ly that the action is not associated solely with the source state or withthe destination state, but with the specific transfer of control betweenthe two. A second advantage, though less important, is that the condi-tion shared by the action and the transition need not be evaluated twice;depending on the complexity of the condition, this could result in sig-nificant performance differences. Finally, a third advantage of thistechnique is that expressing the condition in only one location simpli-fies maintenance of the process’ logic.

Consider as an example the Tx_Mgr process defined in an earlier sectionof this chapter. Suppose that as part of its performance monitoring re-quirements, the process must keep track of the number of occasions onwhich arriving messages are immediately processed, rather than havingto wait for the medium to become available. The submission of a newmessage corresponds to the two transitions departing from the Idlestate. However, only the transition leading to the Tx_status_waitstate corresponds to the specific condition of interest, which is the im-mediate usability of the medium. Since there is no requirement for thecounter to be updated prior to evaluation of transition conditions, thisaction may be performed in the transition’s executive statement, asshown in the following STD fragment.

Page 106: 03 Process Domain

278-Prdef

Process Model Development Methodology Modeling Concepts

• Actions associated with entry into a state. Actions that are performedeach time that a state is entered, regardless of which transition was tra-versed to arrive there, should be associated directly with that state rath-er than any of the transitions or source states. The appropriate locationfor such actions to be implemented is the enter executives of the stateof interest.

The Tx_Mgr model provides a good example for this case as well. TheTx_status_wait state is responsible for determining if an ongoingtransmission is successful or affected by a collision. Suppose that in or-der to detect the end of its own transmission, the process sets a timerwhen the transmission begins; the duration of the timer is exactly equalto the transmission time of the packet. The Tx_status_wait state is en-tered via transitions from several states, including a transition from it-self. However, regardless of the reason for entering this state (e.g.,retransmission, first-time transmission without waiting, first-timetransmission having waited, etc.), the action of setting the transmissiontimer must always be performed. Therefore, the enter executives of theTx_status_wait state provide an appropriate location for this action.The following diagram depicts use of the enter executives in this exam-ple.

Use of Transition Executive to Implement an Action

The number of “unblocked” packets is incremented only if this transition takes place

Page 107: 03 Process Domain

279-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Note that there are ambiguous cases, where a single transition leads intoa state and there is an action to be performed that can be associated witharrival into that state. In such cases, the transition executive and the en-ter executives of the state provide equally valid locations for this actionto be implemented.

• Actions associated with a non-singular subset of transitions. If anaction is to be performed subject to the union of the conditions of morethan one outgoing transition, but not the complete set of outgoing tran-sitions, then the exit executives do not provide a good location to im-plement the action. This is due to the fact that the exit executivescontain logic that is common to all outgoing transitions. Similarly, if asubset (of more than one) of the transitions arriving at a state corre-spond to the performance of an action, the enter executives of that stateshould not be used to implement the action. However, there are two oth-er appropriate options for each of these cases: (1) if the action can berepresented in a compact form and there are a relatively small numberof transitions, then the executive statements of these transitions can beused to represent the action; (2) a forced state can be created to imple-ment the action in its enter executives and the applicable transitions canbe rerouted to pass through that state.

Implementing the actions in the transitions’ executives is the moststraightforward solution to this problem. In addition, this has the advan-

/* A new transmission is beginning; time *//* it with a self interrupt. */start_transmission_timer ();

Use of Enter Executives for ActionsAssociated Exclusively with State Entry

Page 108: 03 Process Domain

280-Prdef

Process Model Development Methodology Modeling Concepts

tages of introducing no additional unforced states. However, since theaction is implemented in several locations (i.e., on each transition in thesubset), maintaining it may require additional effort. Thus, if this solu-tion is chosen, the action should always be implemented by means of amacro or function call, so that all changes that may need to be made canbe made in one place. The following diagrams illustrate the use of thetransition executive approach for both outgoing and incoming transi-tions

.

The executive “E” does not occur if this transi-tion is taken

The executive “E” does not occur if this transi-tion is taken

Subset of Incoming Transitions Performing the Same ActionImplemented with Transition Executives

Subset of Outgoing Transitions Performing the Same ActionImplemented with Transition Executives

Page 109: 03 Process Domain

281-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Using a forced state to contain the action can be useful if the action’simplementation is complex. This approach presents the advantage thatthe executive statements are located in only one place. However, it hasthe disadvantage that it requires an additional element in the STD. Also,in the outgoing transition case, the condition statements must be dupli-cated, first in order to form their union on the transition to the forcedstate, and then to separate control flow to the multiple destinationstates. The following diagrams illustrate use of a forced state for bothcases:

Subset of Outgoing Transitions Performing the Same ActionImplemented by Redirecting through a Forced State

Action is implemented in forced state

Action does not occur if this transition is taken

Subset of Incoming Transitions Performing the Same ActionImplemented by Redirecting through a Forced State

Action is implemented in forced state

Action does not occur if this transition is taken

Page 110: 03 Process Domain

282-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.7.2 Developing Action Statements

In order to perform simulations of a process, actions must ultimately bespecified in a form that can be executed within the OPNET simulationenvironment. Specifying actions on a level that can be executed is referred to asimplementation of the actions. Executive statements that constitute an action’simplementation are required to obey the syntax of the C language, and may makeuse of any of its operators and constructs. In addition, executive statements areoften based on a library of C functions known as OPNET Kernel Procedures orKPs.

Before proceeding to actual implementation, it is useful to develop a logicalspecification for a process’ actions. A logical specification is concerned with thebehavior, timing, and effects of an action, but not with the details of how the actionis actually carried out. By first developing the process’ actions on an abstract level,the developer may more easily manipulate the action statements, noticecommonality between them, and apply the placement guidelines formulated in theprevious section.

Determining the Logical Actions of a Process

In an earlier section pertaining to this development methodology, an event-response table was generated. One of the columns of this table contained actionsthat would be performed as a result of a logical event taking place and a conditionbeing met. These actions are logical actions of the process since they presented inan abstract manner without implementation details.

During the development stage where the event-response table is constructed,the main objective is to outline the control flow of the process by specifying thetransitions between states. Actions are included in the table because they oftendepend on the same events and conditions as transitions and therefore can easily becaptured simultaneously. Thus, at this stage of development, the event responsetable should be revisited as a useful starting point for determining the process’logical actions. Actions taken from the table should be given consistent high-levelnames and placed within the process model according to the guidelines of theprevious section. Note that the structure of the table facilitates the application ofthese guidelines as summarized by the following set of statements:

• An action should be placed in the exit executives of a state if it appearsin all rows for which that state occupies the “Current State” column,since it therefore applies to all transitions.

• An action should be placed in the enter executives of a state if it appearsin each row that identifies the state as the destination of a transition (i.e.,the “Next State” column contains the state’s name).

Page 111: 03 Process Domain

283-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

• An action should be placed in the executive statements of the transi-tions that share the same rows, if neither of the two previous criteria aresatisfied.

It is appropriate that the process’ event response table should serve as a basisfor specifying actions since actions are performed in reaction to the occurrence oflogical events. However, the event-response table may not always include acomplete specification of all actions that a process is required to perform. Adiscrepancy may arise from the fact that the combinations of events and conditionsthat appear in the table do not correspond directly to the conditions under whichcertain actions are performed. As a result, certain action specifications may beoverlooked. Note however, that since the transitions departing from each state arerequired to form a complementary set (at least one must be true), it should bepossible to associate all actions with one or more of the conditions; in the casewhere a condition supersedes the condition required for an action, the action canbe considered to incorporate an additional restrictive clause (e.g., an “if”statement); in the case where an action is dependent on a condition that overlapsseveral conditions associated with transitions, the action can simply appear inmultiple rows. Therefore all actions can and should be represented within theevent-response table.

The following subsection of an event-response table illustrates the specificationof actions that are subject to conditions that do not identically match those of thetransitions. The action “A” partially overlaps two transitions and is subject to thecondition (E0 && C0 && C0’) || (E1 && C1 && C1’); the action “A2” is supersettedby the third transition and depends on the condition (E2 && C2 && C2’).

Logical actions should be entered into the process model executive areassimply as high-level names. Later, during the implementation phase, these macroscan be fully defined within the header block, or replaced in-line by actualimplementation statements. The action statements of the Tx_Mgr process(described as part of the Media Access System example) are shown below as anexample.

Current State Logical Event Condition Action Next State

S0 E0 C0 if C0’ then A S1

E1 C1 if C1’ then A S1

E2 C2 if C2’ then A2S1

Page 112: 03 Process Domain

284-Prdef

Process Model Development Methodology Modeling Concepts

Implementation of Actions

In order for a process to become executable as part of a simulation, each of thelogical actions associated with its states and transitions must be expressed in aform that can be understood by the OPNET simulation environment. Generally,each logical action is decomposed into a series of statements. The statements mayappear directly in the location where the action was placed originally; they mayconstitute a macro defined in the process’ header block; or they may be placed in afunction that is called from the location of the action.

Regardless of their placement, implementation statements must respect thesyntax of the C language. Many implementation statements consist of calls to KPsdefined in the Simulation Kernel. Other common statements are ordinary Clanguage operations such as variable assignments, if statements, or for loops.There are no general guidelines for designing the content of implementationstatements since this depends to a significant extent on the nature of theapplication. Some common examples of the implementation of actions areprovided in the Framework chapter of this manual, organized according to the type

Begin_Message_Transmission occurs for every transition into the Tx_Status_Wait state and there-fore appears in enter executives.

Abort_Transmission action oc-curs whenever the Backoff_wait state is entered, but since there is only one incoming transition it can appear on the transition. (It could also have been placed in enter exec-utives.)

Begin_Backoff action occurs each time that Backoff_wait is entered and so appears in enter executives; could also have appeared on incoming transition since there is only one.

Logical Actions of the Tx_Mgr Process

Page 113: 03 Process Domain

285-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

of event that the actions are designed to respond to. In addition, the SimulationKernel manual provides general descriptions of how to use the capabilitiesprovided by KPs and numerous examples of process action statements.

Implementing Event Suppression

Implementation of logical actions that are described at a high level often entailsthe specification of accompanying peripheral actions, such as updating statevariables or reporting statistics. One particular set of peripheral actions is requiredin most models to support the proper operation of the STDs transitions by ensuringthat only the feasible events of a process can occur in each state.

In order to develop the event-response table of a process, the notion of eventfeasibility was introduced earlier in this chapter, whereby each logical event of aprocess was categorized as feasible, infeasible, or suppressed with respect to eachstate. Suppressed events are those that could normally occur while the processoccupies a particular state, but for which special disabling measures have beentaken. Since the Simulation Kernel has no knowledge of which events should bewithheld, it is the responsibility of a process to autonomously implement eventsuppression at appropriate times.

The most straightforward and systematic way to implement event suppressionis to place a statement in the enter executives of each state to specifically disableevents that should be suppressed while the process occupies that state; in the exitexecutives a single statement can be placed to enable all events. Since the samelogical events are likely to be suppressed in several different states, it is usuallymost efficient to use macro expressions to perform these actions and to later definetheir exact implementation in the header block. An illustration of this approachappears below for the Tx_Mgr example process.

Page 114: 03 Process Domain

286-Prdef

Process Model Development Methodology Modeling Concepts

The underlying mechanism that is used to implement the event suppressionmacros is often based on the KPs op_intrpt_disable() and op_intrpt_enable(). Referto the Modeling Framework chapter of this manual for more information on eventsuppression provided by the Kernel. In situations where multiple processesgenerate logical events for each other via invocation, event suppression may becontrolled by semaphores. For example, Tx_Mgr receives New_Message eventswhen the Q_Mgr process invokes it as a result of having received a new message;suppressing this event for Tx_Mgr therefore should be implemented by notifyingthe Q_Mgr process rather than using a Kernel service. A semaphore residing inmemory shared by the two processes would provide appropriate support for thismechanism.

Event Suppression Statements for Tx_Mgr Process

This statement reverses the effect of any event suppression; an identical statement appears in the exit executives of each state.

If required for a state, event suppression state-ments appear in the enter executives.

Page 115: 03 Process Domain

287-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Implementing Hierarchical Process Invocation

One of the approaches proposed by this methodology suggests the use ofhierarchically related dynamic processes to reduce the complexity of individualmodels. The Bank Teller System provides an applied example of this techniquewhere the process Auth uses the child processes Withdrawal, Deposit, andVerify to perform tasks.

When it is appropriate for a child and parent process to executeasynchronously, then the simple use of the KP op_pro_invoke() provides thenecessary functionality. As soon as the child process completes an invocation, theparent process can resume execution. However, when the desired timingrelationship is that the parent process should not resume execution until the childprocess has reached a certain state, then additional mechanisms are required.Because it may take an arbitrary amount of time and events for the child process toachieve completion of the task, it generally bears the responsibility for notifyingthe parent process when it may resume. The mechanism for this notification isusually also the KP op_pro_invoke() since it has an immediate effect. If non-immediate notification is sufficient, then the semaphores implemented in sharedmemory between the processes may be used as well. The following diagramprovides an example of the Proto-C statements that may be used to implement thistype of configuration, which is referred to as a synchronous hierarchical executionof the child process, since it does not allow the parent process to executeasynchronously to the child process.

Page 116: 03 Process Domain

288-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.7.3 Application to Examples

Because it would be cumbersome to directly include the full specifications ofthe actions for the processes of the four example systems that have been usedthroughout this chapter, these have been provided only in electronic form. The filescontaining these models are located in the pro_meth directory of the OPNETstandard models directory models/std. Please refer to these models as examples

Synchronous Hierarchical Execution ofWithdrawal Process by Auth Process

The parent process blocks after completing the exit executives of this state and will not resume until the child process invokes it (assuming other interrupts are not feasible).

The child process completes the task for which it was invoked when it reaches the exit execu-tives of this state. It therefore notifies the par-ent process and destroys itself.

Page 117: 03 Process Domain

289-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

of complete process implementations that result from this methodology. Themodels have the same names used in this chapter and may be examined by loadingthem into OPNET’s Process Editor.

Prdef.3.8 Stage 7: Selecting an Initial State

An earlier section in this chapter presents four techniques for STDinitialization using the various combinations of initial states and begin simulationinterrupts. While all four methods are possible and may be useful under certaincircumstances, this methodology suggests that only the two techniques that requirebegin simulation interrupts should be used. The advantages of requiring a beginsimulation interrupt are the following:

• Because begin simulation interrupts happen before all other types inter-rupts, the process can position itself in a standard manner for the han-dling of all mainstream interrupts. Namely, when a mainstreaminterrupt occurs, the process is always poised to begin the exit executivestatements of an unforced state.

• Processes can be depended upon to have completed all initialization ac-tivities by the time the first mainstream events occur. This may be im-portant if processes depend on each other being in an initialized state(e.g., processes that share memory usually depend on one process to setthe memory contents to meaningful values before others attempt to ac-cess it).

• By standardizing on use of begin simulation interrupts, it is alwaysknown that queue and processor objects should be configured to enabledelivery of these interrupts (coordination with regard to this issue be-tween the node and process domains is not otherwise enforced).

The two possibilities that remain are for the initial state to be forced orunforced. Since the objective is to have the first mainstream interrupt be handled inthe exact same manner as in steady-state, use of an unforced state implies use ofone of the principal states of the STD, already defined during earlier development.An additional unforced state should not be created, for it would require specialtransitions to handle the occurrence of the first mainstream interrupts, and thisunnecessarily adds complexity and redundancy to the model. However, in mostcases, principal states of the STD are designed to be entered repeatedly by theprocess as new events occur. Therefore, in order to avoid repeated execution ofinitialization actions throughout the life of a process, the initial state should beunforced only if the process is not required to perform any initialization actions.

Page 118: 03 Process Domain

290-Prdef

Process Model Development Methodology Modeling Concepts

The second possibility is to create a new forced state to act as the initial state.Since a begin simulation interrupt is expected, the process can performinitializations and immediately position itself in one of the unforced states of themodule. In general, each process model has a particular unforced state that makessense to use for this purpose, but this can only be determined based on thesignificance assigned to each state. Note in addition, that the enter executives ofthis unforced state will be executed at initialization time; therefore any actionstherein that should not be performed at initialization time should be moved to theappropriate incoming transitions.

Use of Unforced State as Initial State

This state should contain no ini-tialization actions since it may be reentered repeatedly.

Use of Forced State as Initial State

This state contains initializations that are executed only once, when the process is created.

Actions associated with entry of the follow-ing state, but unrelated to initialization, should appear in the executives of the oth-er transitions arriving at the state.

Page 119: 03 Process Domain

291-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Prdef.3.8.1 Application to Examples

As indicated earlier, the example systems used throughout this chapter areprovided in electronic form with the OPNET software. Full process modeldiagrams with initial state indicators are therefore not included here; however, thefollowing table summarizes the choices made with regard to the initial state foreach example process.

Note that for several of the processes, the solution requiring a new, forcedinitial state was selected to allow the possibility of later specifying initializationactions. This is due to the fact that other states that are candidates for being theinitial state may be entered multiple times by the process.

Initial States Selected for Example Processes

Example System Process Strategy Reason for Selection

Pay Telephone Pay_Phone use Idle as initial state

Idle is the natural initial position of the process since no transaction is assumed to be in progress at time zero; no initialization statements are required that do not also need to be executed each time that Idle is reentered

Bank Teller Auth use of Idle as initial state

same as above

Deposit use of Amount_wait as initial state

Amount_wait state is never re-entered since process is destroyed

Withdrawal use of Amount_wait as initial state

Amount_wait state is never re-entered since process is destroyed

Verify use of Balance_wait as Initial state

Balance_wait state is never re-entered since process is destroyed

Medium Access Q_Mgr use of new, forced Init state

one-time only initializations are required (e.g., creation of other processes) and only other state is reentered

Tx_Mgr use of new, forced Init state

one-time only initializations may be needed, and other states may be entered multiple times

Medium_Mon use of new, forced Init state

same as above

Data Link Control Dispatcher use of new, forced Init state

one-time only initializations are required (e.g., creation of process list) and only other state is reentered

Channel_Mgr use of new, forced Init state

one-time only initializations may be needed, and other states may be entered multiple times

Page 120: 03 Process Domain

292-Prdef

Process Model Development Methodology Modeling Concepts

Prdef.3.9 Summary of Development Stages

This section summarizes the stages of the process model developmentmethodology that has been presented in this chapter.

Stage 1: Context Definition

Step 1: Identify interdepen-dent modules

The modules with which the system communicates or shares information are determined and named.

Step 2: Select communication mechanisms with interdepen-dent modules

For each module identified in previous step, the nature of the dependency is examined and an appropriate communication mechanism is chosen.

Step 3: Develop diagram of system and interdependent modules

The interdependent modules and the system of inter-est are placed in a diagram together with paths repre-senting their interfaces. The interfaces are assigned names.

Stage 2: Process-Level Decomposition

Step 1: Determine which pro-cess decomposition tech-nique is applicable to the system

The activities of the system are analyzed to determine appropriate ways of separating them into simpler sets of actions. Single processes may be used to represent an entire subsystem, or three other methods may be used: (1) dynamic creation of a variable number of processes; (2) cooperating, asynchronous processes; (3) hierarchical organization to spread complexity over multiple levels. These techniques may also be combined.

Step 2: If a multi-process implementation is chosen, identify the areas of responsi-bility assigned to each pro-cess

Specific areas of the system’s activity that are assigned to each process are identified. Representa-tive process names are assigned.

Step 3: For multi-process implementations, determine circumstances of process cre-ation and which will be root

A root process is selected among those defined ear-lier, based on property of permanent existence and role as event dispatcher. Conditions under which other processes are created are specified.

Page 121: 03 Process Domain

293-Prdef

Modeling Concepts Process Model Development MethodologyP

rocess D

om

ain

Stage 3: Enumeration of Events (per Process)

Step 1: Define logical events of each process

The activities of the system and the particular role of the process within the system, as well as interactions with other processes and modules are analyzed to determine the circumstances that require the process to be invoked. The occurrence of each such circum-stance is given a name and classified as a logical event.

Step 2: Select event imple-mentation methods

For each logical event identified in the previous step, an appropriate OPNET event type is selected based on the source of the logical event and the type of data that is associated with it.

Stage 4: State-Level Decomposition (per Process)

Step 1: Select states of the process

Identify high-level modes of the process and assign names to them. These are the states of the process.

Step 2: Verify that the selected set of states match criteria

States should respect the following:1) a state corresponds to particular sequences

of events having occurred2) events are handled in a specific manner as a

result of being located in a particular state3) selected states are mutually exclusive and

complementary4) each state should represent a blocking point

for the process

Stage 5: STD Development (per Process)

Step 1: Determine feasible events of each state

Each logical event defined in stage 3 is mapped against each state defined in stage 4; each state-event pair is categorized as infeasible, suppressed, or feasi-ble. Feasible events are those that are expected to occur when the process is in the state of interest.

Step 2: Construct event-response table

The process’ response to each feasible state-event pair is described in the form of a table; each row of the table specifies a state-event combination, an addi-tional condition, and an action and state change that are performed if the condition is met.

Page 122: 03 Process Domain

294-Prdef

Process Model Development Methodology Modeling Concepts

Step 3: Define transitions Transitions are designed by combining conditions and events that allow transfer of control between the same pairs of states.

Step 4: Assemble STD The states defined in stage 4 are graphically placed in the Process Editor; transitions are created to link the states, and conditions are assigned according to the results of step 3.

Stage 6: Specification of Process Actions (per Process)

Step 1: Review specification of the process’ logical actions for completeness

The event-response table is revisited to ensure that the logical action specifications are complete.

Step 2: Place abstract specifi-cation of the logical actions within the STD

Pseudo-code or macro statements representing these logical actions are placed within the STD. State enter and exit executives, and transition executives are used depending on basic rules:

1) exit executives contain actions common to all outgoing transitions;

2) enter executives contain actions common to all incoming transitions;

3) transition executives contain actions associ-ated subsets of outgoing/incoming transi-tions.

Step 3: Specify event sup-pression statements

Macro statements are placed in each state’s enter executives to disable events classified as “suppressed” in stage 5. Statements are placed in each state’s exit executives to enable all events.

Step 4: Define or replace macros and pseudo-code

Each macro or pseudo-code statement developed in stage 3 is replaced by or defined to be a series of exe-cutable statements, using general C language con-structs and OPNET Kernel Procedures.

Stage 7: Initial State Designation (per Process)

Step 1: Select initial state An initial state is selected based on the assumption that the process will be invoked once specifically for initialization purposes. A new forced state is created to act as initial state if one-time only initialization actions are required; otherwise one of the existing unforced states is selected as initial state based on the appro-priate “default” or initial mode of the process.

Stage 5: STD Development (per Process)