AMX 86 User's Guide - KADAK Products Ltd. · PDF fileAMX 86 User's Guide KADAK i TECHNICAL...

410
® AMX 86 User's Guide First Printing: November 1, 1990 Last Printing: March 1, 2005 Copyright © 1990 - 2005 KADAK Products Ltd. 206 - 1847 West Broadway Avenue Vancouver, BC, Canada, V6J 1Y5 Phone: (604) 734-2796 Fax: (604) 734-8114

Transcript of AMX 86 User's Guide - KADAK Products Ltd. · PDF fileAMX 86 User's Guide KADAK i TECHNICAL...

®

AMX™ 86 User's Guide

First Printing: November 1, 1990Last Printing: March 1, 2005

Copyright © 1990 - 2005

KADAK Products Ltd.206 - 1847 West Broadway AvenueVancouver, BC, Canada, V6J 1Y5

Phone: (604) 734-2796Fax: (604) 734-8114

AMX 86 User's Guide KADAK i

TECHNICAL SUPPORT

KADAK Products Ltd. is committed to technical support for its software products. Ourprograms are designed to be easily incorporated in your systems and every effort hasbeen made to eliminate errors.

Engineering Change Notices (ECNs) are provided periodically to repair faults or toimprove performance. You will automatically receive these updates during the product'sinitial support period. For technical support beyond the initial period, you must purchasea Technical Support Subscription. Contact KADAK for details. Please keep us informedof the primary user in your company to whom update notices and other pertinentinformation should be directed.

Should you require direct technical assistance in your use of this KADAK softwareproduct, engineering support is available by telephone, fax or e-mail. KADAK reservesthe right to charge for technical support services which it deems to be beyond the normalscope of technical support.

We would be pleased to receive your comments and suggestions concerning this productand its documentation. Your feedback helps in the continuing product evolution.

KADAK Products Ltd.206 - 1847 West Broadway AvenueVancouver, BC, Canada, V6J 1Y5

Phone: (604) 734-2796Fax: (604) 734-8114e-mail: [email protected]

ii KADAK AMX 86 User's Guide

Copyright © 1990-2005 by KADAK Products Ltd.All rights reserved.

No part of this publication may be reproduced, transmitted, transcribed,stored in a retrieval system, or translated into any language or computerlanguage, in any form or by any means, electronic, mechanical,magnetic, optical, chemical, manual or otherwise, without the priorwritten permission of KADAK Products Ltd., Vancouver, B.C., CANADA.

DISCLAIMER

KADAK Products Ltd. makes no representations or warranties withrespect to the contents hereof and specifically disclaims any impliedwarranties of merchantability and fitness for any particular purpose.Further, KADAK Products Ltd. reserves the right to revise thispublication and to make changes from time to time in the contenthereof without obligation of KADAK Products Ltd. to notify anyperson of such revision or changes.

TRADEMARKS

AMX in the stylized form and KwikNet are registered trademarks of KADAK Products Ltd.AMX, AMX/FS, InSight, KwikLook and KwikPeg are trademarks of KADAK Products Ltd.Microsoft, MS-DOS and Windows are registered trademarks of Microsoft Corporation.All other trademarked names are the property of their respective owners.

AMX 86 User's Guide KADAK iii

AMX 86 USER'S GUIDETable of Contents

PageSection 1: System Description

1. AMX Overview 1

1.1 Introduction ........................................................................................ 11.2 Glossary ............................................................................................. 31.3 AMX Nomenclature ........................................................................... 7

2. General AMX Operation 9

2.1 Introduction to Multitasking ............................................................... 92.2 AMX Operation ................................................................................. 112.3 AMX Managers .................................................................................. 172.4 Starting AMX ..................................................................................... 20

3. Application Tasks 25

3.1 Task Creation ..................................................................................... 253.2 Task States ......................................................................................... 273.3 Starting a Task .................................................................................... 293.4 Task Priority ....................................................................................... 303.5 Task Execution ................................................................................... 313.6 Task and Event Synchronization ........................................................ 323.7 Task Timing ....................................................................................... 343.8 Ending a Task ..................................................................................... 353.9 Message Passing ................................................................................. 363.10 Restart Procedures ............................................................................ 423.11 Exit Procedures ................................................................................ 443.12 Task Enhancements .......................................................................... 46

4. Interrupt Service Procedures 49

4.1 The Processor Interrupt Facility ......................................................... 494.2 ISPs for External Interrupts ................................................................ 514.3 Nested Interrupts ................................................................................ 564.4 ISP/Task Communication .................................................................. 574.5 Task Error Traps ................................................................................ 604.6 Non-Maskable Interrupt ..................................................................... 644.7 Special Interrupts ............................................................................... 654.8 Vector Table Initialization ................................................................. 68

5. AMX Timing Control 69

5.1 Introduction to Timing Facilities ........................................................ 695.2 AMX Clock Handler and Kernel Task ............................................... 715.3 Interval Timers and Timer Procedures ............................................... 755.4 Task Time Slicing .............................................................................. 795.5 Time/Date Manager ............................................................................ 82

iv KADAK AMX 86 User's Guide

AMX 86 USER'S GUIDETable of Contents (Cont'd.)

PageSection 1: System Description (Cont'd.)

6. AMX Semaphore Manager 91

6.1 Introduction ........................................................................................ 916.2 Semaphore Use ................................................................................... 936.3 Semaphore Applications .................................................................... 97

7. AMX Event Manager 103

7.1 Introduction ........................................................................................ 1037.2 Event Synchronization ....................................................................... 1057.3 Event Flag Application ....................................................................... 107

8. AMX Message Exchange Manager 111

8.1 Introduction ........................................................................................ 1118.2 Message Exchange Use ...................................................................... 1138.3 Message Exchange Application ......................................................... 115

9. AMX Buffer Manager 119

9.1 Introduction ........................................................................................ 1199.2 Buffer Pool Use .................................................................................. 1209.3 Buffer Applications ............................................................................ 1229.4 Buffer Manager Caveats ..................................................................... 124

10. AMX Memory Manager 125

10.1 Introduction ...................................................................................... 12510.2 Nomenclature ................................................................................... 12710.3 Memory Allocation .......................................................................... 12810.4 Private Memory Allocation .............................................................. 13010.5 Memory Assignment ........................................................................ 13110.6 Memory Assignment Procedure ....................................................... 132

11. AMX Circular List Manager 135

11.1 Circular Lists .................................................................................... 13511.2 Circular List Use .............................................................................. 13611.3 Circular List Structure ...................................................................... 137

AMX 86 User's Guide KADAK v

AMX 86 USER'S GUIDETable of Contents (Cont'd.)

PageSection 1: System Description (Cont'd.)

12. AMX Linked List Manager 139

12.1 Introduction ...................................................................................... 13912.2 Linked Lists ...................................................................................... 14012.3 Linked List Use ................................................................................ 142

13. Advanced Topics 147

13.1 Fatal Exit .......................................................................................... 14713.2 User Error Procedure ........................................................................ 15013.3 Task Scheduling Hooks .................................................................... 15213.4 Abnormal Task Termination ............................................................ 15313.5 Task Suspend/Resume ...................................................................... 15813.6 Breakpoint Manager ......................................................................... 159

Section 2: System Construction

14. AMX System Configuration 163

14.1 System Configuration Module ......................................................... 16314.2 System Configuration Builder .......................................................... 16414.3 Using the Builder ............................................................................. 16614.4 System Parameter Definition ............................................................ 17014.5 AMX Object Allocation ................................................................... 17314.6 Restart/Exit Procedure Definition .................................................... 17614.7 Task Definition ................................................................................. 17814.8 Timer Definition ............................................................................... 18114.9 Semaphore Definition ...................................................................... 18314.10 Event Group Definition .................................................................. 18514.11 Message Exchange Definition ........................................................ 18714.12 Buffer Pool Definition .................................................................... 18914.13 Breakpoint Manager Definition ...................................................... 191

Section 3: Programming Guide

15. AMX Service Procedures 193

15.1 Introduction ...................................................................................... 19315.2 Summary of Services ....................................................................... 194

16. AMX 86 Procedures 201

16.1 Introduction ...................................................................................... 201 Alphabetic List of Procedures .......................................................... 205

vi KADAK AMX 86 User's Guide

AMX 86 USER'S GUIDETable of Contents (Cont'd.)

PageAppendices

A. AMX 86 Reserved Words 347

B. AMX 86 Error Codes 349

C. Configuration Generator Specifications 353

C.1 Introduction ....................................................................................... 353C.2 User Parameter File Specification ..................................................... 354C.3 System Configuration Template ........................................................ 359C.4 Porting the Configuration Generator ................................................. 362

D. AMX 86 Structure and Constant Definitions 365

D.1 AMX C Structures and Constants ..................................................... 365D.2 AMX Assembler Structures and Constants ....................................... 373

E. AMX 86 Assembler Interface 381

Index Index-1

AMX 86 USER'S GUIDETable of Figures

PageSection 1: System Description

Figure 2.2-1 AMX General Operation ..................................................... 12Figure 3.2-1 AMX Task State Diagram ................................................... 28Figure 3.9-1 Message Transmission ......................................................... 38Figure 3.9-2 Message Reception .............................................................. 39Figure 5.4-1 Simple Time Slicing ............................................................ 80Figure 5.4-2 Interrupted Time Slicing ...................................................... 80Figure 5.5-1 Time/Date Format Specification Parameter ........................ 89Figure 12.2-1 Doubly Linked Lists ........................................................... 141

Section 2: System Construction

Figure 14.2-1 AMX Configuration Building Process .............................. 165Figure 14.3-1 Configuration Manager Screen Layout .............................. 167

Appendices

Figure C.2-1 User Parameter File ............................................................. 354

AMX Overview KADAK 1

1. AMX Overview

1.1 IntroductionThe AMX™ Multitasking Executive provides a simple solution to the complexity of real-time multitasking. AMX supervises the orderly execution of a set of application programmodules called tasks. AMX allows the system designer to concentrate on the applicationwithout becoming overly concerned about the multitasking aspects of the solution.

AMX is based on concepts proven over the past thirty years in minicomputer andmicroprocessor applications in process control environments. AMX simplifies real-timesoftware implementation by providing the system designer with a well-defined set ofrules.

AMX operates in real mode on any Intel® 8086 compatible microprocessor systemincluding the 8086/8088, 80186/188, 80286, Intel386™, Intel486™ and Pentium™. It canalso be used on the VAutomation 24-bit Turbo86 processor family. Unless otherwisespecified, references in this manual to 8086 infer all of the other processors as well.

AMX gives the system designer complete flexibility and control over the microcomputerconfiguration employed. A real-time clock must be provided in the configuration ifAMX timing facilities are to be employed.

AMX provides a wide variety of services from which the real-time system designer canchoose. Many of the services are optional and, if not used, will not even be present inyour AMX system. The AMX managers are all optional.

The purpose of this manual is to provide the system designer and applicationsprogrammer with the information required to properly configure and implement anAMX-based real-time operating system. It is assumed that you are familiar with thearchitecture of the processor on which you will be using AMX. It is further assumed thatyou are familiar with the rudiments of microprocessor programming including theconcepts of code, data and stack separation.

For historical reasons, AMX 86 is coded in assembly language. The result is a fast,compact, reliable implementation whose code has remained invariant throughout thelifetime of this very stable product. AMX is provided in source format to ensure thatregardless of your development environment, your ability to use and support AMX isuninhibited.

The C programming language, commonly used in real-time systems, is used throughoutthis manual to illustrate the features of AMX.

2 KADAK AMX Overview

Section Summary

This manual is divided into three sections. Each section is divided into chapters.

Section 1 of this manual describes the AMX Multitasking System and how it is used.Separate chapters are provided for each of the AMX managers.

Section 2 describes the AMX System Configuration Builder and the manner in which it isused to create your AMX System Configuration Module.

Section 3 is the application programming guide. It provides detailed descriptions of all ofthe AMX service procedures which are available in the AMX Library.

AMX Guides

This manual describes the use of AMX 86 for all target processors on which it can beused. Target specific requirements or programming considerations are provided onlywhen necessary to clarify proper operation on a particular processor.

This manual describes the use of AMX in a tool set independent fashion. References tospecific assemblers, compilers, librarians, linkers, locators and debuggers are purposelyomitted. The AMX 86 Tool Guide provides guidance for the proper use of AMX witheach toolset with which AMX has been tested.

Guidelines for the proper use of AMX when coding in C are provided in the separateAMX 86 C Programming Guide. This guide includes useful debugging tips as well as adescription of the AMX Sample Program provided with AMX.

The AMX 86 Timing Guide discusses general timing issues related to the use of AMX.Timing metrics generated for specific boards and software development toolsets are alsoprovided. These timing figures can be used as guidelines to expected AMX performance,but are not to be construed as product specifications. The AMX Timing Guide isprovided as an appendix in the AMX 86 Tool Guide.

Note

The AMX 86 PC Supervisor is delivered with AMX for usein the development of applications which must run on PCswith access to PC peripherals and DOS.

The AMX 86 PC Supervisor Reference Manual is providedin its own section of this manual.

AMX Overview KADAK 3

1.2 GlossaryBuffer Pool A collection of data buffers whose use is controlled by the AMX

Buffer Manager.

Buffer Pool Id The handle assigned to a buffer pool by AMX for use as a uniquebuffer pool identifier.

Circular List An application data structure used to maintain a list of 1, 2 or 4byte elements with the ability to add and remove elements at boththe top (head) and bottom (tail) of the list.

Clock Handler The name given to the AMX procedure which is called by the ISProot which services the hardware clock interrupt.

Clock Tick The interrupt generated by a hardware clock.

Conforming ISP An Interrupt Service Procedure consisting of an ISP root whichcalls an Interrupt Handler which has the right to make calls to asubset of the AMX service procedures.

Counting SemaphoreA particular type of AMX semaphore used for event signalling orfor controlling access by tasks to multiple resources.

Envelope The private data storage element used by AMX to pass a messageto a task mailbox or message exchange.

Error Code A series of signed integers used by AMX to indicate error orwarning conditions detected by AMX service procedures.

Event Group A set of 16 events whose access and signalling is controlled by theAMX Event Manager.

Event Group Id The handle assigned to an event group by AMX for use as a uniqueevent group identifier.

Exit Procedure An AMX or application procedure executed by AMX during theexit phase when an AMX system is shut down.

Fatal Error A condition detected by AMX which is considered so abnormalthat to proceed might risk catastrophic consequences. Examplesinclude, but are not limited to, insufficient memory in the AMXData Segment or division by zero in an ISP.

FIFO First in, first out. Usually used to refer to the ordering of elementsin a queue, circular list or linked list.

Group Id See Event Group Id.

Handle An identifier assigned by AMX for use by your application toreference a private AMX system data item.

4 KADAK AMX Overview

Interrupt Handler An application procedure called from an ISP root to service aninterrupting device.

Interrupt Service Procedure (ISP)An AMX or application procedure which is executed in responseto an external device interrupt request.

ISP See Interrupt Service Procedure

ISP root The ISP code fragment (produced by AMX function ajispm())which informs AMX that an interrupt has occurred and calls anapplication Interrupt Handler.

Kernel Task The private AMX task which is responsible for all timing controland event sequencing in an AMX system.

Linked List An application data structure used to maintain a doubly-linked listof arbitrary application data elements with the ability to add andremove elements at head, tail or specified positions in the list.

List Element An 8-bit, 16-bit or 32-bit value which can be added to or removedfrom a circular list.

Mailbox An AMX data structure consisting of a single message queue.Mailboxes allow the interchange of messages between two or morecooperating components (tasks, ISPs, etc.) of an AMX system.Each task or message exchange can have up to four mailboxes.

Memory Block A portion of a memory section that has been allocated for use byone or more tasks.

Memory Handle The handle assigned to a private memory section by AMX for useas a unique memory section identifier.

Memory Section A contiguous region of memory assigned to the AMX MemoryManager for allocation to application tasks.

Message Application information passed by AMX in an envelope to a taskmailbox or message exchange.

Message Exchange An AMX data structure that consists of four message queues, eachfor messages of a different priority. The message exchanges allowthe interchange and prioritization of messages between two ormore cooperating components (tasks, ISPs, etc.) of an AMXsystem.

Message Exchange IdThe handle assigned to a message exchange by AMX for use as aunique message exchange identifier.

AMX Overview KADAK 5

Message Queue An AMX data structure used to manage messages sent to a taskmailbox or message exchange. A separate message queue isprovided for each of the four message priorities which a task ormessage exchange can support.

Message Priority Identifies which of a task's or message exchange's four messagequeues is to receive the AMX message.

Nonconforming ISP An Interrupt Service Procedure which bypasses AMX completelyand hence cannot use any AMX service procedures.

RAM Alterable memory used for data storage and stacks.

Resource SemaphoreA particular type of AMX semaphore used to provide access to anentity such as a math coprocessor, disk file or non-reentrant librarywhose ownership is to be controlled by the AMX SemaphoreManager.

Restart Procedure An AMX or application procedure executed by AMX during theinitialization phase when an AMX system is started.

ROM Read only memory of all types including PROMs, EPROMs andEAROMs.

Segment An area of memory in which AMX code or data is stored.Segments are sometimes called sections or regions according to thenomenclature adopted for a particular processor.

Semaphore An AMX data structure which can be used by the AMXSemaphore Manager to provide an event signalling mechanism ormutually exclusive access by tasks to specific user facilities.

Semaphore Id The handle assigned to a semaphore by AMX for use as a uniquesemaphore identifier.

Slice Interval The interval of time allocated to a task which is time sliced.

Slot One of n locations used to store list elements in a circular list.

System Configuration ModuleA software module, produced by the AMX System ConfigurationBuilder, which defines the characteristics of a particular AMXapplication.

System Tick A multiple of the hardware clock tick from which the fundamentalAMX unit of time is derived. All time intervals in an AMX systemare measured in multiples of the system tick.

Tag A 4-character name that can be assigned to any AMX system datastructure when it is created. A tag can be used to find the identifierof a task, timer, semaphore, event group, message exchange orbuffer pool with a particular name.

6 KADAK AMX Overview

Task An application procedure which is executed by AMX in a waywhich makes it look as though all such procedures are executing atonce.

Task Control Block (TCB)A private data structure maintained by AMX for each task in thesystem.

Task Id The handle assigned to a task by AMX for use as a unique taskidentifier.

Task Priority The priority at which a task executes. Tasks which have the sametask priority are actually ordered in priority according to the orderin which the tasks were created.

Task Signal A set of 15 user-defined event signals associated with each task fortask synchronization use.

TCB See Task Control Block

Time Slice The process by which AMX allows tasks having the same priorityto share the use of the processor in a round robin fashion.

Timer A facility provided by AMX to permit precise intervalmeasurement in AMX applications.

Timer Id The handle assigned to a timer by AMX for use as a unique timerIdentifier.

Timer Procedure An application procedure which is executed by the AMX KernelTask whenever the corresponding timer interval expires.

AMX Overview KADAK 7

1.3 AMX NomenclatureThe following nomenclature has been adopted throughout the AMX User's Guide.

Processor registers are referenced as follows:

8-Bit Registers AH, AL, BH, BL, CH, CL, DH, DL16-Bit Registers AX, BX, CX, DX, SP, BP, SI, DIInstruction Pointer IPFlags (Condition Code) CCSegment Registers CS, DS, SS, ES

The processor flags (condition code) are referenced using the mnemonics employed insoftware branches as follows:

Zero ZNon-zero NZCarry CNo Carry NCPositive (no sign) NSMinus (sign) SInterrupt flag IFDirection flag UP if forward; DN if backward

Numbers used in this manual are decimal unless otherwise indicated. Hexadecimalnumbers are indicated as 0xABCD in C code or 0ABCDH in assembly language code.

The terminology A(Table XYZ) is used to define addresses. It is read as "the address ofTable XYZ".

Addresses are written as segment:offset. For example ES:BX is the address with segmentdetermined by extended register ES and offset determined by base register BX.

Read/write memory is referred to as RAM. Read only memory (non-volatile storage) isreferred to as ROM.

AMX symbol names are identified as follows:

ajxxxx AMX procedure called from CAAXXXX AMX procedure called from assemblerAMXXXX Private AMX procedures, structures and constantsAERXXX AMX Error Code XXXAA831xxx.xxx AMX kernel filenamesAJ831xxx.xxx AMX C Interface filenamesAMxxxxxx.xxx AMX reserved filenamesAA832xxx.xxx AMX PC Supervisor filenames

Throughout this manual examples are provided in C and assembly language. In general,code examples in C are presented in lower case. Code examples in assembler are inupper case. File names are shown in upper case. C code assumes that an int is 16 bits asis common for most C compilers for the 8086 family.

8 KADAK AMX Overview

This page left blank intentionally.

General AMX Operation KADAK 9

2. General AMX Operation

2.1 Introduction to MultitaskingA real-time system is characterized by the need to respond rapidly to events occurringasynchronously in time. A multitasking system is one in which a number of activities orprocesses must be performed simultaneously without interference with each other. Asystem in which several activities must operate simultaneously with time-criticalprecision is called a real-time multitasking system.

The AMX Multitasking Executive provides a simple solution to the complexity of real-time multitasking. AMX supervises the orderly execution of a set of application programmodules called tasks. Each task solves a particular problem and provides a specificfunctional capability within the system.

As we all know, the microprocessor can only do one thing at a time. Fortunately, it doesall things very quickly. However, to get the effect that all activities are occurringsimultaneously, it is necessary to rapidly switch back and forth from one process toanother in a well controlled fashion. It is AMX which organizes and controls the use ofthe microprocessor to achieve this apparent concurrent execution of tasks.

Each task solves a particular problem or provides a specific functional capability withinthe system. Each task executes independent of other tasks. Facilities are provided,however, to permit tasks to co-operate to achieve a common goal. This process in whichmore than one task is allowed to share the use of a single processor is called multitasking.The software program which makes it possible is AMX.

What a task does is completely application dependent. In fact, the most difficult aspectof system design is to logically break the problem into a set of tasks which, ifimplemented, will achieve the desired goal. The following example is presented toillustrate one way in which a simple real-time alarm logging system can be implemented.

Example

Assume that it is necessary to periodically scan a set of digital alarm inputs. When anyalarm is detected, a message is to be logged on a printer. The message is to include adescription of the alarm and the time of day at which it occurred.

Careful examination of this problem indicates that in fact it is three problems. First, a setof digital inputs must be scanned for the detection of alarms. Second, a message must beprinted. Finally, the time of day must be maintained for inclusion in the message.

Three problems usually result in three tasks. Our example is no exception. A time of daytask is required to maintain the date and time within the system. The task must beexecuted once each second if time is to be maintained to the nearest second. We willignore the requirement to somehow set the proper time and date. (Isn't that another task?)

10 KADAK General AMX Operation

Alarm scanning will likely be hardware dependent. We will simplify matters byassuming that a scanning task must examine all digital inputs every 100 ms. The taskmust be capable of detecting alarm changes in the digital inputs. When an alarm isdetected, the scanning task must initiate the logging of a message.

However, the scanning task is not allowed the luxury of waiting until the message isprinted. It must continue scanning for additional alarms at the same 100 ms rate. Thescanning task must, therefore, send to the message task parameters identifying the alarmwhich has occurred and the time at which it was detected.

The message task is very simple to describe. It receives parameters identifying the timeat which a particular alarm occurred. The task must output to a printer a messagedescribing the alarm.

The foregoing example, although very simple, illustrates many of the features of a real-time multitasking system. At first, the implementation of the required set of tasks may bedifficult to envision. Two of the tasks must operate periodically at different intervals.The third task, printing, is such a slow process that the other two tasks must be allowed toexecute with higher priority. Moreover, provision must be made to allow the alarmparameters to continue piling up on the message task when alarms are occurring at a ratefaster than can be printed. (What would we do if we had to print high priority alarms firstand delay the printing of lower priority alarms?)

The implementation of the proposed solution is greatly simplified by AMX. AMX willsupervise the execution of the three tasks in the defined priority order. Timing facilitiesare provided by AMX with a resolution governed by the hardware clock. AMX supportsmessage passing between tasks. AMX allows these messages to pile up at the destinationtask at any of four priority levels because automatic message queuing with prioritysorting is an inherent feature of AMX.

This introduction to multitasking is not exhaustive. The intent is to remove some of themystery from the multitasking concept. The above example is intended to inspireconfidence in your ability to understand AMX and use it to solve real-time problems.

General AMX Operation KADAK 11

2.2 AMX Operation

AMX Startup

Each AMX-based system consists of the AMX executive program and a set ofapplication tasks and interrupt service procedures. This collection of programs residentin the memory of the microprocessor configuration represents the entire operatingsystem.

The manner in which the operating system begins execution is application dependent. InROM-based systems, automatic hardware vectoring to the program start address is oftenimplemented. In RAM-based systems, the program is first loaded from some storagemedium (ROM, hard disk, diskette, etc.) or downloaded from one processor to another.Once the program is loaded, it is started at its start address by the loader.

Figure 2.2-1 illustrates the general operation of an AMX system. Execution begins in theuser domain providing the opportunity for hardware specific and application dependentsetup prior to the initialization of the AMX system. For example, hardware interfacesmay require custom configuring. In some systems, it might be desirable to perform amemory integrity check before system startup is permitted.

Once all custom initialization has been performed, the program calls the AMX entryprocedure ajentr. Operating characteristics are defined in an AMX SystemConfiguration Module. It is possible to predefine specific tasks and timers which will beautomatically created by AMX during its initialization phase. AMX initializes itself andplaces all application tasks and timers into an idle state.

Once AMX has initialized all of its internal variables and structures, it executes asequence of user provided Restart Procedures. These procedures can invoke AMXservices to start tasks and initialize interval timers.

12 KADAK General AMX Operation

Control Flow

Function calls

InterruptsInitialization

RestartProcedure

Task Scheduler Services

Start

TimerProcedure

InterruptSupervisor

ClockHandler

InterruptService

Procedure

Kernel Task

User AMX

Task A

Task N

Clock

Figure 2.2-1 AMX General Operation

General AMX Operation KADAK 13

The Task Scheduler

Following system initialization, AMX proceeds to its Task Scheduler. The TaskScheduler searches its list of available tasks to determine the highest priority task capableof execution. Task execution priorities are determined by the system designer. If no taskis ready to begin execution, AMX sits with interrupts enabled, waiting for some externalevent to generate an interrupt.

AMX begins task execution at the task's defined start address. The task executes asthough it were the only program in the system. Services offered by AMX can be invokedby the task by procedure calls as indicated in Figure 2.2-1.

Once a task begins execution, it appears to operate without interruption. The interruptsthat are periodically taking place are completely hidden from the task by the AMXInterrupt Supervisor and Task Scheduler. The task, once executing, inhibits theperformance of all tasks of priority lower than its own. The task continues to executeuntil it decides to relinquish control, even if only temporarily, by calls to AMX.

The task ends by returning to the AMX Task Scheduler which again finds the nexthighest priority task ready to execute and gives it control of the processor. A task, onceexecuting, is free to call any of the AMX task services. For instance, a task can send amessage to a task mailbox or message exchange, wait for an event or wait for a timedinterval. If the task wishes to wait for an event, the AMX service procedure will suspendthe task and request the AMX Task Scheduler to force execution of the next highestpriority task ready for execution.

AMX acts as the context switcher supervising the orderly execution of application tasks.AMX employs a preemptive, priority-driven scheduling algorithm which ensures that thehighest priority task which is ready to do useful work always has control of the processor.

AMX will switch tasks if it receives a request from the executing task to perform anoperation which, of necessity, invokes a task of higher priority. For instance, theexecuting task may request AMX to start a higher priority task.

14 KADAK General AMX Operation

The Interrupt Supervisor

Tasks execute with the processor interrupt facility enabled to permit service of externaldevices. When an external interrupt occurs, the task is interrupted in the manner dictatedby the processor. The processor automatically saves the return address and some subsetof the processor state (registers, flags, etc.) and branches to an Interrupt ServiceProcedure (ISP). The exact vectoring method is determined by the hardwareconfiguration employed in the system.

Two types of ISPs exist: nonconforming ISPs and conforming ISPs.

A nonconforming ISP must quickly service the device to remove the interruptingcondition. The ISP must preserve all registers which it uses. The nonconforming ISPcannot make calls to any AMX service procedures.

A conforming ISP can make use of a subset of the AMX service procedures. Aconforming ISP consists of an ISP root and an Interrupt Handler. The processor vectorsto the ISP root which informs the AMX Interrupt Supervisor that the interrupt hasoccurred. The Interrupt Supervisor preserves the state of the interrupted task and, ifnecessary, switches to an interrupt stack. The Interrupt Supervisor then calls theassociated Interrupt Handler.

The Interrupt Handler must quickly service the device to remove the interruptingcondition. The handler is free to make procedure calls to a subset of the AMX servicefacilities. When device service is completed, the AMX Interrupt Supervisor dismissesthe interrupt.

The AMX Interrupt Supervisor monitors calls made by the Interrupt Handler to AMXservice procedures. If no such calls have been made, AMX automatically restores thestate of the interrupted task and returns directly to the interrupted task at its point ofinterruption.

The Interrupt Handler may have requested AMX to initiate or resume execution of sometask of higher priority than the interrupted task. If so, the AMX Interrupt Supervisorsuspends the interrupted task and marks it as ready to resume execution at the earliestopportunity. The AMX Task Scheduler is then invoked to determine the highest prioritytask capable of execution.

The AMX Interrupt Supervisor supports nested interrupts on processors which providethis capability. If interrupts nest, the Interrupt Supervisor defers its task switching checksuntil all of the concurrent interrupts have been serviced.

Note

A conforming ISP root can be created using AMXprocedure ajispm.

General AMX Operation KADAK 15

Timing Facilities

The AMX Timer Manager provides a Clock Handler and a Kernel Task to providecomplete timing control for your real-time application. The AMX Clock Handler isindependent of any particular hardware configuration. If AMX timing facilities are to beutilized, a real-time clock must be included in the configuration.

The hardware clock interrupt must be serviced by a conforming ISP. Whenever a clockinterrupt occurs, the application Interrupt Service Procedure must dismiss the hardwareclock interrupt and call the AMX Clock Handler.

The AMX Clock Handler triggers the AMX Kernel Task if required. The Kernel Task istriggered at the user defined system tick interval if, and only if, there is any outstandingtiming activity required in the system. In this case, the interrupted task is suspended andthe AMX Kernel Task begins execution.

The AMX Kernel Task executes as the highest priority task in the system. The AMXKernel Task monitors all tasks which are in a timed wait state. If a task's timer expires,the AMX Kernel Task primes the task to resume execution with a timeout indication.

The AMX Kernel Task also services all expiring application interval timers. Wheneveran application interval timer expires, the corresponding application Timer Procedure isexecuted. This procedure can invoke a subset of the AMX services to send messages,signal events or wake tasks. If the timer is defined to be periodic, the AMX Kernel Taskautomatically restarts it with the predefined period.

16 KADAK General AMX Operation

Message Queuing

One of the more powerful features of AMX is its ability to queue messages for tasks.The queuing facility permits messages to pile up in a controlled fashion, freeing the ISP,Timer Procedure or task which is sending the message to continue with its appointedfunction. If a task sends a message, it can suspend itself until the message has beenreceived and processed by some other task.

The AMX message queuing facility is further enhanced by allowing the messages toqueue at any of four priority levels. A task can therefore receive messages from a varietyof callers with the messages already sorted in order of priority by AMX.

The system designer describes the exact message queuing requirements in a taskdefinition or in a message exchange definition. For each task and message exchange, youcan specify which, if any, of the four message queuing priority levels are to be supported.You also specify the required message nesting depth for each of these message queues,often referred to as mailboxes.

AMX maintains a free list of message envelopes. These envelopes are used by AMX totransmit messages to the mailboxes of tasks and message exchanges. The caller'smessage parameters are moved into a free envelope which is then added to the messagequeue of the destination task mailbox or message exchange mailbox.

The AMX message queuing facility is especially useful in event logging applications. Insuch applications, messages are transmitted to a printing task by any task wishing to logan event. The printing task is then executed once for each unique request which it hasreceived. High priority messages can easily be forced to precede low priority messagesusing the AMX message priority feature. Finally, any task wishing to wait until itsparticular message has been logged can do so by informing AMX of its intent at the timethe message is sent.

AMX Shutdown

An AMX system can be shut down in the same orderly fashion in which it was started. Atask initiates a shutdown with a call to the AMX exit procedure ajexit.

It is the caller's responsibility to assure that the AMX system is in a reasonable state topermit a shutdown. For instance, all device I/O operations should be stopped and alltiming activity should be curtailed.

The AMX shutdown procedure executes a series of user Exit Procedures which canrestore the original environment which existed prior to starting the AMX system. Deviceinterfaces can be reprogrammed and interrupt vectors restored if necessary.

Once all of the Exit Procedures have been executed, AMX returns to the point at whichAMX was originally launched.

General AMX Operation KADAK 17

2.3 AMX ManagersAMX provides a set of managers to simplify event synchronization, resourcemanipulation and memory allocation. Not all applications will make use of all of themanagers. The system designer can decide which of the AMX managers is best suitedfor a particular application.

The Time/Date Manager provides Y2K compliant time of day calendar support ifrequired. The AMX calendar clock includes second, minute, hour, day, month, year andday of the week. AMX services are provided to set and read the calendar clock.A formatting procedure is also provided to translate the calendar time and date from theinternal format in which it is maintained by AMX into an ASCII string in several of themost popular formats.

An application procedure can be tied to the calendar clock and called at one secondintervals to permit simple time of day event scheduling.

The Semaphore Manager provides two types of semaphores each with priority queuingand timeout: resource semaphores and counting semaphores.

A resource semaphore can be used to provide controlled access to your resources. It usesa binary semaphore to limit access to each resource to one task at a time. Ownership andrelease of a resource is governed by calls to the Semaphore Manager. A resourcesemaphore offers the unique characteristic of identifying each resource owner. Only thetask which owns a resource is permitted to release it.

General purpose counting semaphores can be created for mutual exclusion and resourcemanagement. Tasks must request the Semaphore Manager for access to the resourcecontrolled by such a semaphore. The task can specify the priority of its request to use thesemaphore. If the semaphore is not free, the task will be forced to wait for itsavailability. The task will be placed on the semaphore wait queue at the priority specifiedby the task. Optionally, the task can specify a timeout interval limiting the time the taskis prepared to wait.

A task, ISP or Timer Procedure can signal the semaphore with a call to the SemaphoreManager. The Semaphore Manager grants access to the semaphore to the task, if any,waiting at the top of the semaphore's wait queue.

The Event Manager provides a convenient method for synchronizing one or more tasksto events detected in Interrupt Service Procedures, Timer Procedures and other tasks. Atask requests the Event Manager to suspend its operation until any one of a particular setof events occurs. Alternatively, the task can request to wait until all of a set of eventconditions are met. Optionally, the task can specify a timeout interval limiting the timethe task is prepared to wait. More than one task can be waiting for the same event or setof events.

When a task, ISP or Timer Procedure detects an event, it signals the event with a call tothe Event Manager. The Event Manager checks to see if the event has resulted in anevent combination for which one or more tasks are waiting. If so, the tasks which werewaiting are allowed to resume execution.

18 KADAK General AMX Operation

The AMX 86 Task Mailbox facility provides a general purpose message queuingmechanism for tasks. This service is not provided by a separate AMX manager; it is aninherent feature of AMX 86. Any task can have up to four private mailboxes in whichthe task can receive AMX messages. Tasks, ISPs or Timer Procedures can sendmessages to such a task mailbox. The messages are ordered in each task mailboxaccording to their order of arrival. If such a task is idle when a message is deposited inone of its mailboxes, the task will automatically be started and given the messageextracted from the mailbox. At any time, a task can request a message from any of itsmailboxes. When the task ends, it will automatically be restarted if its mailboxes are notall empty. The task will be given the highest priority message available.

The Message Exchange Manager provides a general purpose prioritized messagequeuing facility. Tasks, ISPs or Timer Procedures can send messages to a messageexchange to be queued at any of four priority levels. When a task requests a messagefrom a message exchange, it is given the highest priority message available. If nomessage is available, the task will be forced to wait. The task will be placed on themessage exchange wait queue at the wait priority specified by the task. Optionally, thetask can specify a timeout interval limiting the time the task is prepared to wait. Thisinterval can be from no wait to an indefinite wait. When a message subsequently arrives,it is immediately given to the task waiting at the top of the message exchange's waitqueue.

The Buffer Manager provides fast, efficient access to multiple pools of buffers, eachbuffer representing a fixed size block of memory. This form of memory managementmeets the requirements of most typical applications and is best suited for real-time use inwhich memory block availability must be predictable and in which the penalties formemory fragmentation cannot be tolerated.

Application modules can request the Buffer Manager to get a buffer from a pool. Unlikeother AMX managers, the Buffer Manager does not permit a task to wait for a buffer tobecome available.

When released, the buffer is automatically returned by the Buffer Manager to the pool towhich the buffer belongs. Buffer ownership can be increased so that more than one taskcan simultaneously own a shared buffer. Special facilities are provided to assure that if abuffer is owned by more than one task, it is only returned to its pool when the slowestowner finally releases it.

The Memory Manager controls the dynamic allocation of memory to tasks in themultitasking environment. Multiple sections of user defined memory can be controlledby the Memory Manager. A section can exceed 64K bytes. The memory in each sectionmust be contiguous but the sections themselves do not have to be contiguous.

A task can request the Memory Manager to allocate a contiguous block of memory of anysize. When finished with the block, the task requests the Memory Manager to free thememory for use by other tasks.

A particularly unique feature of the Memory Manager permits any block of memory(including those acquired from the Memory Manager) to be treated as memory fromwhich smaller private blocks can be dynamically allocated.

General AMX Operation KADAK 19

The Circular List Manager provides a general purpose circular list facility formaintaining compact lists of 8-bit, 16-bit or 32-bit variables. Circular lists areparticularly useful for managing character streams associated with input/output devices.

The Linked List Manager provides a fast, general purpose doubly-linked list facility formaintaining lists of arbitrary application data structures (objects).

The Linked List Manager removes the tedium and the frequent errors usually encounteredwhen each application must manipulate the linkages of different types of objects ondifferent lists. Objects can reside on multiple lists at the same time, a characteristicfrequently encountered in real problems but ignored by most list manipulation software.

20 KADAK General AMX Operation

2.4 Starting AMXAn AMX operating system consists of AMX, the subset of its managers which youchoose to use and your complement of application programs. All of these modules areconnected together to form the AMX operating system as described in the AMX ToolGuide.

Before launching AMX, you must establish the required operating mode for the particulartarget processor you are using. AMX 86 operates only in the 8086 real mode.

AMX uses the Medium or Large segmentation model in which multiple code segmentsand one or more read/write data segments are provided. AMX makes no assumptionabout the manner in which these segments correlate to physical memory.

AMX is launched with a launch parameter defining the nature of the launch. The launchparameter is a 16-bit unsigned integer in which each bit defines a particular launchcharacteristic. Bit mask mnemonics AMLPxx are defined in include files AMX831SD.H andAMX831SD.DEF.

Bit Value Launch parameter

0 0 Launch is permanentAMLPTMP Launch is temporary

1 0 Vector Table is not alterable (in ROM or not accessible)AMLPVA Vector Table is alterable (in RAM and accessible)

2 0 Interrupts disabled during launchAMLPIE Interrupts enabled during launch

AMX is always launched from your main program (or startup module) by calling AMXprocedure ajentr from C or AAENTR from assembly language.

Your AMX operating system can be launched in two ways: permanently or temporarily.The type of launch is determined by bit 0 of the launch parameter.

Bit 1 of the launch parameter indicates whether or not AMX will be permitted to alter theprocessor vector table. For most applications, the vector table is in RAM and thereforealterable.

AMX disables the interrupt system at the time you launch AMX. Unless bit 2 of yourlaunch parameter indicates otherwise, interrupts will remain disabled during the startupprocess while AMX initializes its internal parameters and calls each of your RestartProcedures.

General AMX Operation KADAK 21

Permanent Launch

In most applications, your AMX operating system is resident in ROM or loaded intoRAM. AMX is started in real mode and given permanent control of the processor.

An AMX system can be launched permanently from a main program coded in C asillustrated in the following example.

The implication of starting AMX from a main C program is that a C startup module hasalready provided a stack before procedure main was called. The main procedure callsAMX at its entry point ajentr with three parameters. The first parameter is the launchparameter. The value AMLPVA indicates that the launch is permanent (bit 0 is 0), vectorsare alterable (bit 1 set by AMLPVA) and interrupts are to be disabled during the launch (bit2 is 0).

The second parameter is the pointer to your application's User Parameter Table in theSystem Configuration Module which defines the characteristics of your AMX system.The third parameter, NULL, must be present but is not used by AMX because the launch ispermanent.

/* Start AMX for permanent execution */

#include "amx831sd.h" /* AMX Structure Definitions */

void main(){

struct amxupts FAR *uptp; /* User Parameter Table pointer*/

:ajupt(&uptp); /* Fetch pointer to UPT */

/* Start AMX: no exit, *//* vectors alterable and *//* interrupts disabled */

ajentr(AMLPVA, uptp, NULL);}

If the vector table is in ROM or, for any reason, is not to be altered by AMX, set thelaunch parameter to 0 instead of AMLPVA. In this case, you will not be able to use AMXservices to dynamically install pointers to Interrupt Service Procedures into the vectortable.

If you wish interrupts enabled during the launch process, add AMLPIE to the launchparameter. Be sure that interrupts from a particular device are inhibited until you haveinstalled an ISP to handle interrupts from the device.

22 KADAK General AMX Operation

An AMX system can be launched permanently from a startup module coded in assemblylanguage as illustrated in the following example.

Systems of this type begin execution at the AMX entry point AAENTR with the launchparameter in register BX. Register BX[0] must be set to zero to indicate that a permanentlaunch is required. Register pair ES:SI must provide a pointer to the User ParameterTable in the System Configuration Module which defines the characteristics of yourAMX system.

Set register BX[1] to 1 (AMLPVA) if interrupt vectors are to be alterable. If you set registerBX[1] to 0, you will not be able to use AMX services to dynamically install pointers toInterrupt Service Procedures into the vector table.

Set register BX[1] to 0 if interrupts are to be disabled during the startup process. If youset register BX[1] to 1 (AMLPIE) to enable interrupts during the launch, be sure thatinterrupts from a particular device are inhibited until you have installed an ISP to handleinterrupts from the device.

When AMX is started in this manner, it immediately establishes the AMX Kernel Stackas the current stack. There is therefore no need for your application to provide a stack fora permanent launch.

In a ROM based system, AMX is frequently restarted whenever the 8086 processor isreset. A startup module, coded in assembler, receives control, initializes the 8086, entersprotected mode and starts AMX as illustrated in the following example.

EXTRN AAENTR:FAR ;AMX Entry PointEXTRN _AMXUPT_:DWORD ;A(User Parameter Table)

;USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;UPTADR DD _AMXUPT_ ;A(User Parameter Table);START PROC FAR

:Initialize 8086:LDS SI,CS:UPTADR ;DS:SI = A(User Parameter Table)MOV BX,AMLPVA ;BX = no exit, vectors alterable

;and interrupts disabledJMP AAENTR ;start AMX

;START ENDP;USER_CODE ENDS

General AMX Operation KADAK 23

Temporary Launch

Your AMX operating system can be started, allowed to run for a while and then stopped.This type of operation is called a temporary launch. The most common application ofthis type occurs on PC compatibles. An AMX operating system is started from DOS,allowed to operate for a while and then forced to return to DOS.

If you wish to start an AMX system for temporary execution from a module coded inassembler, refer to the source code for procedure ajentr in AMX source fileAJ831KI.ASM in installation directory AMX831\CIF. Mimic the simple operations whichare provided by that procedure.

An AMX operating system can be started for temporary execution from a main Cprogram as in the following example.

AMX is started at its entry point ajentr with three parameters. The first is the launchparameter AMLPTMP+AMLPVA indicating that the launch is temporary (bit 0 set byAMLPTMP), vectors are alterable (bit 1 set by AMLPVA) and interrupts are to be disabledduring the launch (bit 2 is 0).

If the vector table is in ROM or, for any reason, is not to be altered by AMX, replace thevalue AMLPVA in the launch parameter with the value 0. In this case, you will not be ableto use AMX services to dynamically install pointers to Interrupt Service Procedures intothe vector table.

If you wish interrupts enabled during the launch process, add AMLPIE to the launchparameter. Be sure that interrupts from a particular device are inhibited until you haveinstalled an ISP to handle interrupts from the device.

As for a permanent launch, the second parameter is a pointer to your User ParameterTable. The third parameter is a pointer to a double word variable of your choice.

24 KADAK General AMX Operation

When an AMX system is launched for temporary execution, it executes until one of yourapplication tasks calls the AMX exit procedure ajexit requesting an orderly shutdownof the AMX system (see Chapter 3.11). The ajexit caller can return two parameters tothe procedure that launched AMX. One of these parameters is an integer which isreceived as errcode from the ajentr call. The other is a double word parameter storedin the variable provided in the call to ajentr.

In the following example, the integer result is stored in variable errcode and the doubleword parameter is recorded in variable resultp.

/* Start AMX for temporary execution */

#include "amx831sd.h" /* AMX Structure Definitions */

void main(){

struct amxupts FAR *uptp; /* User Parameter Table pointer */int errcode;char *resultp;::ajupt(&uptp); /* Fetch pointer to UPT */

/* Start AMX: exit allowed, *//* vectors alterable and *//* interrupts disabled

errcode = ajentr(AMLPTMP+AMLPVA, uptp, &resultp);

:Interpret your termination status (errcode) and, if necessary,look at your results referenced by the pointer returned inpointer variable resultp.:}

Application Tasks KADAK 25

3. Application Tasks

3.1 Task CreationThe AMX Multitasking Executive provides a simple solution to the complexity of real-time multitasking. AMX supervises the orderly execution of a set of application programmodules called tasks. Each task solves a particular problem and provides a specificfunctional capability within the system.

The maximum number of tasks in a system is user defined in your System ConfigurationModule (see Chapter 14.5). The defined maximum sets an upper limit on the number ofactual tasks that can be created by the application. AMX 86 sets an upper bound of 100tasks in a system. Other versions of AMX have no such restriction.

Tasks can be created in two ways. Tasks can be predefined in your AMX SystemConfiguration Module which is processed by AMX at startup. Tasks defined in thisfashion are automatically created by AMX but are not started. Restart Procedures andtasks can also dynamically create tasks using AMX procedure ajtkcre.

AMX assigns a task identifier (id) to each task when it is created. The task id is a handlewhich uniquely identifies the particular task. When AMX prebuilds a task, it saves thetask identifier in the id variable specified in the task's description.

When tasks are created dynamically, AMX returns the assigned task id to the creator. Itis the responsibility of the application to keep track of the task id for future reference tothe task.

When a task is created, you can provide a unique 4-character task tag to identify the task.The tag can be used subsequently in a call to ajtktag to find the task id allocated byAMX to the particular task.

AMX uses the information in the task definition to construct a Task Control Block (TCB)for the task. The TCB of each task is used exclusively by AMX to control taskexecution. At any instant in time, the content of the TCB, as maintained by AMX,completely describes the state of the corresponding task.

26 KADAK Application Tasks

Tasks which do not receive messages are written as Large or Medium model C functionswithout formal parameters. These tasks must be started using AMX procedure ajtrig.For this reason, such tasks are called trigger tasks. For example, a task that immediatelyends would appear as follows:

void cdecl task1(void){

}

Tasks which must receive a message are written as Large or Medium model C functionswhich receive a set of parameters. Tasks that receive messages are called message tasks.These tasks must be started using any of the variations of AMX procedure ajsend orajsenw. For example, a task which receives an integer as a message and then ends wouldappear as follows:

void task2(int message){

}

A message task must be defined to include one to four message queues (also called taskmailboxes) in which the task receives messages. Messages which arrive in the task'smailboxes are automatically delivered to the task on the task's stack ready for processingby the task. This type of message processing is described in Chapter 3.9.

Tasks written in assembly language must be coded as FAR procedures as follows:

TASK_CODE SEGMENT BYTE 'CODE';; The task is located in user program memory;

ASSUME CS:TASK_CODE;STTASK PROC FAR

:Set DS and ES if required by taskAccess parameter on stack via BPDo task functions:RET ;Return to AMX

;STTASK ENDP;TASK_CODE ENDS

Application Tasks KADAK 27

3.2 Task StatesA task is always in one of the following states:

IdleReadyRunWaitHalt

When a task is created, AMX assigns it a Task Control Block and sets it in the idle state.An idle task has no outstanding requests to execute pending. It is waiting to be triggered.

A ready task has an outstanding request to execute or is ready to resume execution afterhaving been interrupted or waiting.

A task which is executing is the only task which is in the run state.

A task is in the wait state when it is blocked pending the occurrence of some event. Thewait state is always qualified with an indication in the TCB as to what the task is waitingfor.

The halt state is reserved for use by KADAK debug utilities to suspend all task executionfor debugging purposes.

The halt state is used by the AMX Breakpoint Manager to suspend all task executionwhen a debug breakpoint is encountered. When a debug breakpoint is encountered, allapplication tasks except the one in which the breakpoint occurred are placed in the haltstate. When you leave the debugger, the tasks are restored to the state they were in priorto the breakpoint.

Figure 3.2-1 illustrates the task states and shows the state transitions which are possible.The halt state is not explicitly shown.

28 KADAK Application Tasks

event of interestor timeout occurs

ajtrig - trigger a task

ajwait - waitajwatm - timed wait

ajsenw - send message to taskmailbox and wait for ack

ajmxwat - wait on a message exchange

ajsmrsv - reserve a resourceajsmwat - wait on a semaphore

ajevwat - wait for event

task ends or isinterrupted

no higher prioritytask running

no requestsoutstanding

Idle

Ready

Run

Wait

ajsgwat - wait for task signal

ajsend - send message to a task

Figure 3.2-1 AMX Task State Diagram

Application Tasks KADAK 29

3.3 Starting a TaskAt startup, AMX initializes all predefined application tasks into an idle state. Once idle,a task cannot execute until AMX receives a directive to start the task. How then does anAMX system get off the ground?

Three AMX directives are provided to start a task. These directives are procedure calls toAMX. The ajtrig call is used to trigger a task without a message. The ajsend call isused to send a message to a task. The ajsenw call is used to send a message to a task andwait for it to be received and acted upon. In response to any of these calls, AMX primesthe task for subsequent execution. In the case of ajsend or ajsenw calls, the caller'smessage parameters are moved into a message envelope. The envelope is then inserted inthe destination task's mailbox at the priority level indicated by the caller.

Requests to start a task can be issued in any of the following application modules.

Restart ProcedureApplication TaskInterrupt Service ProcedureTimer Procedure

The Restart Procedure provides the first opportunity to start an application task. Atstartup, after all predefined tasks have been created, AMX executes all of the RestartProcedures described in the Restart Procedure List. A Restart Procedure can be used torequest execution of one or more tasks in the system. The AMX Task Schedulersubsequently starts the highest priority task capable of execution.

Once a task is executing, it is allowed to request the execution of any task in the system,including itself. A task can use the ajsend or ajsenw call to send a message to anothertask. The ajsenw call is only available to tasks. A task issuing an ajsenw call to AMXsuspends itself (waits) until such time as the called task has executed in response to thecall. AMX guarantees that the called task is executed in response to one caller at a time.

Requests for task execution can also be initiated in response to device interrupts. Whenan interrupt occurs, the device Interrupt Service Procedure (ISP) is executed. The ISPcan issue an ajtrig call to start a particular task. It can issue an ajsend call if a messagemust be sent to the task being called. Whenever an ISP requests to start a task, AMXtemporarily suspends the interrupted task, thereby leaving it in a state ready to resumeexecution. The AMX Task Scheduler is then invoked to start (or return to) the highestpriority task ready for execution. It is this type of operation that permits a task to beginexecution in response to an event which is considered to be of higher priority than thetask which was running.

AMX also permits tasks to be executed at periodic intervals. For example, a periodicapplication interval timer (see Chapter 5) can be started by your application. When thetimer expires, the AMX Kernel Task executes the associated application TimerProcedure. The Timer Procedure can issue an ajtrig or ajsend call to AMX to requestexecution of any given task.

30 KADAK Application Tasks

3.4 Task PriorityTask priorities are used by the AMX Task Scheduler to determine which task to execute.At all times, the task with the highest priority which is capable of execution will run.

A task's priority is defined at the time the task is created. Task priorities range from 0(highest) to 255 (lowest). Priorities 0 and 128 to 255 inclusive are reserved for AMXuse. The AMX Kernel Task executes at priority 0 above all other tasks.

Application tasks can be assigned priorities 1 to 127 inclusive. Since the number ofpriority levels exceeds the maximum number of possible tasks, it is evident that prioritylevels do not have to be shared.

If more than one task is assigned the same priority, AMX will assign the tasks relativepriorities according to the chronological order in which they were created with the firstcreated task having the higher priority.

A task may change its priority or the priority of any other task. This practice is notrecommended however. Experience has shown that this facility is rarely required and alltoo often is abused. The task's new priority remains in effect until you decide, if ever, tochange it again.

Application Tasks KADAK 31

3.5 Task Execution

AMX starts a task by making a FAR procedure call to the task. AMX starts execution of atask at the task start address specified in the task's definition. The task is started inresponse to a request for its execution. Requests can come from Restart Procedures,tasks, Interrupt Service Procedures or Timer Procedures (see Chapter 3.3).

AMX starts the task when no tasks of higher priority are capable of execution. A taskcan therefore only execute if all higher priority tasks are idle or suspended for somereason.

When AMX starts the task, the following conditions exist:

Interrupts are enabled.All registers are free for use.DS,ES DGROUP segmentSS:SP Task stack ready for useBP Offset of received message on stackThe direction flag is set to forward.

Tasks started in this manner can be readily coded in C or assembler.

A message may have been passed to the task. Message passing is described in moredetail in Chapter 3.9. A task receives message parameters on its stack. The processorbase pointer register (BP) is initialized by AMX to the offset of the first byte of a messageon the task stack.

A caller's message parameters are moved into a message envelope by AMX fortransmission to a task. When the task starts, the parameters in the message envelope aretransferred to the task's stack and the envelope is automatically released for reuse.

The number of parameter bytes that can be passed to a task is configured by you in theAMX User Parameter Table. The content of the message is completely user defined.

Once a task begins execution, it has complete control of the processor. The interruptsystem must be left enabled to permit device interrupts to be serviced. If a task mustdisable interrupts for some reason, it is recommended that this period be kept as short aspossible so that the system's interrupt response time is not degraded.

The application task can execute without concern for the fact that interrupts will occurand will be serviced. If higher priority tasks become ready for execution, the task will besuspended temporarily by AMX. When higher priority tasks become suspended or havecompleted their operation, the interrupted task will be permitted by AMX to resumeexecution from its point of interruption.

Occasionally a task must perform a sequence of operations without interference by othertasks. If the sequence is too long to permit interrupts to be disabled, the task can requestAMX to become temporarily privileged. During the period of privileged execution,interrupts remain enabled but execution of any higher priority task, including the AMXKernel Task, is inhibited. Privileged operations should be kept as short as possible.

32 KADAK Application Tasks

3.6 Task and Event SynchronizationAMX offers several simple forms of task/event synchronization.

Using the ajwait call, a task can unconditionally wait for an event. The event can betask dependent, device dependent or time dependent. The task, having issued an ajwaitcall, remains suspended unconditionally until another task, an Interrupt Service Procedureor a Timer Procedure issues an ajwake call requesting AMX to wake up the particularwaiting task. This ajwait/ajwake pair can be used to provide simple eventsynchronization.

AMX also supports this form of synchronization with an automatic timeout facility. Atask can issue an ajwatm call specifying the maximum interval which the task is willingto wait for the event to occur. If no other task, ISP or Timer Procedure issues an ajwakecall in the interim, AMX will automatically wake up the task when the interval expires.The task receives from AMX an indication whether or not a timeout occurred.

A more powerful and flexible form of task/event synchronization is supported by tasksignals. Each task owns a set of 15 user defined task signals. A task can issue anajsgwat call to wait, with optional timeout, for a specific combination of signals to beset.

Tasks, ISPs and Timer Procedures can call AMX procedure ajsgnl to set any of aparticular task's task signals when corresponding events are detected. The task receivesan indication whether or not a timeout occurred.

A task can also be synchronized to another task using the AMX call and wait messagepassing facilities. A task sends a message to another task using the AMX ajsenw callwhich forces the sender to wait. When the receiving task eventually receives the sender'smessage, it can issue an ajwakc call to wake the calling task. The sender will thenresume execution knowing full well that its message has already been received by thetask to which it was sent. If the receiving task does not issue an ajwakc call, AMX willdo so automatically when the receiving task ends. No timeout is provided with this typeof synchronization.

These synchronization facilities offer the advantage of simplicity. These mechanisms arean inherent part of the AMX kernel. The disadvantage of each is that the event signallermust know the task id of the task which is waiting or to whom a message must be sent.

Application Tasks KADAK 33

The simple features included in the AMX kernel are augmented by three powerfulmechanisms for event synchronization provided by separate AMX managers.

The Semaphore Manager provides counting semaphores with queuing and timeoutfacilities for mutual exclusion and resource management. It also offers a unique resourcesemaphore which extends to semaphores the concept of ownership of the correspondingresource.

The Event Manager offers the best solution for complex event coordination. It permits atask to be synchronized to any or all of a particular set of events. It also allows more thanone task to wait for the same events.

The Message Exchange Manager allows a task to be synchronized to another task usingits call and wait message passing facilities. It allows one or more tasks to wait at amessage exchange for the arrival of a message. Tasks, ISPs and Timer Procedures cansend messages to the message exchange using the AMX ajmxsnd call. The receivingtask must use the AMX procedure ajmxwat to wait for a message at the messageexchange.

Each of the synchronization methods provided by the managers share several commonfeatures. In each case, the signaller does not need to know the identity of task(s) waitingfor its signal. When multiple tasks wait on a semaphore, event group or messageexchange, each task specifies the priority at which it wishes to wait. Finally, any taskwaiting on a semaphore, event group or message exchange can specify the maximuminterval which the task is willing to wait.

34 KADAK Application Tasks

3.7 Task TimingThe AMX Clock Handler and Kernel Task act as a Timer Manager providing timingfacilities for use by tasks. It has been shown in Chapter 3.6 that tasks can wait for anevent to occur with an automatic timeout. The task is suspended following its waitrequest until the event occurs or the interval specified in the call expires.

The ajwatm call to AMX can also be used by a task to implement a delay. The delayinterval is specified in system ticks. The task is suspended until the interval expires.AMX assures that the task automatically resumes execution, provided that no higherpriority task is able to execute.

Other timing functions required by the task can be implemented using interval timers (seeChapter 5). Timers are 32-bit counters. Timing resolution is in multiples of the systemtick. The AMX routine ajtmcnv is available to convert milliseconds to the equivalentnumber of system ticks.

Timers can be created at any time by a call to the AMX routine ajtmcre.

A timer is started by writing the timer period to it using the AMX routine ajtmwr. At anyinstant, a task can read the time remaining in the interval by calling AMX routineajtmrd. A timer can be stopped by writing zero to it. A timer can be deleted when it isno longer required by a call to ajtmdel. These simple procedures give the task completecontrol over interval timing.

Whenever an interval timer expires, AMX executes an associated Timer Procedure.Using this feature, a task can start an interval timer and rest assured that, when theinterval expires, the action determined by the associated Timer Procedure will beperformed. Since the Timer Procedure is called by the AMX Kernel Task which has thehighest priority in the system, the Timer Procedure executes at a priority higher than thatof any application task.

Interval timers must be used by tasks wishing to measure time. Instruction countingloops are of no value in a multitasking system. Since a task is being constantlyinterrupted and occasionally suspended to execute higher priority tasks, any timingperformed by counting instructions within a program loop will be in error.

Application Tasks KADAK 35

3.8 Ending a TaskWhen a task completes its appointed function, it must relinquish control of the processorto AMX. The AMX Task Scheduler will then give control of the processor to the nexthighest priority task ready to execute.

AMX starts a task by a FAR procedure call to the task at the task start address. The taskprogram is, therefore, a procedure. When the task is finished, it returns to AMX innormal end-of-procedure fashion.

A task may wish to abort execution under error conditions. The task's stack may bedeeply nested when the error condition arises. To allow a task to terminate under thesecircumstances, AMX provides the ajend exit facility. Any task which calls ajend isimmediately terminated by AMX.

When a task is triggered or a message is sent to a task, the task receives a request toexecute. A task executes once for each such request. When the task ends, AMXexamines the task to determine if any additional requests for execution of the task arepending. If outstanding requests are present, AMX flags the task as ready to run again.The AMX Task Scheduler will then immediately start this task again. This processcontinues until the task finally ends and no requests for execution of the task are present.At that time, AMX places the task into the idle state.

If the task has received a message, AMX must perform some additional processing whenthe task ends. AMX checks to see if the message came from a task. If so, AMX tests tosee if the sender is waiting for the termination of the task just ending. If the sender iswaiting, AMX sets it into the ready state ready to resume execution.

It is possible that an application task may never end. Such a task, once started, runsforever. For example, a task might wait for an event and then do some event-dependentprocessing. Once the processing is complete, the task waits for the next event.

In this example, the task never reaches a logical end. Note, however, that the task doesbecome suspended awaiting an event. A task which has no logical end and which neversuspends itself is said to be compute bound.

Even if a task does wait, it is still possible that the task may effectively be computebound. For instance, assume that a low priority task repetitively sends a message to ahigher priority task and waits for an answer. Also assume that the higher priority taskwill always provide an immediate response. In this case, the lower priority task willalways be allowed to resume after its message is sent even though a temporarysuspension does occur. The task will block all lower priority tasks.

Note

A compute bound task inhibits execution of all lowerpriority tasks.

36 KADAK Application Tasks

3.9 Message PassingAMX supports the passing of a message to a task mailbox or message exchange.

Messages can be sent to a task by:

Application TasksInterrupt Service ProceduresTimer ProceduresRestart ProceduresExit Procedures

You can send a message to a task mailbox or message exchange using the AMXprocedure ajsend (or its variation ajsendp) or ajmxsnd respectively. The maximumnumber of parameter bytes that can be sent in a message is configured by you in yourSystem Configuration Module. The parameter bytes are completely applicationdependent.

Messages must be integer aligned. In the following examples, it is assumed that your Ccompiler aligns arrays and structures on boundaries that are integer aligned.

int i;short int iarray[6];char carray[12];struct msg {

char m1;char m2;short int m3;long m4;} msga;

The following calls will send the specified message to the mailbox of the task with idtaskid or to the message exchange with exchange id mxid . The messages are sent atpriority 3.

int priority = 3;ajsend(taskid, priority, &c); /* Send c */ajsend(taskid, priority, &i); /* Send i */ajsend(taskid, priority, iarray); /* Send iarray */ajmxsnd(mxid, priority, carray); /* Send carray */ajmxsnd(mxid, priority, &msga); /* Send msga */

The messages are stored in FIFO order in the task mailbox or message exchange messagequeue. The caller specifies the priority level of the message. The priority level (0, 1, 2 or3) determines the message queue (mailbox) into which the message will be placed.

If the caller is a task sending a message to another task, it can request AMX to suspendits operation until the called task has executed in response to the request. This isaccomplished by calling ajsenw (or its variation ajsenwp) rather than ajsend.

Application Tasks KADAK 37

AMX uses message envelopes for parameter transmission. AMX gets a free envelope,moves the caller's message parameters into it and adds the envelope to the task mailboxor message exchange message queue.

If the sender requested to wait, AMX inserts information into the envelope which allowsAMX to remember that the sending task has been suspended waiting foracknowledgement of the receipt of its message by some other task.

Note that when AMX returns from a call to send a message, the memory occupied by thecaller's message is available for reuse by the caller.

Note

AMX always copies MAXMSZ bytes from the sender'smessage into the envelope. MAXMSZ is defined in yourAMX System Configuration Module and is >= 12.

Hence, the transmitted message will always be MAXMSZbytes in length even if your message is a single integer.

For assembly language programmers, procedure AASEND is used to send a message to atask and to wait if desired.

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;MSGA DB ? ;m1

DB ? ;m2DW ? ;m3DD ? ;m4

;MSGAD DD MSGA ;pointer to MSGATASKID DW ? ;taskid;USERPROC PROC FAR

LES BX,CS:MSGAD ;ES:BX = A(MSGA)MOV DX,CS:TASKID ;DX = task idMOV CH,0 ;CH = 0 (no wait)

; ;CH = 80H (wait)MOV CL,2 ;CL = priority (0,1,2 or 3)CALL AASEND ;send the messageRET

;USERPROC ENDP;USER_CODE ENDS

38 KADAK Application Tasks

Figure 3.9-1 provides an example of the manner in which messages are allowed to queueon a message exchange. The same message queuing technique is used when messagesare sent to a task's private mailboxes within its Task Control Block (TCB).

In the example, the following situation is assumed to exist at the message exchange onwhich the destination task is waiting.

The message exchange has four message queues corresponding to the four priority levelsat which it can post messages. Level 0 is the highest priority; level 3 is the lowestpriority. The example shows that no messages are pending on levels 0 or 2. Threemessages, I, J and K, are pending on level 1. Two messages, L and M, are pending onlevel 3. One message, X, is currently being serviced by the destination task.

The destination task has been interrupted and it is ready to resume execution. As a resultof the interrupt, task YY was allowed to execute because it was of higher priority than thedestination task. Task YY made a request to AMX to send a message to the messageexchange at message priority level 1. As a result of this request, AMX moved themessage parameters from task YY into a message envelope and added this envelope tothe bottom of the level 1 message queue associated with the message exchange. Theresult is shown in Figure 3.9-1.

Message KMessage J

Message IMessage M

Message L

Message YY

0 2 31

MESSAGE EXCHANGE

Message Xbeing processed

Figure 3.9-1 Message Transmission

Application Tasks KADAK 39

In due course the destination task will continue to execute and complete its processing ofthe current message, X. The destination task will then request AMX for a message fromthe message exchange three more times in succession to process messages I, J and K.Finally, the message from task YY will be retrieved from the message exchange andprocessed.

Figure 3.9-2 illustrates the situation at the destination task at the instant it begins toprocess the message from task YY. Provided that no additional calls to post messages tothe message exchange have occurred, the messages will be as shown. Message queues 0,1 and 2 are empty. Messages L and M are still pending at priority level 3. The messagefrom task YY is ready for processing by the destination task.

When the destination task retrieves a message from the message exchange, the messageparameters are already removed from the envelope and copied to the storage areaprovided by the task, usually on the task's stack. The message parameters received by thedestination task are in exactly the same order as they were sent by the caller.

Message MMessage L

0 2 31

MESSAGE EXCHANGE

Message YYbbeeiinngg pprroocceesssseedd

Figure 3.9-2 Message Reception

40 KADAK Application Tasks

It is important to note that a copy of the sender's message parameters is sent to thedestination task. Once the sender's parameters have been copied into the messageenvelope, the caller is free to reuse the parameter storage if desired. Thus, as soon asprocedure ajsend or ajmxsnd (or any of their variations) returns to its caller, theparameter variables are free for reuse.

A message which is delivered to a task in one of its mailboxes is copied directly to thetask's stack prior to starting the task. However, when a message exchange is used, thedestination task must provide a pointer to storage large enough to hold the entire messagewhich it will receive. Since AMX unconditionally delivers messages of MAXMSZ (>= 12)bytes in length, the message storage must be of at least that size.

The AMX task which receives a variety of messages should declare a union rmsg in orderto reference the different messages. Note that the union should include one instance of anarray amxmsg consisting of three long values to ensure that rmsg is large enough to holdany AMX message.

union rmsg {long amxmsg[3];char c;int i;short int iarray[6];char carray[12];struct msg msga;};

Then the task can be written as follows:

void taskn(int dummy){

union rmsg *pmsg;

pmsg = (union rmsg *)&dummy; /* Pointer to received message */::The received message can now be accessedusing union pointer pmsg.:}

In this simple example, the task receiving the messages has no obvious way ofdetermining how to interpret the message. Is the message one character (pmsg->c) or awhole structure (pmsg->msga)? This dilemma is usually solved by including anapplication specific operation code with all messages.

Note that we have declared the task's received message as an integer and then usedpointer variable pmsg to access the parameters in the message. AMX passes parametersby value with no concern for the restrictions imposed by various high level languages.Hence a whole array or structure can be passed by value by AMX to a task. However,not all C compilers support such parameter passing.

Application Tasks KADAK 41

Message Extension

AMX delivers messages to a task by copying the message from a message envelope to amessage frame on the task's stack. AMX also presents an extension to the applicationmessage on the task's stack. The message extension identifies who sent the message and,if a task, whether the sender is waiting for a response.

The message extension is provided for the use of private AMX tasks such as the KernelTask. Application tasks should rarely be aware of its presence.

Access to the message extension is illustrated in the following C example. Refer toAppendix D for a description of the message extension structure amxmsgxs. Assemblerprogrammers will find the message extension on the task stack at SS:BP+UMS where UMSis the size of your application messages declared in your AMX User Parameter File.

#include "amx831sd.h" */ AMX Structure Definitions */#define UMS 12 */ User message size */

void taskn(int dummy) */ Dummy parameter declaration */{

struct amxmsgxs *msgxp; /* Message extension pointer */

msgxp = (struct amxmsgs *)((char *)&dummy + UMS);:The message extension can now be accessedusing pointer msgxp.:}

42 KADAK Application Tasks

3.10 Restart ProceduresThe manner in which the operating system begins execution is application dependent.Execution begins in the user domain providing the opportunity for hardware specific andapplication dependent setup prior to the initialization of the AMX system. For example,hardware interfaces may require custom configuring. In some systems, it might bedesirable to perform a memory integrity check before system startup is permitted.

AMX will enable or disable the interrupt system at the time you launch AMX, as dictatedby the launch parameter you provide when you start AMX.

Once AMX has initialized all of its internal variables and structures, it executes thesequence of application Restart Procedures provided in the Restart Procedure List in yourSystem Configuration Module (see Chapter 14.6). These procedures can invoke AMXservices to start tasks and initialize interval timers.

When AMX calls a Restart Procedure, the following conditions exist:

Interrupts reflect the state specified at the time AMX waslaunched. If AMX was launched with launch parameter AMLPIE,interrupts will be enabled. Otherwise interrupts will be disabled.

All registers are free for use.DS,ES DGROUP segmentSS:SP AMX Kernel Stack ready for useThe direction flag is set to forward.

Restart Procedures are written as Large or Medium model C procedures without formalparameters.

void cdecl rrproc(void) /* Restart Procedure */{

:Do restart processing:}

A Restart Procedure is coded in assembly language as a FAR procedure as follows:

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;RRPROC PROC FAR

:Restart Procedure code goes here.:RET

;RRPROC ENDP;USER_CODE ENDS

Application Tasks KADAK 43

Restart Procedures can enable specific device interrupts if required. Note that interruptsfrom a device should not be enabled until the application ISP has been installed and madeready to handle the interrupting device.

Restart Procedures should not enable the processor interrupt system if your launchparameter indicated that AMX was to execute with interrupts disabled during the launch.In this case, AMX will disable interrupts upon completion of your Restart Procedure.

A Restart Procedure must not issue any AMX directives which would in any waysuspend or terminate task execution.

Restart Procedures use the AMX Kernel Stack. In addition to the minimum stack sizerequired for the AMX Kernel Stack, you must allocate sufficient stack to satisfy the worstcase requirements of all application Restart Procedures.

Note

Restart Procedures must only use AMX services which aremarked in Chapter 16 as� Restart Procedure

44 KADAK Application Tasks

3.11 Exit ProceduresAn AMX system can be shut down in an orderly fashion by a task call to procedureajexit. The manner in which the operating system ends execution is applicationdependent. For example, hardware interfaces may require restoration to their initialstates.

AMX supervises the shutdown process by sequentially calling all of the application ExitProcedures in the order defined in the Exit Procedure List in your System ConfigurationModule (see Chapter 14.6). Once all Exit Procedures have been executed, AMX returnsto the original program that launched AMX with an ajentr call.

When AMX calls an Exit Procedure, the following conditions exist:

Interrupts are enabled.All registers are free for use.DS,ES DGROUP segmentSS:SP Task stack which was in effect when ajexit was called.The direction flag is set to forward.

Exit Procedures are written as Large or Medium model C procedures without formalparameters.

void cdecl epproc(void) /* Exit Procedure */{

:Do exit processing:}

An Exit Procedure is coded in assembler as a FAR procedure as follows:

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;EPPROC PROC FAR

:Exit Procedure code goes here.:RET

;EPPROC ENDP;USER_CODE ENDS

Application Tasks KADAK 45

Exit Procedures execute in the context of the task which issued the ajexit call. They aretherefore free to use all services normally available to tasks. For instance, an ExitProcedure could use ajsenw to send a shutdown message to a task and wait for that taskto do its shutdown processing. When the Exit Procedure resumes after the ajsenw call, itreturns to AMX which then calls the next Exit Procedure in the list.

An Exit Procedure must not issue any AMX directives which would in any way terminatetask execution.

Exit Procedures use the stack of the task which called ajexit. It is therefore essentialthat the task which calls ajexit be allocated sufficient stack to satisfy the worst caserequirements of all application Exit Procedures.

Note

Exit Procedures must only use AMX services which aremarked in Chapter 16 as� Exit Procedure

Warning

If any Exit Procedure is coded using the Medium model,the task which calls ajexit MUST also use the Mediummodel.

46 KADAK Application Tasks

3.12 Task EnhancementsAMX offers several task enhancements which, although rarely used, can occasionallycome in handy. These enhancements are briefly summarized below.

Task Control Block Extension

Within a task's Task Control Block, 16 bytes are reserved for the private use of the task.Their use is completely determined by the application.

A Task Control Block for a particular task can be located using procedure ajtktcb. Theprivate storage is located at offset AMTCBUSR in the Task Control Block.

If you are coding in C, you must use structure definition amxtcbs from header fileAMX831SD.H to access this storage.

If you are coding in assembly language, you must use structure definition AMXTCBS fromheader file AMX831SD.DEF to access this storage.

Stack Fences

When AMX creates a task, it installs a fence at the top and bottom of the task's stack.The fence is a 32-bit value containing the unusual pattern 0x55555555 ('UUUU').

The 4-character task tag is copied to the stack immediately below the top fence as adebugging aid to identify each stack's owner.

These fences can be of significant help during the development and testing of your AMXsystem. When you are trying to detect a fault in your system, it is often advisable toexamine your task stacks carefully to be sure that none of the fences have been altered.An altered fence is an indication that you have a task which is overflowing orunderflowing its stack or, worse yet, a bad piece of code which is writing to some task'sstack in error.

Application Tasks KADAK 47

AMX Kernel Task Priority

The AMX Kernel Task operates as the highest priority task in your AMX system. Itsexecution priority is zero. It has the reserved task tag 'AMXK'.

Occasionally, an application is encountered in which a task must execute at very highpriority in order to cope with the idiosyncrasies of an extremely high speed device. Insuch cases, the priority of the AMX Kernel Task can be dropped from zero to some lowerpriority determined by you for your application. To do this, you must call AMXprocedure ajtkpry to change the priority of the AMX Kernel Task.

It is recommended that you exhaust all other avenues of approach to the high speeddevice handling problem before taking this way out. Usually, high speed devices are besthandled at the interrupt level using the techniques described for special interrupts inChapter 4.7.

If you choose to drop the priority of the AMX Kernel Task, you must pay a penalty. Anytask which you place at a priority higher than the AMX Kernel Task is not allowed to useany of the following AMX services:

Raise privilege levelTimed waitsInterval timer operationsSemaphore Manager servicesEvent Manager servicesMessage Exchange Manager servicesMemory Manager services

48 KADAK Application Tasks

This page left blank intentionally.

Interrupt Service Procedures KADAK 49

4. Interrupt Service Procedures

4.1 The Processor Interrupt FacilityThe key to event-driven, real-time, multitasking systems is the processor's interruptfacility. Tasks execute with the interrupt facility enabled permitting the system torespond to a real-time event.

The hardware interrupt mechanism is an automatic facility provided by the processor.AMX permits the system designer to determine how the hardware interrupt facility willbe employed.

Tasks must execute with the interrupt facility enabled.

From time to time, AMX must inhibit interrupts while it performs a critical, indivisiblesequence of operations. AMX keeps such intervals very short. For instance, even whileAMX is switching from one task to another, it is able to respond to interrupts.

To further improve interrupt response, AMX permits nesting of interrupts on processorswhich support this feature. As soon as the interrupt request has been cleared, interruptscan be enabled to permit response to other external events.

When an interrupt occurs, the processor disables the interrupt facility and stores the flagsand return address on the current stack to permit the processor to eventually resume theinterrupted process. In some cases, an internal or external interrupt mask is set to inhibitnew requests of priority less than or equal to the priority of the device being serviced.

Hardware external to the processor usually identifies the interrupt source. The processoruses this identification to automatically fetch a unique device dependent pointer from theprocessor vector table and branch to the address specified by that pointer. The programlocated at that address is called an Interrupt Service Procedure (ISP).

In general, an ISP saves the registers it wishes to use, services the device, restores theregisters, enables the interrupt system and returns to the executing program at the point ofinterruption.

If more than one device is connected to the same external interrupt source, your ISP mustdetermine the interrupt source in one of several ways. The simplest, but slowest, is asoftware poll of the devices. The ISP tests each device sequentially to determine thesource of the interrupt and branches to a device service procedure to handle the specificinterrupt.

Alternatively, external hardware can be added to provide unique vectoring for eachdevice which can generate interrupts. If this approach is adopted, then a separate ISPmust be provided for each device.

The AMX Interrupt Supervisor simplifies ISP operation within the AMX multitaskingenvironment. The AMX Interrupt Supervisor permits an ISP to communicate with anytask in the system. The remainder of this chapter describes how ISPs are used within asystem.

50 KADAK Interrupt Service Procedures

When used with the 8086 family of microprocessors, AMX supports the followingexception and interrupt sources:

Divide error (DIV or IDIV instruction)Non-Maskable interrupt (NMI hardware signal)Overflow (INTO instruction)Bounds error (BOUND instruction)External devices (INTR hardware signal)

All other special processor exceptions such as invalid opcode (type 6) or the 80386general protection exception (type 13) are not handled by AMX. They must bespecifically serviced by your own exception handler.

The design and implementation of the interrupt structure used in a particular applicationis completely under your control. Significantly, AMX does not use any of the softwareinterrupts such as the Single-Step or INT n interrupts. They are left for application andtesting use.

Interrupt Service Procedures KADAK 51

4.2 ISPs for External InterruptsTwo types of ISPs exist: nonconforming ISPs and conforming ISPs.

Nonconforming ISPs

A nonconforming ISP must quickly service the device to remove the interruptingcondition. The ISP must preserve all registers which it uses. The nonconforming ISPcannot make calls to any AMX service procedures.

The nonconforming ISP executes in the context of the process (task, ISP, AMX kernel)which was interrupted. The ISP therefore uses the stack of the interrupted process.Consequently, all stacks must be large enough to meet the worst case needs of allnonconforming ISPs.

The nonconforming ISP can enable interrupts to allow interrupt service by other higherpriority nonconforming ISPs. The nonconforming ISP MUST NOT allow an interrupt toa conforming ISP.

Conforming ISPs

A conforming ISP is intended for use with AMX. A conforming ISP consists of an ISProot and an Interrupt Handler. Often these two components are merged indistinguishablyinto one body of code. The processor vectors to the ISP root which informs the AMXInterrupt Supervisor that the interrupt has occurred. The Interrupt Supervisor preservesthe state of the interrupted task and, if necessary, switches to an interrupt stack. Uponreturn to the ISP root, the associated Interrupt Handler is called. Your handler mustperform all services required by the device. Your handler is free to make procedure callsto a subset of the AMX service facilities.

The conditions that will exist upon entry to your Interrupt Handler are dependent uponthe tool set which you are using and the language in which your Interrupt Handler isprogrammed. In general:

Interrupts are disabled (masked) at a device dependent priority level.A subset of the registers are free for use.The AMX Interrupt Stack is in use.

When your Interrupt Handler executes, external interrupts of priority less than or equal tothe interrupting device are always disabled. Your Interrupt Handler must NOT enableany interrupts of lesser or equal priority. Your handler can enable higher priority externalinterrupts if permitted by your target hardware and your application software design.

When device service is completed, your Interrupt Handler returns to the ISP root whichinforms the AMX Interrupt Supervisor that interrupt service is complete.

AMX monitors calls made by the Interrupt Handler to AMX service procedures. If nosuch calls have been made, the AMX Interrupt Supervisor automatically restores the stateof the interrupted task and allows the ISP root to return directly to the interrupted task atits point of interruption.

52 KADAK Interrupt Service Procedures

If the Interrupt Handler requested AMX to initiate or resume execution of some task ofhigher priority than the interrupted task, the AMX Interrupt Supervisor suspends theinterrupted task and marks it as ready to resume execution at the earliest opportunity.The AMX Task Scheduler is then invoked to determine the highest priority task capableof execution.

If interrupts nest, the Interrupt Supervisor defers its task switching checks until all of theconcurrent interrupts have been serviced.

In due course, AMX returns to the ISP root ready to resume execution at the point ofinterruption. It is important to note that, because of task switching invoked by the AMXInterrupt Supervisor, there may be a significant delay before AMX returns to the ISP rootand resumes execution of the interrupted task.

Note

Interrupt Handlers must only use AMX services which aremarked in Chapter 16 as� ISP

The Interrupt Handler is free to use the following AMX service procedures tocommunicate with tasks. If the affected task is of higher priority than the task which waspreempted by the interrupt, AMX will initiate a task switch when the interrupt service hasbeen completed.

ajsend AASEND Request a task to execute and send it a messageajtrig AATRIG Request a task to execute with no messageajwake AAWAKE Wake a task known to be waiting for this interruptajsgnl AASGNL Signal a taskajsmsig AASMSIG Signal to a semaphoreajevsig AAEVSIG Signal an eventajmxsnd AAMXSND Send a message to a message exchange

Interrupt Handlers are also free to use the following AMX buffer management and timingfacilities.

ajbget AABGET Get a bufferajbfre AABFRE Free a bufferajbau AABAU Add to buffer use count

ajtmwr AATMWR Start/stop an interval timerajtmrd AATMRD Read an interval timer

The full range of AMX circular list handling routines (see Chapter 11) can be used byapplication Interrupt Handlers. These circular lists can be especially useful to providecharacter buffering. For example, an input device Interrupt Handler can add characters tothe bottom of a circular list while a related task removes them from the top of the list.

The AMX List Manager services (see Chapter 12) can also be used by Interrupt Handlers.Note that an Interrupt Handler should not manipulate keyed lists.

Interrupt Service Procedures KADAK 53

Conforming ISP Construction

The construction of an Interrupt Service Procedure (ISP) to service an external interruptis a simple process.

The conforming ISP consists of two parts: the ISP root and your Interrupt Handler. TheISP root is a code fragment most easily created using procedure ajispm.

The Interrupt Handler can be written in as a Large or Medium model C functionwithout formal parameters. If the C function makes any calls to AMX, restrictions forISPs must be obeyed. The following example of a device Interrupt Handler illustrateshow little application code must be programmed to satisfy AMX.

If the processor Interrupt Vector Table (IVT) is in RAM and AMX was launched withvector access allowed, you can install the pointer to the ISP root into the IVT using AMXfunction ajivtw. Otherwise, you must initialize the device's entry in the IVT asdescribed in Chapter 4.8 before launching AMX. The following example assumes thatthe device interrupts through vector number 32.

#include "amx831cf.h" /* AMX C Interface Header */static struct amxisps isproot; /* ISP root */

void cdecl dvcisp(void){

local variables, if required:Perform all device service.Interrupts may be enabled using ajei() if nested interruptsare supported by your design.:

/* If necessary, disable interrupts and clear the request in *//* one or more interrupt controllers (such as the Intel 8259). */

ajdi(); /* Disable interrupts */ajoutb(0x20, 0x20); /* Non-specific EOI */}

void cdecl rrproc(void) /* Restart Procedure */{

ajispm(dvcisp, &isproot); /* Make ISP root */

ajivtw(32, (void (*)())&isproot); /* Install ISP in IVT */}

The ISP root created by AMX in static variable isproot is an ISP coded as follows:

ISPROOT LABEL FARCALL AAINT ;begin interrupt serviceCALL DVCISP ;ISPCALL AAINX ;end interrupt serviceIRET ;end of interrupt

54 KADAK Interrupt Service Procedures

The Interrupt Service Procedure should be coded using assembly language if speed ofexecution is critical.

EXTRN AAINT:FAREXTRN AAINX:FAR

;DVC_CODE SEGMENT BYTE 'CODE';

PUBLIC DVCISP; The ISP is located in user program memory;

ASSUME CS:DVC_CODE;DVCISP PROC FAR

CALL AAINT ;let AMX know::Perform all device service.All registers are free for use.Interrupts may be enabled if nesting is supported.::If necessary, disable interrupts and clear the request inone or more interrupt controllers (such as the Intel 8259).CLI ; Disable interruptsMOV AL,20HOUT 20H,AL ; Non-specific EOICALL AAINX ;let AMX knowIRET ;return from interrupt

;DVCISP ENDP;DVC_CODE ENDS

If the processor Interrupt Vector Table (IVT) is in RAM and AMX was launched withvector access allowed, you can install the pointer to the ISP into the IVT using AMXfunction AAIVTW. The ISP begins execution at address DVCISP. The ISP calls the AMXInterrupt Supervisor (AAINT) to inform AMX that the interrupt has occurred.

Interrupt Service Procedures KADAK 55

The AMX Interrupt Supervisor, when invoked, switches to an Interrupt Stack providedby you in your System Configuration Module. The AMX Interrupt Supervisor thenreturns to the application ISP. The ISP must perform all services required by the device.

Upon return to the ISP from the AMX Interrupt Supervisor entry procedure AAINT, theregisters are initialized as follows.

Interrupts are disabled.All registers are free for use.DS,ES DGROUP SegmentSS:SP AMX Interrupt Stack ready for useCX,DX,SI Unaltered by procedure AAINTThe direction flag is set to forward.All other registers are undefined.

It should be noted that AMX procedure AAINT preserves registers CX, DX and SI. Thisfeature can be used to advantage when creating special ISPs like those described inChapter 4.7.

The external interrupt facility is disabled. Your ISP can enable the external interruptfacility if so desired. In this case, the ISP must be sure to either clear the source of theinterrupt before enabling interrupts or to mask (disable) the interrupt source if thehardware exists to do so.

When the interrupt service is complete, the ISP informs the AMX Interrupt Supervisor byissuing the termination call to AAINX. The final IRET instruction restores the processorflags register and returns to the point of interruption.

It is important to note that, because of task switching invoked by AAINX, there may be asignificant delay before AMX returns to your IRET to resume execution of the interruptedtask. No device operations, AMX calls or commands to an interrupt controller such asthe Intel 8259 chip are allowed after the call to AAINX.

56 KADAK Interrupt Service Procedures

4.3 Nested InterruptsAMX supports nested interrupts. The AMX Interrupt Supervisor maintains a privatenesting level indicator. AMX must be informed of the start (AAINT) and end (AAINX) ofeach interrupt.

When AMX sees that a task has been interrupted, it switches to a predefined InterruptStack. If AMX detects that the interrupt has occurred during execution of a deviceInterrupt Service Procedure, then no stack switching occurs. The interrupted ISP issuspended and the new ISP is started.

When an ISP ends, AMX takes action based on the state of its nesting indicator. When anested interrupt ISP is completed, AMX returns to the interrupted ISP. When the lastinterrupt ISP (corresponding to the first task interrupt) is completed, AMX prepares toreturn to the interrupted task. If, as a consequence of interrupt service, a significant eventhas been declared, AMX suspends the interrupted task and goes to the AMX TaskScheduler to find the highest priority task which is ready to execute.

Since the AMX Interrupt Stack is used for nesting interrupts, the stack size must be largeenough to support the worst case combination of nested ISPs. Each nested interruptrequires that the Interrupt Stack be increased to meet the needs of the additional nestedISP.

Warning

You must not permit a conforming ISP to interrupt anonconforming ISP.

The AMX clock ISP is a conforming ISP.

Interrupt Service Procedures KADAK 57

4.4 ISP/Task CommunicationAMX provides a set of service procedures to ease the communication between tasks anddevice Interrupt Handlers. These AMX procedures simplify event synchronization andpermit parameter passing to tasks.

Wait/Wake Synchronization

The ajwait/ajwake pair of procedures is often used for event synchronization. A taskissues an ajwait call to AMX to wait unconditionally for an event. When the eventoccurs, as indicated by an interrupt, the Interrupt Handler makes an ajwake callidentifying the task which it wishes to wake up.

Synchronization capability can be further enhanced using the automatic timeout facilityprovided by AMX. The task issues an ajwatm call indicating the maximum interval forwhich it is willing to wait for the event. When the interrupt occurs, the Interrupt Handlerissues the ajwake call to wake up the task. The task resumes execution with anindication provided to it by AMX that the event did occur. If, on the other hand, theinterrupt does not occur within the specified timeout interval, the AMX Kernel Task willwake up the task. In this case, the task resumes execution with an indication provided byAMX that a timeout occurred. When the task resumes execution, it is, therefore, capableof determining if the event occurred within the expected interval.

Task Signal Synchronization

The simple wait/wake synchronization described above is actually a subset of eventsynchronization provided by AMX known as task signals. Each task has associated withit a set of 15 independent flags called task signals. The task can wait for any specific tasksignal or combination of task signals by calling ajsgwat indicating the maximum intervalwhich it is willing to wait.

When the interrupt associated with a particular task signal occurs, the Interrupt Handlerissues the ajsgnl call to signal the task that the particular event has occurred. If the taskis not still waiting for other task signals, AMX will allow the task to resume executionwith an indication that its task signal conditions were met. If, on the other hand, all tasksignals for which the task was waiting do not occur within the specified timeout interval,the AMX Kernel Task will force the task to resume execution with a timeout indication.

58 KADAK Interrupt Service Procedures

Semaphore Synchronization

The AMX Semaphore Manager provides an even more powerful synchronizationcapability. It provides the automatic timeout facility and also allows more than one taskto wait for the same event, with each task determining its own waiting priority.Furthermore, the Interrupt Handler need not know the identity of the waiting tasks (ifany) or their chosen waiting priorities. The AMX Semaphore Manager willautomatically ensure that the task with the highest waiting priority is given access to thesemaphore first.

Synchronization using counting semaphores with an initial count of zero is achieved asfollows. A task issues an ajsmwat call indicating the maximum interval for which it iswilling to wait for the semaphore and its chosen waiting priority. When the interruptoccurs, the Interrupt Handler issues an ajsmsig call to wake up the task with the highestwaiting priority that is blocked on the semaphore. The task will always know when itresumes execution whether the event actually occurred or whether the maximum waitinterval elapsed.

Event Group Synchronization

The AMX Event Manager provides another form of synchronization. It allows more thanone task to be waiting for a specific event or for a combination of events. It also providesthe automatic timeout facility. The Interrupt Handler does not have to know which tasks(if any) are waiting for its event.

Synchronization using an event group is achieved as follows. A task clears an event flagin an event group and then issues an ajevwat call indicating the maximum interval it iswilling to wait for the event to occur. The Interrupt Handler issues an ajevsig call to setthe particular event flag for which it is responsible. The Event Manager then allows alltasks which are waiting for that particular event flag to be set to resume execution. Thetask will always know when it resumes execution whether the event actually occurred orwhether the maximum wait interval elapsed.

Message Exchange Synchronization

An Interrupt Handler can communicate with a task by sending a message to a messageexchange. The AMX Message Exchange Manager allows more than one task to wait fora message from a message exchange with each task determining its own wait priority andmaximum wait interval. An Interrupt Handler does not need to know the identity of thewaiting tasks (if any) or their chosen waiting priorities.

Synchronization via a message exchange is achieved as follows. A task calls ajmxwat towait on a particular message exchange indicating the priority of its request and themaximum interval it is willing to wait for a message to arrive.

When the interrupt occurs, the Interrupt Handler calls ajmxsnd to send a message to themessage exchange. The Message Exchange Manager delivers the message to the taskand allows the task to resume execution. If no interrupt occurs before the timeoutinterval expires, the AMX Kernel Task will force the task to resume execution with atimeout indication.

Interrupt Service Procedures KADAK 59

Task Triggering

An Interrupt Handler can communicate with a task by invoking the task's execution.When an interrupt occurs, the Interrupt Handler issues the ajtrig call to AMXidentifying the task which it wishes to have executed.

This technique can be very useful for handling slowly occurring events. For example, adevice generates an interrupt and the Interrupt Handler responds by acquiring a block ofdata from the device. The data is stored in memory by the Interrupt Handler forsubsequent use by a task. The Interrupt Handler then starts the task with the ajtrig call.It is assumed that timing is such that the task will be able to completely process the dataprior to the next occurrence of a similar event. This constraint is typical in many real-time system implementations.

Message Transmission

An Interrupt Handler can also start a task and send it a message. For example, a controlpanel might be used by an operator to initiate actions within a system. An interrupt isgenerated when the operator depresses a pushbutton requesting a specific function. Inresponse to the interrupt, the Interrupt Handler reads a command register at the controlpanel to determine the action to be taken. Data, such as set-point settings, would also beread by the Interrupt Handler.

The Interrupt Handler interprets the command, determines the task in the systemresponsible for performing the requested function, and issues an ajsend call to AMXrequesting execution of that task. The data retrieved from the control panel is transmittedto that task as parameters in the message.

Chapter 3.9 provides a complete description of the parameter passing process.

60 KADAK Interrupt Service Procedures

4.5 Task Error TrapsThe 80x86 processor automatically detects the occurrence of execution errors such asdivision by zero, arithmetic overflow or an array bound violation. These errors, by theirvery nature, must be handled by the application in the context of the task in which theyoccur.

AMX offers tasks a convenient method of trapping such errors. For each task, AMXmaintains a pointer to a task trap handler for each detectable error.

Normally, when a task is running, AMX treats these errors as fatal if they occur. A taskcan specify a trap handler for a particular error trap by calling AMX service procedureajitrp or AAITRP. Thereafter, if the error occurs while running in the context of thetask, the task automatically branches to its trap handler.

Note that the actual processor error exception is completely serviced by AMX. The tasksimply appears to have suddenly jumped to its trap handler.

Divide errors cannot be disabled. Once a task specifies a divide error trap handler, anysubsequent divide error which occurs when that task is executing will cause an immediatejump to the task's divide error trap handler.

Overflow error exceptions do not occur automatically. The task must execute aninterrupt on overflow (INTO) instruction to cause the overflow exception if the overflowflag (OF) is set. If the exception occurs and the task has specified an overflow error traphandler, then AMX will cause the task to jump to that handler.

Bound error exceptions do not occur automatically. The task must execute a boundcheck (BOUND) instruction to cause the bound error exception if specific array bounds areviolated. If the exception occurs and the task has specified a bound error trap handler,then AMX will cause the task to jump to that handler.

AMX maintains unique divide, overflow and bound error trap handlers for each task. If atask is suspended and another task executes, AMX selects the divide, overflow and boundtrap handlers for the new task. When the suspended task resumes, its unique traphandlers are reinstated.

A task trap handler for a particular error trap is reset (cancelled) with a request to AMXto set the pointer to NULL (0L).

When a task is first created, AMX sets the task's trap handlers to NULL forcing errors to befatal until the task specifies its own trap handlers. Once a task defines its trap handlers,they remain defined even if the task ends execution. If the task is subsequently executedagain, its previously defined trap handlers remain in effect unless altered by the task.

If a trapped error exception occurs in a task with no trap handler or in a RestartProcedure, an ISP or a Timer Procedure, AMX initiates a fatal exit as described inChapter 13.1.

Interrupt Service Procedures KADAK 61

The task trap handler can be written as a Large or Medium model C function with formalparameters.

#include "amx831sd.h" /* AMX Structure Definitions*/

void cdecl tdiverr(struct amxregs regs, /* Register structure */void FAR *faultp) /* Fault pointer */{

:Process the error:}

Since the task trap handler executes in the context of the task, the task's stack mustaccount for the stack used by the handler. An additional sizeof(struct amxregs)bytes of stack is required to accommodate the processor dependent stack frame generatedby AMX prior to its call to the trap handler.

AMX provides the address of the fault and the state of each processor register at the timeof the fault.

The error exception is serviced by AMX. The address of the fault is on the stack asparameter faultp. For the overflow trap, the address points to the instruction followingthe INTO instruction. For the 8086/88 and 80186/188 DIV, IDIV or BOUND instruction, theaddress points to the instruction following the instruction which caused the fault. For the80286 and 80386 DIV, IDIV or BOUND instruction, the address points to the instruction(including any instruction prefixes) which caused the fault. The state of each register atthe time of the fault is present on the stack in an AMX register structure regs (seedefinition in Appendix D.1).

The register values in structure regs can be examined and modified with care. Ifnecessary, the FAR pointer faultp can be modified, with care, to force resumption atsome other location in the task code. If the trap handler returns to AMX, execution willresume at the location specified by faultp with registers set according to the values instructure regs.

Since the trap handler executes in the context of the task in which the error trap occurred,it is free to use all AMX services normally available to tasks. In particular, the traphandler can call ajend to end task execution if so desired.

Note

Task trap handlers are NOT Interrupt Handlers even thoughthe error interrupt is detected via a processor exception.

62 KADAK Interrupt Service Procedures

Note that the C trap handler receives a structure amxregs passed by value. If your Ccompiler does not allow such declarations, you can use casts to coerce access to theparameters on the stack as follows:

#include "amx831sd.h" /* AMX Structure Definitions*/

void cdecl tdiverr(int dummy){

struct amxregs *regp; /* Pointer to registers */void FAR *faultp; /* Fault pointer */

regp = (struct amxregs *)&dummy;faultp = *((void FAR **)(regp + 1));:Process the error:}

The task trap handler can be coded in assembly language as a FAR procedure. Upon entryto the procedure, the following conditions exist:

Interrupts are as they were at the time of the fault.All registers are free for use.DS,ES DGROUP SegmentSS:SP Task stack ready for useSS:BP A(parameters on stack)The direction flag is set to forward.

The parameters on the stack include a register structure AMXREGS (see Appendix D.2)followed by a FAR pointer to the fault location. For the overflow trap, the address pointsto the instruction following the INTO instruction. For the 8086/88 and 80186/188 DIV,IDIV or BOUND instruction, the address points to the instruction following the instructionwhich caused the fault. For the 80286 and 80386 DIV, IDIV or BOUND instruction, theaddress points to the instruction (including any instruction prefixes) which caused thefault.

If the overflow trap handler issues a FAR return instruction, it will cause execution toresume following the INTO instruction. If the divide or bound trap handler issues a FARreturn instruction, the effect will be processor dependent. The 8086/88 and 80186/188will resume execution following the instruction which caused the fault. For the 80286and 80386, the instruction which caused the fault will be executed again. Note thatrecovery from divide and bound errors may be next to impossible in some applications.

Interrupt Service Procedures KADAK 63

INCLUDE AMX831SD.DEF ;AMX Structure Definitions;USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;TDIVERR PROC FAR

:Access register structure AMXREGS via SS:BP:LES BX,DWORD PTR [BP+(SIZE AMXREGS)]

; ;ES:BX = A(fault):Process the error:RET

;TDIVERR ENDP;USER_CODE ENDS

64 KADAK Interrupt Service Procedures

4.6 Non-Maskable InterruptThe Intel 80x86 processor and equivalents provide a non-maskable interrupt (NMI). Thisinterrupt cannot be inhibited by software.

You have complete control over the non-maskable interrupt ISP. Usually, the NMIinterrupt is used to signal a catastrophic event such as a pending loss of power. The ISPmust process the interrupt in an application-dependent fashion, restore all registers andreturn to the point of interruption if feasible. This ISP must assure that the interruptfacility is restored according to its state at the time the non-maskable interrupt occurred.

The NMI ISP must be a nonconforming ISP. The NMI ISP cannot use AMX services.Consequently the non-maskable interrupt cannot be used as an additional, generalpurpose device interrupt.

Some hardware assisted debuggers may use the NMI interrupt to signal a breakpoint.The AMX Breakpoint Manager can be used with such debuggers (see Chapter 13.6).

Warning

Because the occurrence of an NMI interrupt cannot becontrolled, the NMI interrupt can occur at any instant,including within critical sections of AMX.

Consequently, the NMI ISP cannot call any AMX serviceprocedures.

Interrupt Service Procedures KADAK 65

4.7 Special Interrupts

Nonconforming Interrupts

In some systems there may be devices which generate interrupts requiring nocommunication or synchronization with any task in the system. For example, a high-speed scanner can interrupt the processor whenever new data readings are available. TheISP reads the new data and stores it in memory for subsequent use by any modulerequiring the information. These modules always use the most recently available value asseen in memory. Interrupts such as this do not need to use AMX services. The ISPsimply saves the registers it requires for its own use, processes the interrupting device,restores the registers and immediately returns to the point of interruption using an IRETinstruction.

Since ISPs of this type use the stack in effect at the time of the interrupt, care must betaken to assure that ALL stack sizes, including the AMX Interrupt Stack and KernelStack, are increased to meet the needs of the special ISPs.

ISPs of this type are called nonconforming ISPs. You must arrange in hardware that allsuch nonconforming interrupt sources are of higher priority than all conforming AMXInterrupt Service Procedures. If this is not possible, the private Interrupt ServiceProcedure must execute with interrupts disabled. Note that the AMX clock ISP (seeChapter 5.2) is considered to be a conforming ISP.

Occasional Task Interaction

In some applications, it may be desirable to bypass AMX for all but certain criticalinterrupts. For example, in a communication system, normal receive interrupts simplyinsert the received character into an already available input buffer. Transmit interruptssimply transmit the next available character from an output buffer. These interrupts canbe serviced very quickly in a nonconforming ISP, bypassing AMX entirely.

However, when the receiver finally has a complete message or when the transmit buffergoes empty, the device service procedure must send a message to a particular task toinform it that a significant event has occurred on the communication line.

The device service procedure must suddenly become a conforming AMX InterruptService Procedure. It can do this by restoring all saved registers and calling a conformingISP root. The ISP root informs AMX that the interrupt has occurred and calls thedevice's Interrupt Handler which can then send its message to the task.

Note that if interrupts of this type are employed, all AMX and task stacks must meet therequirements of the nonconforming device ISP.

66 KADAK Interrupt Service Procedures

Shared Interrupt Handlers

Occasionally a single Interrupt Handler can be used to service more than one identicaldevice. For example, an Interrupt Handler for an asynchronous serial I/O device (UART)could be used to service the UART for each of several communication lines.

For the Interrupt Handler to be shared, the code must be reentrant. This usually impliesthat the information unique to each UART (such as the device port address and linestatus) must be in a data structure accessible by the handler.

A shared Interrupt Handler must therefore be able to determine which of several devicedependent data structures it should use to service a particular device interrupt. A pair ofcustom ISP roots coded in assembly language can be used to solve this problem.

The following example illustrates how little application code must be written to create ashared Interrupt Handler to handle two devices.

struct dvcblock {int port; /* Device port */int line; /* Logical line number */:Other dynamic device parameters};

struct dvcblock dcbA = {0xF8, 1};struct dvcblock dcbB = {0xE8, 2};

void cdecl deviceih(struct dvcblock *dcbp){

:Service device specified by pointer dcbp:}

Interrupt Service Procedures KADAK 67

The two device ISP roots are illustrated below. Each of the ISP roots calls the InterruptHandler deviceih passing it a pointer to a unique, public, device dependent datastructure (dcbA or dcbB). Note that most common C compilers add leading underscoresto function and variable names declared in C.

Your application must install the pointers to ISP roots DVCROOT1 and DVCROOT2 into theprocessor Interrupt Vector Table prior to enabling interrupt generation by thecorresponding devices.

EXTRN AAINT:FAR ;AMX interrupt entryEXTRN AAINX:FAR ;AMX interrupt exit

;EXTERN _dcbA:DWORD ;Device control block AEXTERN _dcbB:DWORD ;Device control block BEXTERN _deviceih:FAR ;Shared Interrupt Handler

;;DVC_CODE SEGMENT BYTE 'CODE';

ASSUME CS:DVC_CODE,DS:NOTHING;

PUBLIC DVCROOT1 ;ISP root for device #1PUBLIC DVCROOT2 ;ISP root for device #2

;DVCWB1: DD _dcbA ;A(device control block A)DVCWB2: DD _dcbB ;A(device control block B);DVCROOT1 PROC FAR ;device ISP root #1

CALL AAINT ;let AMX knowLDS SI,CS:DVCWB1 ;DS:SI = A(work block #1)JMP SHORT DVCCMN

;DVCROOT2 LABEL FAR ;device ISP root #1

CALL AAINT ;let AMX knowLDS SI,CS:DVCWB2 ;DS:SI = A(work block #2)

DVCCMN: PUSH DSPUSH SICALL _deviceih ;common Interrupt HandlerADD SP,4 ;remove parameterCALL AAINX ;let AMX knowIRET

;DVC_CODE ENDS ;end of code segment

68 KADAK Interrupt Service Procedures

4.8 Vector Table InitializationThe 80x86 processor operating in real mode vectors to an Interrupt Service Procedure(ISP) directly through its Interrupt Vector Table which, in AMX nomenclature, is simplycalled the AMX Vector Table.

The Vector Table may be located in RAM or ROM as dictated by your hardwareconfiguration. If the Vector Table is in RAM, it can be further characterized as alterableor not. Whether or not AMX is allowed to alter the content of the Vector Table isdetermined by the setting in your launch parameter when you start AMX.

Alterable Vector Table

The Vector Table must be initialized to provide dispatch access to all ISPs. If the VectorTable is in RAM and is declared alterable, AMX services can be used to initialize theVector Table. Your application must initialize the Vector Table entry for each interruptor exception which your application services. You can use the AMX procedure ajivtw(AAIVTW) during the AMX launch to install any ISP or ISP root (including an NMI ISP orother nonconforming ISPs or exception handlers) into the Vector Table entry of yourchoice.

If the Vector Table is in RAM and is declared alterable, AMX will automatically installits own exception handlers for the error exceptions which AMX treats as task traps.

Unalterable Vector Table

Special consideration is required if the Vector Table is to be in ROM or is declared byyour launch parameter to be unalterable by AMX.

The Vector Table must be initialized when the ROM image is created. If the VectorTable is in RAM but has been declared unalterable, the RAM copy of the Vector Tablemust be initialized (as for a ROM image) before AMX is launched. Pointers to all ISPs(including conforming ISP roots, nonconforming ISPs and the NMI ISP) must beinstalled in the ROM image.

AMX requires that the entries for the error exceptions for which it is responsible beinitialized to branch to the addresses specified below.

Vector AMXNumber Entry Point Purpose

0 AADERH Divide by zero4 AAOVFH Overflow5 AABERH Bound error

AMX Timing Control KADAK 69

5. AMX Timing Control

5.1 Introduction to Timing FacilitiesMost real-time systems are characterized by the need to provide precise control over thetiming of activities. A hardware clock provides the timing source; AMX provides thecontrol over its use.

The unit of time in an AMX system is the system tick which is a fixed interval derivedfrom the hardware clock. The system tick interval is user selectable. Typically, it is setat 10 ms or 100 ms. The system tick interval is chosen to provide the minimumresolution required in a particular application without inflicting unnecessary timingoverhead.

Task Delays and Timeouts

A task can suspend itself for a specific interval. A task can also wait for an event whichmust occur within a specific interval. If the event fails to occur within the interval, thetask resumes execution with a timeout indication.

Interval Timers

Application interval timers are the most general form of timer provided by AMX. Oncesuch a timer has been created, it can be started, interrogated and stopped by any task orInterrupt Service Procedure. When a timer is created, an application dependent TimerProcedure must be provided. Whenever the timer expires, AMX executes this TimerProcedure passing it a parameter which was specified when the timer was created.

Application timers can also be periodic. The timer period is specified when the timer iscreated. AMX calls the corresponding Timer Procedure periodically at the definedinterval.

The following AMX procedures provide interval timer services:

ajtmcnv AATMCNV Convert milliseconds to system ticksajtmcre AATMCRE Create an interval timerajtmdel AATMDEL Delete an interval timerajtmrd AATMRD Read an interval timerajtmtag AATMTAG Find timer id of timer with a specific tagajtmwr AATMWR Start/stop an interval timer

70 KADAK AMX Timing Control

Calendar Clock

The AMX Time/Date Manager provides Y2K compliant time of day calendar support ifrequired. The AMX calendar clock includes second, minute, hour, day, month, year andday of the week. AMX services are provided to set and read the calendar clock. Aformatting procedure is also provided to translate the calendar time and date from theinternal format in which it is maintained by AMX into an ASCII string in several of themost popular formats.

An application procedure can be tied to the calendar clock and called at one secondintervals to permit simple time of day event scheduling.

The following AMX procedures provide calendar clock services:

ajtds AATDS Set calendar time/dateajtdg AATDG Read calendar time/dateajtdf AATDF Format calendar time/date as an ASCII string

Time Slicing

The AMX Timer Manager can provide time slicing if required. Time slicing is theprocess whereby AMX can force tasks which have the same execution priority to sharethe use of the processor on a round robin basis. The processing interval allocated to atask is called its time slice. The time slice for each task can be uniquely definedpermitting fine tuning of the AMX time slice facility to meet each application's particularneeds.

The following AMX procedures provide time slicing services:

ajtslv AATSLV Change a task's time slice intervalajtsof AATSOF Disable time slicingajtson AATSON Enable time slicing

AMX Timing Control KADAK 71

5.2 AMX Clock Handler and Kernel TaskAMX includes a conforming clock ISP root, a Clock Handler and a Kernel Task toprovide timing facilities. Whenever a clock interrupt occurs, the clock ISP root calls yourapplication clock Interrupt Handler to dismiss the hardware clock interrupt. The ISP rootthen calls the AMX Clock Handler to trigger the AMX Kernel Task if required. TheKernel Task is triggered at the defined system tick interval if, and only if, there is anyoutstanding timing activity required in the system. In this case, the interrupted task issuspended and the AMX Kernel Task begins execution.

The AMX Kernel Task monitors all tasks which are in a timed wait state. The timer usedby AMX for task waits is maintained privately by AMX for each task. If the timerexpires, the Kernel Task removes the task from the wait state. The task is allowed toresume execution when the Kernel Task ends with an indication that a timeout occurred.

The AMX Kernel Task also services all expiring application interval timers. Wheneveran interval timer expires, the corresponding Timer Procedure is executed. This procedurecan invoke a subset of the AMX services to trigger tasks, send messages to taskmailboxes or message exchanges, signal events or wake tasks. If the timer is defined tobe periodic, the AMX Kernel Task automatically restarts it with its predefined period.

Once all expiring task timers and application interval timers have been serviced, theAMX Kernel Task ends execution.

Your clock Interrupt Handler can be coded in either C or assembler. For efficiency,assembly language is recommended since most handlers require only one or two machineinstructions to dismiss the clock interrupt request.

You must also start your hardware clock at the correct frequency when AMX is launched.You can do this in a Restart Procedure or in some task which is triggered at launch time.

Note

AMX is delivered to you with clock drivers ready for usewith one or more of the timing devices commonly usedwith the 80x86 processor. These clock drivers are installedas described Appendix C of the AMX 86 Tool Guide.

72 KADAK AMX Timing Control

Clock ISP Implementation

AMX can provide timing facilities only if a hardware clock interrupt is available. Forefficiency, it is recommended that the clock ISP be coded in assembly language asillustrated below. Note that the clock ISP root and Interrupt Handler have been merged,making the clock ISP a single body of code. It is assumed in this example that interruptnumber 33 has been allocated for clock use.

EXTRN AACLK:FAR ;AMX Clock HandlerEXTRN AAIVTW:FAR ;AMX install ISP pointer

;;; Assume clock interrupt vector is located in Interrupt Vector Table; for interrupt number 33;CLK_CODE SEGMENT BYTE 'CODE';; The device ISP is located in user program memory;

ASSUME CS:CLK_CODE;CLKISP PROC FAR

PUSH DX ;save some registers::Code, if required, tokeep the hardware clock running.Use only those registers saved.Do not enable interrupts.::POP DX ;restore registersCALL AACLK ;AMX Clock HandlerIRET ;return from interrupt

;CLKISP ENDP;;

; Clock Restart Procedure;

PUBLIC RRCLK;RRCLK PROC FAR

MOV AX,SEG CLKISPMOV ES,AXMOV BX,OFFSET CLKISP ;ES:BX = A(Clock ISP)MOV DX,33 ;clock interrupt numberCALL AAIVTW ;install clock ISPRET

;RRCLK ENDP;CLK_CODE ENDS

AMX Timing Control KADAK 73

In this example, the clock ISP pointer (CLKISP) must be installed into vector number 33in the processor Interrupt Vector Table (IVT). AMX service procedure AAIVTW has beenused in a Restart Procedure for this purpose. When the clock interrupt occurs, theprocessor disables the interrupt facility, saves the flags and the return address on theinterrupted task's stack and fetches the ISP pointer from vector 33 in the IVT. Theprocessor then jumps to the clock ISP at address CLKISP in program memory.

The clock ISP must ensure that the clock keeps running. The manner in which this isaccomplished is, of course, hardware dependent. Sometimes one or more processorregisters will be required in order to access the hardware clock to keep it running. TheISP must save the registers it requires, keep the clock running and restore the registers.The ISP calls the AMX Clock Handler at its entry point AACLK.

Note that interrupts must be disabled upon entry to procedure AACLK.

If more than one device shares the interrupt, the ISP must determine the interrupt sourceby testing device status registers. If the clock caused the interrupt, the ISP must dismissthe clock interrupt and keep the clock running. The ISP must then call the AMX ClockHandler at its entry point AACLK.

Note that the clock ISP does not call the AMX Interrupt Supervisor entry or exitprocedures AAINT or AAINX. The AMX Clock Handler AACLK will invoke the AMXInterrupt Supervisor if, and only if, an AMX clock tick must be serviced by the AMXKernel.

It is important to note that, because of task switching invoked by function AACLK, theremay be significant delay before AMX returns from the AACLK call and executes the IRETinstruction to resume execution of the preempted task.

74 KADAK AMX Timing Control

It is preferred that the AMX Clock Handler be called from a clock ISP coded in assemblylanguage as in the example already provided. However, it is possible to code the clockISP in C as indicated in the following example. This C solution is not recommendedsince it significantly increases the service overhead for every clock interrupt.

The clock ISP and Restart Procedure can be written as Large or Medium model Cfunctions without formal parameters.

#include "amx831cf.h" /* AMX C Interface Header */

static struct amxisps isproot; /* Clock ISP root */

void cdecl clockih(void) /* Clock Interrupt Handler */{

:Dismiss clock interrupt and keep clock runningDo not enable interrupts.:ajclk(); /* AMX Clock Handler */}

void cdecl rrclk(void) /* Restart Procedure */{

ajispm(clockih, &isproot); /* Create Clock ISP root */ajivtw(33, (void (*)())&isproot); /* Install Clock ISP */}

AMX Timing Control KADAK 75

5.3 Interval Timers and Timer ProceduresAMX supports any number of application interval timers in a system. The maximumnumber in a system is defined in your System Configuration Module (see Chapter 14.5).

A timer must be created by an application before it can be used. Restart Procedures,tasks, ISPs and Timer Procedures can create timers. It is recommended that only RestartProcedures and tasks be used to create timers.

AMX procedure ajtmcre is used to create a timer. AMX allocates a timer and returns atimer id to the caller. The timer id is a handle which uniquely identifies the particulartimer allocated for use by the application. It is the responsibility of the application tokeep track of the timer id for future reference to the timer.

When a timer is created, you can provide a unique 4-character tag to identify the timer.The tag can be used subsequently in a call to ajtmtag to find the timer id allocated by theTimer Manager to the particular timer.

When a timer is created, the caller must also specify the following parameters: the timerperiod, a pointer to an application Timer Procedure and an optional 32-bit applicationdependent parameter.

The timer period determines if the timer is periodic. If the timer period is zero, the timeris a one-shot timer. Whenever a one-shot timer is started, it runs until it expires at whichtime it remains idle until started again.

If the timer period is non-zero, the timer is periodic. The period specifies the timer'speriod measured in AMX system ticks.

Whenever a timer expires, the AMX Kernel Task executes the Timer Procedure whichwas provided when the timer was created. The Timer Procedure receives the timer id andthe predefined 32-bit application parameter as parameters.

When a timer is created, AMX sets the timer idle. The timer remains idle until it isstarted by a Restart Procedure, task, ISP or Timer Procedure. Timers are started bycalling AMX procedure ajtmwr to write the initial timer interval into the timer.

Timer intervals are measured in multiples of system ticks. For convenience, the AMXprocedure ajtmcnv can be used to convert a period specified in milliseconds to thecorresponding number of system ticks.

Timers are down-counters. When a timer expires, the AMX Kernel Task calls the timer'sTimer Procedure. One-shot timers remain expired unless they are restarted by theirTimer Procedure. Periodic timers are automatically restarted by the AMX Kernel Taskwith their predefined timer period before the timer's Timer Procedure has been executed.

When an interval timer is no longer needed, it can be deleted with a call to ajtmdel.

76 KADAK AMX Timing Control

The AMX service procedures which can be called from a Timer Procedure include thefollowing:

ajtrig AATRIG Start (trigger) a task with no messageajsend AASEND Start a task by sending it a message at one of 4 prioritiesajwake AAWAKE Wake a task which is waitingajsgnl AASGNL Signal a task

ajtmcre AATMCRE Create an interval timerajtmdel AATMDEL Delete an interval timerajtmrd AATMRD Read an interval timerajtmwr AATMWR Start/stop an interval timerajtmcnv AATMCNV Convert milliseconds to system ticks

ajsmsig AASMSIG Signal to a semaphoreajevsig AAEVSIG Signal one or more events in an event groupajmxsnd AAMXSND Send message to message exchange

ajbget AABGET Get a buffer from a specific poolajbfre AABFRE Free a buffer

Circular List Manager servicesLinked List Manager services

The following conditions exist when the Timer Procedure is called by the AMX KernelTask:

Interrupts are enabled.All registers are free for use.DS,ES DGROUP segmentSS:SP AMX Kernel Stack ready for useBP Offset of parameters on stackThe direction flag is set to forward.

AMX Timing Control KADAK 77

Timer Procedures can be written as Large or Medium model C functions with formalparameters.

#include "amx831cf.h" /* AMX C Interface Header */

void cdecl truser( /* Timer Procedure */AMXID timerid, /* timer id */struct userblock FAR *userp) /* pointer to user block */{

:Do timer expiry processing:}

Timerid is the timer id assigned by AMX to the interval timer when it was created.Userp is the 32-bit application parameter provided when the timer was created. In thisexample, it is assumed that userp is a FAR pointer to an application structure of typeuserblock.

The Timer Procedure must execute with the interrupt facility enabled. If interrupts mustbe temporarily disabled, they must be enabled prior to returning to the AMX KernelTask. A Timer Procedure must not issue any AMX directives which would in any wayforce the Kernel Task to wait for any reason.

Note

Timer Procedures must only use AMX services which aremarked in Chapter 16 as� Timer Procedure

Application Timer Procedures use the AMX Kernel Stack.

In addition to the minimum stack size required for the AMX Kernel Stack, you mustallocate sufficient stack to satisfy the worst case requirements of all application TimerProcedures.

78 KADAK AMX Timing Control

The Timer Procedure can be coded in assembler as a FAR procedure as follows:

TMR_CODE SEGMENT BYTE 'CODE';; The Timer Procedure is located in user program memory;

ASSUME CS:TMR_CODE;TRUSER PROC FAR

MOV DX,WORD PTR [BP] ;DX = timer idLES BX,DWORD PTR [BP+2] ;ES:BX = 32-bit timer parameter::Timer Procedure code goes here::RET

;TRUSER ENDP;TMR_CODE ENDS

AMX Timing Control KADAK 79

5.4 Task Time SlicingAMX provides task time slicing as an option. The AMX system must be configured toinclude a clock if time slicing is to be possible. Time slice intervals are then specified asmultiples of the AMX system tick.

Time slicing is normally disabled. It is enabled with a call to AMX procedure ajtson. Itcan be disabled again with a subsequent call to ajtsof.

If your AMX System Configuration Module indicates that time slicing is required, AMXwill automatically enable time slicing by calling ajtson prior to executing anyapplication Restart Procedure at launch time.

Time slicing is a feature which coexists with the normal AMX preemptive priority-basedtask scheduling. Whether or not a task is time-sliced depends on two things: the task'sexecution priority and the task's time slice interval. Both of these parameters are firstdefined when a task is created.

If a task's time slice interval is zero, the task will not be time sliced. A non-zero timeslice interval specifies the number of AMX system ticks which will be given to the taskbefore the task is forced to relinquish the processor to another time sliced task.

A task is time sliced with all other tasks having the same execution priority and a non-zero time slice interval. A set of time sliced tasks are normally created to share aparticular execution priority. Tasks which are not time sliced (their time slice interval iszero) are usually assigned to different execution priority levels. More than one set oftime sliced tasks can be created, each set existing at a different priority level. Other taskscan reside at priorities between the time sliced sets.

The order in which tasks at a particular shared priority level are given their time slice byAMX is determined by the chronological order in which the tasks were created.

80 KADAK AMX Timing Control

Figure 5.4-1 illustrates the allocation of processing time to two tasks, B and C. Task Bwas created first with a time slice interval of 100 AMX system ticks. Task C was createdlater with a time slice interval of 50 AMX system ticks. At time t1, tasks B and C wereboth triggered by a higher priority task A which then ended.

Since task B was created first, it executes first. Thereafter, in the absence of any otherhigher priority task activity, the processor is shared by tasks B and C as illustrated.

Task C begins to execute at time t2 when task B's first 100 tick time slice expires. Attime t3, task B ends execution. The processor is immediately given to task C whichcontinues to execute without further interruption by task B.

┌────────┐ ┌────────┐ ┌──┐│ 100 │ │ 100 │ │25│

Task B ──────┘ └────┘ └────┘ └────────────┌────┐ ┌────┐ ┌────────────│ 50 │ │ 50 │ │ >50

Task C ───────────────┘ └────────┘ └──┘↑ ↑ ↑t1 t2 t3

Figure 5.4-1 Simple Time Slicing

Figure 5.4-2 illustrates the effects to be expected if, while tasks B and C are being timesliced, higher priority task A is invoked and executes to completion within 125 systemticks.

┌──────────┐│ 125 │

Task A ───────┘ └──────────────────────────────────┌──┐ ┌──────┐ ┌────────┐ ┌──┐│25│ │ 75 │ │ 100 │ │25│

Task B ────┘ └──────────┘ └────┘ └────┘ └─────┌────┐ ┌────┐ ┌─────│ 50 │ │ 50 │ │ >50

Task C ─────────────────────────┘ └────────┘ └──┘↑ ↑ ↑t1 t2 t3

Figure 5.4-2 Interrupted Time Slicing

AMX Timing Control KADAK 81

Time slicing can be completely disabled at any time with a call to AMX procedureajtsof. Procedure ajtson can then be used to enable time slicing.

Task time slice intervals can be dynamically adjusted using AMX procedure ajtslv tofine tune the shared use of the processor based on observed effects.

The starting and ending of time sliced tasks are not synchronized to the AMX clock.However, switching between time sliced tasks will only occur at AMX system ticksbecause the switch is initiated by the AMX Kernel Task.

It should be noted that if higher priority tasks frequently interrupt a time sliced task, theexact processing time allocated to the task will not exactly equal n*t where n is the task'stime slice interval and t is the AMX system tick period. The task will be forced torelinquish the processor after the n'th system tick which occurs while the task isexecuting. However, because of higher priority task activity, the task did not get the useof the processor for the entirety of each of its n system ticks.

Finally, if a task is time sliced and all other tasks at the same execution priority are idle orblocked, a time slicing overhead penalty will still exist. The AMX Kernel Task willcontinue to interrupt the task at its time slice interval, conclude that task switching isunnecessary and resume execution of the interrupted task.

Suggestion

Do not use time slicing unless its use is warranted. Betteruse of processor time results if tasks are allowed to run tocompletion.

Misuse is abuse!

82 KADAK AMX Timing Control

5.5 Time/Date ManagerMost real-time systems require the maintenance of a calendar clock. The AMXTime/Date Manager provides this facility.

The Y2K compliant calendar clock maintained by the Time/Date Manager includessecond, minute, hour, day, month and year. Leap year is accounted for. The day of theweek (Mon to Sun) is also maintained.

An application Scheduling Procedure can be connected to the calendar clock to provideactivity scheduling based on the time of day.

The Time/Date Manager includes a set of service procedures for use by application tasks,Timer Procedures, Interrupt Service Procedures and Restart Procedures. These include:

ajtdg AATDG Get Time and Dateajtds AATDS Set Time and Dateajtdf AATDF Format Time and Date as an ASCII string

Several conflicts always arise with the maintenance of time and date. These conflictsarise when:

1) the clock is trying to update the time and date while2) a task is trying to read the time and date and3) another task is trying to set the time and date.

The conflicts are even more pronounced if separate calls are required to get both time anddate. The Time/Date Manager resolves these conflicts.

AMX Timing Control KADAK 83

Operation

The Time/Date Manager includes two components: an AMX Restart Procedure and a setof service procedures.

If your AMX System Configuration Module enables the Time/Date option, AMXautomatically calls the Time/Date Restart Procedure during the launch prior to executingany application Restart Procedure. The calendar clock is set to 00:00:00 MondayOctober 01/1990 (the distribution date of the Time/Date Manager).

The Time/Date Manager creates a periodic interval timer and starts it with a one secondperiod. At one second intervals thereafter, the AMX Kernel Task executes the Time/DateTimer Procedure. The current time and date are updated by one second.

The Time/Date Manager employs an interlock mechanism to ensure that any racebetween a task trying to set a new time and date and the Time/Date Timer Proceduretrying to update time and date is resolved. The task's new time and date have precedence.

This interlock mechanism also assures that any task trying to read the current time anddate does not get a partially updated (and hence erroneous) time and date.

Once the time and date have been updated, the Time/Date Timer Procedure calls anapplication Scheduling Procedure if one has been provided. This procedure, called oncea second, is thus tied to the calendar clock and can be used to initiate activities whichmust be time of day driven. A detailed description of this facility is provided later in thischapter.

The Time/Date Timer Procedure ends once the application Scheduling Procedure (if any)has been executed.

84 KADAK AMX Timing Control

Time/Date Structure

The Time/Date Manager provides time and date in the following form. C structureamxtds is defined in the AMX header file AMX831SD.H. Assembler structure AMXTDS isdefined in the AMX definition file AMX831SD.DEF.

The C and assembler structure definitions are shown below.

/* AMX Time/Date Structure */

struct amxtds {

unsigned char amtdsec; /* seconds (0-59) */unsigned char amtdmin; /* minutes (0-59) */unsigned char amtdhr; /* hours (0-23) */unsigned char amtddy; /* day (1-31) */unsigned char amtdmn; /* month (1-12) */unsigned char amtdyr; /* year (0-99) */unsigned char amtdow; /* day of week (Mon=1 to Sun=7) */unsigned char amtdcen; /* 0 if time/date is incorrect */

/* century if time/date is correct */};

; AMX Time/Date Structure;AMXTDS STRUC;AMTDSEC DB ? ;seconds (0-59)AMTDMIN DB ? ;minutes (0-59)AMTDHR DB ? ;hours (0-23)AMTDDY DB ? ;day (1-31)AMTDMN DB ? ;month (1-12)AMTDYR DB ? ;year (0-99)AMTDOW DB ? ;day of week (Mon=1 to Sun=7)AMTDCEN DB ? ;0 if time/date is incorrect; ;century if time/date is correct;AMXTDS ENDS;

AMX Timing Control KADAK 85

Time/Date Validity

The century is used as follows. At startup, the Time/Date Restart Procedure resets thecentury to 0 to indicate that the initial default time and date are incorrect. Note that theinitial time and date are valid; they are just not correct. At some later time, an applicationprogram can issue a call to the Time/Date service procedure ajtds to set a correct timeand date. The century specified as a parameter in that call should be set indicating thatthe time and date parameters are correct.

The century can be reset to 0 by an application program with an ajtds call to indicatethat the time and date are incorrect.

When setting the time and date, the day of the week does not have to be provided as longas the year lies between 1974 and 2099. The Time/Date Manager will figure it out andset it accordingly.

Time/Date Scheduling

Many real-time systems require that certain activities be performed at specific times ofday. For instance, it may be required that every day at 8:00 a.m. a 24 hour report begenerated. Or maybe every 1/2 hour, measured from the hour, the system must make ameasurement and display the result. The Time/Date Manager provides the mechanismnecessary to implement such features.

At one second intervals the Time/Date Timer Procedure updates the time and date andthen calls an application Scheduling Procedure. The name of this procedure must beprovided in your System Configuration Module (see Chapter 14.4).

Your Scheduling Procedure is called with a FAR procedure call with an actual Time/Datestructure as a parameter. Note that the structure is passed to the procedure by value. Thestructure specifies the time and date at the instant the procedure is called.

The Scheduling Procedure is application dependent. It executes as part of the Time/DateTimer Procedure. It must therefore not be compute or I/O bound.

In general, the procedure checks the time (and date if necessary) and determines if someapplication dependent action must be initiated at that instant. If action is required, theprocedure either performs the action directly or requests AMX to start some other taskwhich is responsible for taking the required action.

You must be sure to allocate sufficient stack to the AMX Kernel Task to accommodatethe needs of the Scheduling Procedure.

86 KADAK AMX Timing Control

The following conditions exist when your Time/Date Scheduling Procedure is called bythe Time/Date Manager

Interrupts are enabled.All registers are free for use.DS,ES DGROUP segmentSS:SP AMX Kernel Stack ready for useBP Offset of parameters on stackThe direction flag is set to forward.

The Scheduling Procedure can be written as a Large or Medium model C procedure asfollows:

#include "amx831sd.h" /* AMX Structure Definitions */

void cdecl tdshed( /* Scheduling Procedure */int dummy) /* Dummy parameter */{

struct amxtds *ptdp; /* Pointer to time/date */

ptdp = (struct amxtds *)&dummy;:Perform required tests and initiateactions if it is time for them:}

Note that function tdshed is declared to receive a dummy integer parameter. Thefunction actually receives an entire amxtds time/date structure passed by value.However, not all C compilers support this facility. Therefore, we recommend that youuse a local pointer variable ptdp to gain access to the time/date structure as illustratedabove.

AMX Timing Control KADAK 87

Your Time/Date Scheduling Procedure can be coded in assembly language as a FARprocedure as follows:

INCLUDE AMX831SD.DEF ;AMX Structure Definitions;;TDS_CODE SEGMENT BYTE 'CODE';; Time/Date Scheduling Procedure located in program memory;

ASSUME CS:TDS_CODE;

PUBLIC TDSHD;TDSHD PROC FAR

MOV AL,[BP].AMTDSEC ;AL = seconds:MOV DL,[BP].AMTDDY ;DL = day::Perform required tests and initiateactions if it is time for them::RET

;TDSHD ENDP;TDS_CODE ENDS

Note that function TDSHD receives an entire AMXTDS time/date structure passed by valueon its stack. Since register BP is initialized with the offset of the structure on the stack,register BP can be used to directly access the time/date structure as illustrated above.

88 KADAK AMX Timing Control

Time/Date ASCII Formats

The Time/Date Manager procedure ajtdf can be used to format time and date into anASCII character string in any of several popular formats. The time and date is presentedto ajtdf in the standard AMX time/date structure. The ASCII string is returned in acharacter buffer provided by the caller. See Chapter 16 for the ajtdf calling sequence.

Time can be formatted as either of:

HH:MMbHH:MM:SSb

where: HH = hours (00 to 23)MM = minutes (00 to 59)SS = seconds (00 to 59)b = space time/date are correct (century <> 0)b = # time/date are incorrect (century = 0)

The date can be formatted as any of:

DDD MMM dd/ccyybDDD mm/dd/ccyybDDD dd MMM/ccyybDDD dd/mm/ccyybDDD ccyy/mm/ddb

where: DDD = day of week (Mon to Sun)MMM = month (Jan to Dec)mm = month (01 to 12)dd = day (01 to 31)cc = century (19 or 20)yy = year (00 to 99)b = space

The 4 character day-of-week (DDDb) and/or the two character century (cc)can be omitted.

The format of time and/or date is specified by a format specification parameter, a singlebyte presented to procedure ajtdf.

AMX Timing Control KADAK 89

Figure 5.5-1 describes the format specification byte and the effect of each bit in it on theformatting of the time and date.

7 6 5 4 3 2 1 0

TD1 TD0 C M S W D1 D0

TD1 TD0 Time/Date selection

0 0 time followed by date 23:59:59 Sun Jan 31/930 1 time only 23:59:591 0 date only Sun Jan 31/931 1 date followed by time Sun Jan 31/93 23:59:59

S = 0 display seconds 23:59:59S = 1 suppress seconds 23:59

W = 0 suppress day of week 23:59:59 Jan 31/93W = 1 display day of week 23:59:59 Sun Jan 31/93

M D1 D0 Date format

0 0 0 American alphanumeric form Jan 31/930 0 1 American numeric form 01/31/930 1 0 European alphanumeric form 31 Jan/930 1 1 European numeric form 31/01/931 0 0 Metric form 93/01/31

C = 0 suppress century Jan 31/93C = 1 include century Jan 31/1993

Figure 5.5-1 Time/Date Format Specification Parameter

90 KADAK AMX Timing Control

This page left blank intentionally.

AMX Semaphore Manager KADAK 91

6. AMX Semaphore Manager

6.1 IntroductionE.W. Dijkstra introduced two primitive operations to resolve two seemingly unrelatedproblems: mutually exclusive access by tasks to critical resources and thesynchronization of asynchronously occurring activities.

The abstract primitives, called P and V operators, operate on a variable called asemaphore. Many variations of these P and V operators have been implemented sincetheir first introduction. The AMX Semaphore Manager provides two variations: acounting semaphore which has been enhanced to provide priority queuing and automatictimeout, and a resource semaphore in which resource ownership is tied to a specific task.

A counting semaphore is a semaphore with an associated counter which is incrementedby the P operator (signal) and decremented by the V operator (wait). The resource(object) controlled by the semaphore is free (available) when the counter is greaterthan 0. The number of resources (objects) controlled by the semaphore is determined bythe maximum value the counter is allowed to achieve.

A counting semaphore with a maximum count of one is a binary semaphore. It can beused to provide mutually exclusive access to a single resource or to signal a particularevent.

A resource semaphore is a binary semaphore which can only be used for resourceownership control. It differs from a counting semaphore in one significant feature:resource ownership is tied to a specific task. No other task except the task owning theresource is allowed to signal the release of the resource.

The counting and resource semaphores provided by the Semaphore Manager have beenenhanced to provide priority queuing and automatic timeout. Tasks which wait onsemaphores can specify the priority at which they wish to wait for the resource or eventcontrolled by the semaphore. Tasks can also specify the maximum interval which theyare prepared to wait.

The AMX Semaphore Manager provides the following semaphore management services:

ajsmcre AASMCRE Create a semaphoreajsmdel AASMDEL Delete a semaphore

ajsmrsv AASMRSV Reserve a resource semaphore (optional timeout)ajsmrls AASMRLS Release a resource semaphore (nested)ajsmfre AASMFRE Free a resource semaphore (unconditional)

ajsmwat AASMWAT Wait on a counting semaphore (optional timeout)ajsmsig AASMSIG Signal to a counting semaphoreajsmget AASMGET Get use of a counting semaphore (no wait)

ajsmtag AASMTAG Find the semaphore id of a semaphore with a specific tag

92 KADAK AMX Semaphore Manager

Your use of the Semaphore Manager is optional. If you intend to use it, you mustindicate so in your System Configuration Module. You must also provide a hardwareclock and include the AMX timing facilities.

Semaphores can be predefined in your System Configuration Module which is processedby the Semaphore Manager at startup. Semaphores which are predefined areautomatically created by the Semaphore Manager. The semaphore id assigned to eachpredefined semaphore is stored in a variable which you must provide for that purpose.

AMX Semaphore Manager KADAK 93

6.2 Semaphore UseThe Semaphore Manager supports any number of semaphores. The maximum number ofsemaphores in a system is defined in your System Configuration Module (see Chapter14.5). The defined maximum sets an upper limit on the number of actual semaphoresthat can be created in your application.

A semaphore must be created by an application before it can be used. RestartProcedures, tasks, ISPs and Timer Procedures can create semaphores. It is recommendedthat only Restart Procedures and tasks be used to create semaphores.

A semaphore is created with a call to procedure ajsmcre indicating the type ofsemaphore, counting or resource, to be created. The Semaphore Manager allocates asemaphore and returns a semaphore id to the caller. The semaphore id is a handle whichuniquely identifies the semaphore. It is the responsibility of the application to keep trackof the semaphore id for future reference to the semaphore.

When a semaphore is created, you can provide a unique 4-character tag to identify thesemaphore. The tag can be used subsequently in a call to ajsmtag to find the semaphoreid allocated by the Semaphore Manager to the particular semaphore.

When a semaphore is no longer needed, it can be deleted with a call to ajsmdel. TheSemaphore Manager will reject the attempt to delete the semaphore if any task is waitingfor the use of the semaphore. When the Semaphore Manager deletes a semaphore, itmarks the semaphore as invalid such that any subsequent reference to the semaphore willbe rejected.

You must be absolutely certain that no task, ISP or Timer Procedure is referencing thesemaphore just as you go to delete it. Be aware that the deleted semaphore id mayimmediately be reused by AMX for some other purpose.

94 KADAK AMX Semaphore Manager

Counting Semaphore

A counting semaphore is created by specifying an initial semaphore count greater than orequal to zero in the call to ajsmcre. When used for mutual exclusion, the semaphoreshould be given an initial value of one.

If a semaphore is initialized with a semaphore value of n, it can be used to control accessto n resources of a particular type. For instance, a counting semaphore with an initialcount of three could be used to control access to three printers in a system. When used inthis fashion, the Semaphore Manager assures that no more than three tasks can own aprinter at any one time. However, the Semaphore Manager does not provide anyguidance as to which of the three available printers a task can use.

Access to the resource controlled by a counting semaphore is acquired with a call toprocedure ajsmwat. Only tasks are allowed to call this procedure because the caller mayhave to wait for the resource to become available. When requesting use of a resource, thetask specifies the interval, measured in system ticks, which it is willing to wait for theresource if the resource is unavailable at the time of the call. The task also specifies thepriority at which it is prepared to wait, zero being the highest priority.

If the resource controlled by the semaphore is available, the Semaphore Manager gives itto the calling task immediately. If the resource is unavailable, the Semaphore Managerwill add the task to the semaphore's wait queue at the priority it said it was willing towait. Thus tasks which require high priority access to the resource can preempt lowerpriority waiting tasks in the wait queue.

When the task is finished using the resource, it signals its release by calling procedureajsmsig. The Semaphore Manager releases the resource and checks the semaphore'swait queue. If any tasks are waiting on the queue, the resource is immediately given tothe task at the head of the wait queue. If that task is of higher priority than the task whichis releasing the resource, a task switch will occur giving the higher priority task animmediate opportunity to use the resource. If the task being granted use of the resourceis of lower priority than the task which is releasing it, the new owner will have to waituntil the currently executing task relinquishes control of the processor.

If the semaphore does not become available within the timeout interval specified by thetask, the task will be removed from the semaphore wait queue and will resume executionwith a timeout indication.

Tasks, ISPs or Timer Procedures which need to use a resource but which cannot wait forthe resource must call ajsmget to get use of the resource. Unlike ajsmwat, procedureajsmget will not allow the caller to wait on the semaphore queue. If the resource cannotbe immediately granted to the caller, ajsmget returns an error indication.

AMX Semaphore Manager KADAK 95

Resource Semaphore

AMX resource semaphores provide the simplest mechanism for controlling the access tocritical resources. Resources may include disk files, I/O devices, database components,regions of memory, specific words of memory or any other entity which is considered tobe a resource.

An application task requests ownership of a resource with a call to the SemaphoreManager. If the resource is available, the task is granted immediate ownership of it. Ifthe resource is unavailable, the task is inserted on a list of tasks waiting for the resourceat a wait priority specified by the task. The task can optionally specify the maximumtime interval it is prepared to wait for access. When the task which currently owns theresource releases it with a call to the Semaphore Manager, the resource will be given tothe task with the highest waiting priority.

Although a resource semaphore uses a binary semaphore for controlling access to theresource, it differs from the general counting semaphore facility provided by the AMXSemaphore Manager in one significant feature. Resource ownership is tied to a specifictask. Only the task owning such a resource is permitted to signal its release. TheSemaphore Manager does not permit more than one task to share ownership of such aresource.

A resource semaphore is created by specifying an initial semaphore count of -1 in the callto ajsmcre. The Semaphore Manager creates a resource semaphore and automaticallygives it an initial value of one indicating that the resource is free.

A resource is reserved by calling procedure ajsmrsv using the semaphore id allocated tothe particular resource semaphore when it was created. Only tasks can reserve a resourcecontrolled by a resource semaphore. The task which owns the resource can reserve itagain and again resulting in a nested reservation.

When requesting use of a resource, the task specifies the interval, measured in systemticks, which it is willing to wait for the resource if the resource is unavailable at the timeof the call. The task also specifies the priority at which it is prepared to wait, zero beingthe highest priority.

The resource is released with a call to ajsmrls. The task which owns the resource mustrelease the resource once for each nested reserve that it has made. The resource becomesfree when the nesting count reaches zero. Alternatively, the resource can be releasedunconditionally with a call to ajsmfre.

If the resource is in use when ajsmrsv is called, the task will be added to the resourcesemaphore queue forcing the task to wait at the priority specified by the task in its call toreserve the resource. When the current owner of the resource releases it, the SemaphoreManager gives the resource to the task (if any) waiting at the beginning of the resourcesemaphore queue. Hence, a task must wait until all other tasks ahead of it in the queueuse and release the resource.

If the task is of higher priority than the task which is releasing the resource, a task switchwill occur giving the higher priority task an immediate opportunity to use the resource. Ifthe task being granted use of the resource is of lower priority than the task which isreleasing it, the new owner will have to wait until the currently executing taskrelinquishes control of the processor.

96 KADAK AMX Semaphore Manager

If the resource does not become available within the timeout interval specified by thetask, the task will be removed from the resource semaphore wait queue and will resumeexecution with a timeout indication.

Tasks which need to use a resource but which cannot wait for the resource to be free canstill call ajsmrsv. However, they must specify a timeout value of less than zero so thatthey will not wait on the resource semaphore queue. If the resource cannot beimmediately granted to the caller, ajsmrsv returns an error indication.

AMX Semaphore Manager KADAK 97

6.3 Semaphore Applications

Mutual Exclusion

Assume that three tasks, A, B and C, require shared access to a common data structurebeing used to control some process. Access to the data structure must be mutuallyexclusive so that one task cannot be modifying the data in the structure while another taskis accessing it.

A semaphore with an initial count of one is required because there is only one datastructure to manage. A counting semaphore is created in a Restart Procedure andinitialized with a count of one. One task can own the resource; two tasks can be waiting.Note that the Semaphore Manager does not guarantee that only tasks A, B and C canaccess the data structure.

In this example, Task A waits indefinitely (timeout value = 0) at priority level 20 foraccess to the data variable. Task B waits indefinitely at priority level 10. Task C onlywaits for 100 system ticks at priority 5 before it assumes that it cannot have the resource.

This example is illustrated on the next page. The manner in which Tasks A, B and C arecreated and started is beyond the scope of this example.

Parameters 1 and 2 in the data structure are modified by the tasks to illustrate that theiralteration by one task is guaranteed by the semaphore to be completed before access byeither of the other two tasks is allowed.

98 KADAK AMX Semaphore Manager

#include "amx831cf.h" /* AMX C Interface Header */

static AMXID daccess; /* Data access semaphore id */

static struct {int dbpar1; /* parameter 1 */int dbpar2; /* parameter 2 */::} datavar; /* Data variable */

void cdecl rruser(void) /* Restart Procedure */{

ajsmcre(&daccess, 1, "DACS"); /* Create counting semaphore */}

void cdecl sttaskA(void) /* Task A */{

/* Wait for access */

if (ajsmwat(daccess, 0, 20) == AEROK) {datavar.dbpar1 = 1; /* Set parameters */datavar.dbpar2 = 1;}

}

void cdecl sttaskB(void) /* Task B */{

/* Wait for access */

if (ajsmwat(daccess, 0, 10) == AEROK) {datavar.dbpar1 = 2; /* Set parameters */datavar.dbpar2 = 2;}

}

void cdecl sttaskC(void) /* Task C */{

/* Wait 100 ticks for access */

if (ajsmwat(daccess, 100, 5) == AEROK) {datavar.dbpar1 = 3; /* Set parameters */datavar.dbpar2 = 3;}

}

AMX Semaphore Manager KADAK 99

Task/Event Synchronization

A counting semaphore can be used to provide synchronization between a task waiting foran event and a task, ISP or Timer Procedure in which the event is detected. Thefollowing example assumes that a device ISP detects the event.

A task creates a counting semaphore with an initial count of zero.

The task then starts the device and waits on the semaphore. When the event of interest isdetected by the ISP, it signals to the semaphore. The Semaphore Manager grants accessto the waiting task which then resumes execution knowing that the event occurred.

#include "amx831cf.h" /* AMX C Interface Header */

static AMXID syncisp; /* ISP synchronization semaphore id */

void cdecl sttask(void){

int status;

ajsmcre(&syncisp, 0, "SISP"); /* Create counting semaphore */:Start device I/O:

/* Wait 1 second for event */status = ajsmwat(syncisp, ajtmcnv(1000), 0);

if (status == AEROK) { /* OK? */:Event occurred within 1 second:}

else if (status == AERTMO) { /* Timeout? */:Event did not occur within 1 second:}

else { /* Fatal error */:No such semaphore exists (who deleted it?):}

ajsmdel(syncisp); /* Delete semaphore */}

100 KADAK AMX Semaphore Manager

EXTRN AAINT:FAR ;enter ISPEXTRN AAINX:FAR ;leave ISPEXTRN AASMSIG:FAR ;signal to a semaphoreEXTRN _SYNCISP:WORD ;ISP synchronization semaphore id

;;DVC_CODE SEGMENT BYTE 'CODE';

ASSUME CS:DVC_CODE;;DVCISP PROC FAR

CALL AAINT ;tell AMX:Clear interrupt sourceCheck for event:MOV BX,_SYNCISP ;BX = semaphore idCALL AASMSIG ;signal to semaphore::CALL AAINX ;tell AMXIRET ;end of interrupt

;DVCISP ENDP;DVC_CODE ENDS

In this example, we have mixed C and assembly language for illustration purposes.Notice the use of the underscore character in the assembler code reference to variable_SYNCISP. In C, the variable is named syncisp. The underscore is required because wehave assumed that the C compiler actually assigns the symbol name _syncisp to thevariable. Also note that we have assumed that the program linker can ignore upper/lowercase differences in symbols. Your C compiler and linker may behave differently.

Refer to the AMX 86 Tool Guide for a more complete description of C, assembler andlinking requirements when using AMX with a particular toolset.

AMX Semaphore Manager KADAK 101

Resource Nesting

Assume that two tasks, A and B, have to share a numeric coprocessor. Furthermore,these two tasks also must share a common library procedure ncmath which must use thecoprocessor.

A resource semaphore must be used because ownership of the numeric coprocessor mustbe tied to one task at a time and the owner must be allowed to make nested resourcereservation calls.

In the example, Task A waits indefinitely (timeout value = 0) at priority level 20 for theuse of the numeric coprocessor. Once the task owns the coprocessor, it initializes it andcalls ncmath to perform some mathematical operation using it. Task A then finishesusing the coprocessor and releases it.

Task B does not use the coprocessor directly. It calls ncmath to perform a mathematicaloperation which requires the use of the coprocessor.

The math library procedure waits forever at priority 20 to reserve the coprocessor withoutknowing which task is calling. If ncmath is called by Task B while Task A owns thecoprocessor, Task B will be suspended by the Semaphore Manager until Task A isfinished with the coprocessor.

The manner in which Tasks A and B are created and started is beyond the scope of thisexample.

For simplicity, Tasks A and B do not check the error codes returned by ncmath or theSemaphore Manager. In practice, error codes should never be ignored.

102 KADAK AMX Semaphore Manager

#include "amx831cf.h" /* AMX C Interface Header */

static AMXID ncaccess; /* Coprocessor resource *//* semaphore id */

void cdecl rruser(void){

ajsmcre(&ncaccess, -1, "387P"); /* Create resource semaphore */}

int ncmath(AMXID ncid) /* Semaphore id */{

int status;

status = ajsmrsv(ncid, 0, 20); /* Reserve coprocessor */if (status == AEROK) {

:use coprocessor and do math operation:status = ajsmrls(ncid); /* Release coprocessor */}

return(status);}

void cdecl sttaskA(void){

ajsmrsv(ncaccess, 0, 20); /* Reserve coprocessor */:initialize coprocessor:ncmath(ncaccess); /* Common math operation */ajsmrls(ncaccess); /* Release coprocessor */:}

void cdecl sttaskB(void){

:ncmath(ncaccess); /* Common math operation */;}

AMX Event Manager KADAK 103

7. AMX Event Manager

7.1 IntroductionThe AMX Event Manager provides the most general form of event synchronizationoffered by AMX. The Event Manager provides a convenient mechanism for separatingthe tasks waiting for events from the tasks, Timer Procedures and Interrupt ServiceProcedures which can signal the event. The Event Manager also allows more than onetask to simultaneously wait for a particular event. Tasks can wait for a particularcombination of events or for any one of a set of events to occur.

The Event Manager provides a set of event flags which can be associated with specificevents in your system. These event flags are provided in groups with 16 event flags pergroup. Note that the number of event flags per group is dictated by the basic registerwidth (integer size) of the target processor. Hence, 32-bit versions of AMX have 32event flags per group.

As an example, suppose that two tasks, A and B, must each wait until a motor turns on.Assume that an interrupt will occur when the motor is turned on.

It is assumed that Tasks A and B are completely independent; their processing isunrelated. One method of accomplishing the necessary synchronization is for both tasksto set software flags indicating that they are waiting for the motor and then call AMXprocedure ajwait to wait for the motor to turn on. When the motor control ISP detectsthat the motor has started, it could check the wait flags for the two tasks and wake thetasks if necessary with calls to ajwake.

This solution does not provide good functional separation between processes. The motorcontrol ISP must be aware that Tasks A and B are waiting for the motor to turn on. Asyou can imagine, this lack of functional separation is compounded when there are manytypes of events occurring in a system.

The Event Manager provides a more general solution to this problem. An event flag isdefined to represent the state of the motor (off or on). A Restart Procedure initializes theevent flag so that it matches the actual state of the motor. When Tasks A and B mustwait for the motor, they do so by calling the Event Manager requesting to wait until themotor control event flag indicates that the motor is on. When the motor control ISPdetects that the motor is on, it signals the event with a call to the Event Manager. TheEvent Manager wakes all tasks, including Tasks A and B, which are waiting for themotor to be on.

104 KADAK AMX Event Manager

The AMX Event Manager provides the following event management services:

ajevcre AAEVCRE Create an event groupajevdel AAEVDEL Delete an event groupajevsig AAEVSIG Signal one or more events in a groupajevwat AAEVWAT Wait for all/any of a set of events in a group

(optional timeout)ajevrd AAEVRD Read current state of events in a groupajevnt AAEVNT Get state of event flags at completion of event waitajevtag AAEVTAG Find the event group id of an event group with a specific tag

Your use of the Event Manager is optional. If you intend to use it you must indicate so inyour System Configuration Module. You must also provide a hardware clock andinclude the AMX timing facilities.

Event groups can be predefined in your System Configuration Module which is processedby the Event Manager at startup. Event groups which are predefined are automaticallycreated by the Event Manager. The event group id assigned to each predefined eventgroup is stored in a variable which you must provide for that purpose.

AMX Event Manager KADAK 105

7.2 Event SynchronizationThe AMX Event Manager supports any number of event groups in a system. Each eventgroup includes 16 event flags. The maximum number of event groups in a system isdefined in your System Configuration Module (see Chapter 14.5). The defined maximumsets an upper limit on the number of actual event groups that are available through theEvent Manager in your application.

Each event in a group is represented by a boolean flag representing the state of the event.The event flags are represented in one 16-bit variable. It is recommended that theboolean states 0 and 1 be used as false and true indicators respectively. The zero statetherefore represents no event. The one state indicates that the event has occurred.

An event group must be created by an application before it can be used. RestartProcedures, tasks, ISPs and Timer Procedures can create event groups. It isrecommended that only Restart Procedures and tasks be used for this purpose.

Event Manager procedure ajevcre is used to create an event group. The Event Managerallocates an event group and returns a group id to the caller. The group id is a handlewhich uniquely identifies the particular event group allocated for use by the application.It is the responsibility of the application to keep track of the group id for future referenceto the event group.

When an event group is created, you can provide a unique 4-character tag to identify theevent group. The tag can be used subsequently in a call to ajevtag to find the eventgroup id allocated by the Event Manager to the particular event group.

When an event group is created, the caller specifies the initial state that each of the eventflags in the group is to assume. Hence, the process of creating a group automaticallyinitializes all events in the group to a predefined state. The assignment of events tospecific event flags in the event group is completely determined by the system designer.

Once an event group has been created, it can be used to synchronize tasks to any of theevents which it represents. A task can wait for an event by calling procedure ajevwat.Only tasks can wait for events. If a task wishes to wait for more than one event, all of theevents must be contained in the one event group specified by the task in its call toajevwat.

When the task calls ajevwat to wait for an event, it specifies the group id of the eventgroup containing the events of interest. It provides a 16-bit mask identifying which of theevents are of interest and a 16-bit value indicating the particular state of interest for eachof the selected events. The task also specifies one of two types of match criterion to beused for event detection. Tasks can wait for any one of the selected events in the groupto achieve its specified state. Alternatively, the task can insist that all of the selectedevents must exactly match their specified state before an event match can be declared.

Finally, the task calling ajevwat must also specify the interval, measured in system ticks,which it is prepared to wait for the event match to occur. Upon return from ajevwat, thetask receives status indicating whether an event match occurred within the expected timeinterval. Note that a task will not be forced to wait if the state of the event flags meetsthe task's match criterion at the time of the call.

106 KADAK AMX Event Manager

Events are signalled by tasks, ISPs and Timer Procedures. The event is signalled with acall to procedure ajevsig. The caller specifies the group id of the event group whichcontains the particular event. More than one event can be signalled in a single call toajevsig. The caller specifies a 16-bit mask identifying the particular event flags in thegroup and a 16-bit value which specifies the new state of each of these selected eventflags.

Whenever an event is signalled, the Event Manager determines if any tasks are waitingfor any of the events in the particular group. If tasks are waiting on the group, the EventManager checks the new state of the event flags to see if the event match criterion of anyof the waiting tasks has been achieved. Whenever an event match is detected, the EventManager wakes the task whose match criterion has been met. Providing that no tasks ofhigher priority are executing, the task will resume execution with an indication that theevent combination for which it was waiting has occurred.

If a task needs to know the exact state of the event flags at the time its event matchoccurred or timed out, it can issue a call to the Event Manager procedure ajevnt.

A task, ISP or Timer Procedure can determine the current state of the event flags at anyinstant with a call to ajevrd.

If an event group is no longer required, the group can be deleted with a call to the EventManager procedure ajevdel. The Event Manager will free the event group for reuse.The Event Manager will not allow you to delete an event group which has one or moretasks still waiting for events in the group.

You must be absolutely certain that no task, ISP or Timer Procedure is referencing theevent group just as you go to delete it. Be aware that the event group id may immediatelybe reused by AMX for some other purpose.

AMX Event Manager KADAK 107

7.3 Event Flag ApplicationThe following example, coded in C, is provided to illustrate the use of the AMX EventManager for event synchronization.

The example shows two tasks, A and B, which must be synchronized to the state of amotor. Task A must wait for the motor to be turned on. Task B must wait for the motorto be on and up to its maximum speed.

A 100 millisecond interval timer samples a motor control status register to determine thestate of the motor. Whenever the motor state changes, the Timer Procedure signals theevent. Note that the Timer Procedure signals both the on/off state and the motor speedsimultaneously. It only signals changes in the motor state so that event synchronizationoverhead is minimized.

Note that the Timer Procedure receives its timer's id timerid and a parameter unused,neither of which is used by the procedure.

A Restart Procedure allocates an event group for motor control. Two of the event flags inthe group are initialized to reflect the state of the motor at the time the system wasstarted. The remaining event flags in the group are unused. A 100 millisecond periodicinterval timer is created and started.

The creation and starting of Tasks A and B is outside the scope of this example. It isassumed that if the Restart Procedure is unable to create an event group for motor control,Tasks A and B will not be started. In our example, Tasks A and B assume that a validevent group id has been provided in variable motorgroup.

Note that bit 0 of the motor control status register determines if the motor is on or off.Bit 1 of the motor control status register determines if the motor is at maximum speed.For convenience, event flags 0 and 1 (bits 0 and 1 in the event group) are assigned tomirror the corresponding bits in the motor control status register.

108 KADAK AMX Event Manager

#include "amx831cf.h" /* AMX C Interface Header */

static AMXID motorgroup;static unsigned char motorstatus;

#define MOTORPORT 0x65 /* Motor status port */#define MOTORON 0x01 /* Motor on */#define MOTORMAX 0x02 /* Motor at maximum speed */

#define MOTOREVT (MOTORON + MOTORMAX)

void cdecl tpmotor( /* Motor Timer Procedure */AMXID timerid, void *unused) /* Unused parameters */{

unsigned int status;

status = ajinb(MOTORPORT) & MOTOREVT;

/* If a change in motor status occurs *//* Update motor status *//* Signal that changes have occurred */

if (status != motorstatus) {motorstatus = status;ajevsig(motorgroup, MOTOREVT, status);}

}

void cdecl rrmotor(void) /* Motor Restart Procedure */{

AMXID timerid;

motorstatus = ajinb(MOTORPORT) & MOTOREVT;

/* If an event group is available *//* Set the initial event states to match the motor status *//* If a 100 ms periodic timer can be created *//* Start it to go off at the next AMX system tick */

if (ajevcre(&motorgroup, motorstatus, "EVMT") == AEROK) {if (ajtmcre(&timerid, ajtmcnv(100), tpmotor,

NULL, "TMMT") == AEROK)ajtmwr(timerid, 1); /* Start timer */

}}

AMX Event Manager KADAK 109

void cdecl sttaskA(void) /* Task A */{

/* Wait forever for motor on */if (ajevwat(motorgroup, MOTORON, MOTORON, 0, 0) == AEROK) {

:Motor is on.Process accordingly.:}

}

void cdecl sttaskB(void) /* Task B */{

/* Wait 5 seconds for motor *//* on and at maximum speed */

if (ajevwat(motorgroup, MOTOREVT, MOTORON + MOTORMAX,1, ajtmcnv(5000)) == AERTMO) {

:Motor not on and up to speed.Take recovery action.:}

else {:Motor is on and up to speed.Process accordingly.:}

}

110 KADAK AMX Event Manager

This page left blank intentionally.

AMX Message Exchange Manager KADAK 111

8. AMX Message Exchange Manager

8.1 IntroductionThe AMX Message Exchange Manager provides a very flexible, general purposemechanism for inter process communication and synchronization using prioritizedmessages. In particular, it offers an instant solution to a common problem frequentlyencountered in real-time applications: one or more processes (producers) having toasynchronously deliver requests of varying priorities for service to one or more servers(consumers) whose identity is unknown to the producer.

For example, assume that two printers are available to print reports and that requests forspecific reports originate from a periodic Timer Procedure, from a data acquisition taskand from a data base update task. The producers do not know which printer, if any, isfree for use at the instant they must initiate their requests. Furthermore, if no printer isfree, the data acquisition task and Timer Procedure are unable to wait for a printer tobecome available. The data acquisition task must be able to inject high priority printrequests when errors are detected. How then to solve the problem?

The Message Exchange Manager readily provides the solution. A message exchange iscreated to act as a prioritized print request queue. The data acquisition task, TimerProcedure and data base task send their print requests to the message exchange. Twoprint server tasks, one for each printer, wait on the message exchange for the next printrequest. Each print server completes the generation of one report on its printer and thengoes back to the exchange for the next request.

As just illustrated, the AMX Message Exchange Manager provides an extension to theinherent message passing services offered by AMX. The AMX kernel only allows amessage to be sent to the particular task identified by the sender. The Message ExchangeManager extends the message delivery system to permit any task, ISP or Timer Procedureto receive a message. In so doing, it also removes the restriction requiring the messagesender to identify the message receiver.

The Message Exchange Manager uses a message exchange to deliver messages. Amessage exchange consists of four message queues into which messages can bedeposited. The message queues are ordered according to priority (0, 1, 2 or 3), messagequeue 0 being of highest priority.

Messages are delivered to the message queues in a message exchange in messageenvelopes. These are the same envelopes that are used by AMX to deliver messages totask mailboxes (see Chapter 3.9).

Any task, ISP, Timer Procedure or Restart Procedure can send a message to a messageexchange. The sender indicates the priority of its message (0 to 3) thereby identifying themessage queue into which it will be delivered.

Any task, ISP or Timer Procedure can request a message from a message exchange.Only tasks are allowed to wait for the arrival of a message if none is present in themessage exchange when the task makes its request. A task can specify the priority atwhich it is willing to wait and the maximum time interval which it will wait for amessage to arrive.

112 KADAK AMX Message Exchange Manager

The task's wait priority is not to be confused with the message queue priority. Themessage queue priority determines the priority ordering of messages in the messageexchange when no task is waiting for a message. The task's wait priority determines theorder of tasks in the wait queue when more than one task is waiting for a message toarrive at an empty message exchange.

The flexibility of a message exchange comes from the fact that any number of consumersand producers can rendezvous at a message exchange without explicit knowledge of eachother. Each consumer and producer only needs to know which message exchange to use.No consumer or producer owns the message exchange.

Constraints on the use of message exchanges are self-imposed by the system designer.You determine which producers and consumers will use each of your messageexchanges. The only restriction imposed by the Message Exchange Manager is that onlytasks are allowed to wait for a message to arrive at an empty message exchange.

The AMX Message Exchange Manager provides the following message exchangeservices:

ajmxcre AAMXCRE Create a message exchangeajmxdel AAMXDEL Delete a message exchangeajmxsnd AAMXSND Send a message to a message exchangeajmxsndfajmxsndpajmxget AAMXGET Get a message from a message exchange (no wait)ajmxwat AAMXWAT Wait for message to arrive at a message exchange

(optional timeout)ajmxtag AAMXTAG Find exchange id of a message exchange with a specific tag

Your use of the Message Exchange Manager is optional. If you intend to use it you mustindicate so in your System Configuration Module. You must provide a hardware clockand include the AMX timing facilities.

Message exchanges can be predefined in your System Configuration Module which isprocessed by the Message Exchange Manager at startup. Message exchanges which arepredefined are automatically created by the Message Exchange Manager. The messageexchange id assigned to each predefined message exchange is stored in a variable whichyou must provide for that purpose.

AMX Message Exchange Manager KADAK 113

8.2 Message Exchange UseThe Message Exchange Manager supports any number of message exchanges. Themaximum number of message exchanges in a system is defined in your SystemConfiguration Module (see Chapter 14.5). The defined maximum sets an upper limit onthe number of actual message exchanges that can be created in your application.

A message exchange must be created by an application before it can be used. RestartProcedures, tasks, ISPs and Timer Procedures can create exchanges. It is recommendedthat only Restart Procedures and tasks be used to create message exchanges.

Create

Message Exchange Manager procedure ajmxcre is used to create a message exchange.The Message Exchange Manager allocates a message exchange and returns a messageexchange id to the caller. The exchange id is a handle which uniquely identifies themessage exchange. It is the responsibility of the application to keep track of the messageexchange id for future reference to the exchange.

When a message exchange is created, you must specify the maximum number of messageenvelopes which are allowed to reside in each of the message exchange's four messagequeues. Message queue depths may range from 0 to 32767. If a particular queue is notused, set that queue's depth to zero. At least one message queue must have a non-zerodepth.

Message queue depth has no effect on AMX memory requirements. That is, increasing amessage queue depth does not increase memory needs. The message queue depths canbe used to limit the number of messages allowed to be pending at the message exchangeat any instant.

When a message exchange is created, you can provide a unique 4-character tag toidentify the message exchange. The tag can be used subsequently in a call to ajmxtag tofind the message exchange id allocated by the Message Exchange Manager to theparticular message exchange.

When the Message Exchange Manager creates a message exchange, it sets all of themessage exchange's message queues empty.

Send

A message is sent to a message exchange with a call to procedure ajmxsnd (or itsvariations ajmxsndf or ajmxsndp). The sender must specify the message priority (0highest; 3 lowest) thereby indicating the message queue into which the message will bedelivered. If the specified message queue is full or has been defined to have a depth ofzero, the sender will be given an error indication.

A message is a set of parameter bytes located contiguously in memory. The maximumnumber of parameter bytes in a message is configured by you in your SystemConfiguration Module (see Chapter 14.4). These parameter bytes are completelyapplication dependent. The message size exactly matches that used for task mailboxmessages (see Chapter 3.9).

114 KADAK AMX Message Exchange Manager

Messages are sent to message exchanges in AMX message envelopes. The MessageExchange Manager gets a free message envelope from the common pool of envelopesmaintained by AMX. You must therefore be sure to allocate enough message envelopesto meet the needs of all of your message exchange messages as well as your taskmessages.

Receive

Any task, ISP or Timer Procedure can get a message from a message exchange by callingprocedure ajmxget. If the message exchange has any messages, the highest prioritymessage (0 highest; 3 lowest) which arrived first will be given to the caller. If themessage exchange is empty, the caller will immediately receive an error indication.

Tasks can also call procedure ajmxwat to get a message from a message exchange. Onlytasks are allowed to call this procedure because the caller may have to wait for a messageto arrive at the message exchange. If the message exchange has any messages, thehighest priority message (0 highest; 3 lowest) which arrived first will be given to thecaller. If the message exchange is empty, the caller will be forced to wait for a messageto arrive.

The task specifies the interval, measured in system ticks, which it is willing to wait for amessage to arrive. An interval of 0 indicates a willingness to wait forever. The task mustalso specify the priority at which it is prepared to wait, zero being the highest priority.

The Message Exchange Manager will add the task to the message exchange's wait queueat the priority the task said it was willing to wait. Thus a task can preempt other tasksalready waiting in the queue at lower priority.

When a message finally arrives at the message exchange, the Message ExchangeManager will give it to the task, if any, at the head of the message exchange's wait queue.A task switch may occur immediately if the task being given the message is of highertask priority than the currently running task.

If no message arrives at the message exchange before the timeout interval specified by atask expires, the task will be removed from the message exchange wait queue and willresume execution with a timeout indication.

Delete

When a message exchange is no longer needed, it can be deleted with a call to ajmxdel.The Message Exchange Manager will reject the attempt to delete the message exchange ifany task is waiting on the message exchange wait queue or if any messages remain in anyof the exchange's message queues. When the Message Exchange Manager deletes themessage exchange, it marks the message exchange as invalid such that any subsequentreference to the message exchange will be rejected.

You must be absolutely sure that no producer or consumer is referencing the messageexchange just as you go to delete it. Be aware that the deleted message exchange id maybe immediately reused by AMX for some other purpose.

AMX Message Exchange Manager KADAK 115

8.3 Message Exchange ApplicationThe following example, coded in C, is provided to illustrate the use of the AMX MessageExchange Manager.

This example illustrates a solution to the problem posed in the introduction (Chapter 8.1).Two message processing tasks, A and B, accept and service the messages from the dataacquisition and data base tasks and the Timer Procedure. The processing tasks expectmessages to arrive within 5 seconds.

A Restart Procedure creates the message exchange with message queues 0, 2 and 3, eachof depth 10. In our example, the tasks and Timer Procedure assume a valid messageexchange id has been provided in variable msgexch. The Restart Procedure also createsand starts the Timer Procedure.

The creation and starting of tasks A and B and the creation of the data acquisition anddata base tasks is outside the scope of this example. It is assumed that if the RestartProcedure is unable to create the message exchange, the tasks will not be started.

Since we do not know how the data acquisition task and the data base update task werecreated, we will assume that their task ids are available in global variables as would bethe case if the AMX Configuration Builder had been used to create the tasks.

The Timer Procedure triggers the data acquisition task once a second and sends atime-stamp message to the message exchange at the highest priority, 0.

The data acquisition task samples the data, triggers the data base update task and sends adata sample message to the message exchange at medium priority 2.

The data base update task processes the sampled data, updates the data base and sends adata update message to the message exchange at low priority 3.

Note that the two tasks, sttaskA and sttaskB, share a common re-entrant task body,sttask. In practice, procedure sttaskB could be eliminated and Task B could be createdwith sttaskA as the task start address. The example is coded to more clearly illustratethat two tasks actually exist.

116 KADAK AMX Message Exchange Manager

#include "amx831cf.h /* AMX C Interface Header */

#define UMS 12 /* User message size */

extern AMXID dactid; /* Data acquisition task id */extern AMXID dbtid; /* Data base update task id */

static AMXID msgexch; /* Message exchange id */

struct appmsg { /* Message structure */short int msgtype; /* Application message type */short int rsv; /* Reserved for alignment */long data; /* Data sample */void *dbp; /* Pointer to data base */};

union msgu {long maxmsg[UMS/sizeof(long)]; /* Maximum message size */struct appmsg umsg; /* User message */};

/* Timer Procedure */void cdecl tmrproc(AMXID tmrid, void *unused){

union msgu msgbuf; /* Message buffer */

:Construct message in msgbuf.umsg:ajmxsnd(msgexch, 0, &msgbuf); /* Send message at priority 0 */

ajtrig(dactid); /* Trigger data acquisition task*/}

void cdecl rrmsg(void) /* Restart Procedure */{

AMXID tmrid; /* Timer id */

if (ajtmcre(&tmrid, /* Create periodic 1 sec timer */ajtmcnv(1000),(void (*)())tmrproc,NULL, "TIMR") == AEROK)

ajtmwr(tmrid, 1); /* Start timer immediately */

/* Create message exchange */ajmxcre(&msgexch, 10, 0, 10, 10, "MSGX");}

AMX Message Exchange Manager KADAK 117

void cdecl sttask(void) /* Common task body */{

union msgu msgbuf; /* Message buffer */int status;

/* Wait at priority 0 for *//* up to 5 sec for message */

status = ajmxwat(msgexch, &msgbuf, ajtmcnv(5000), 0);

if (status == AEROK) {:Process the message in msgbuf.umsg:}

else if (status == AERTMO) {:Process timeout - no message in 5 seconds:}

else {Message retrieval failedProcess some other error condition}

}

void cdecl sttaskA(void) /* Task A */{

for (;;) sttask(); /* Do sttask forever */}

void cdecl sttaskB(void) /* Task B */{

for (;;) sttask(); /* Do sttask forever */}

118 KADAK AMX Message Exchange Manager

void cdecl dactask(void) /* Data acquisition task */{

union msgu msgbuf; /* Message buffer */

:Perform data acquisition functions:if (no_error) {

:Construct message in msgbuf.umsg:

/* Send message at priority 3 */ajmxsnd(msgexch, 3, &msgbuf);:}

else { /* Error has occurred! */:Construct message in msgbuf.umsg:

/* Send error message at *//* priority 0 */

ajmxsnd(msgexch, 0, &msgbuf);}

ajtrig(dbtid); /* Trigger data base task */}

void cdecl dbasetask(void) /* Data base update task */{

union msgu msgbuf; /* Completion message */

:Perform data base update functions::Construct message in msgbuf.umsg:

/* Send completion message at *//* priority 2 */

ajmxsnd(msgexch, 2, &msgbuf);}

AMX Buffer Manager KADAK 119

9. AMX Buffer Manager

9.1 IntroductionThe AMX Buffer Manager simplifies the management of memory buffers in a real-timesystem. It provides a general mechanism for the allocation and control of fixed sizebuffers.

The AMX Buffer Manager provides fast, efficient access to multiple pools of buffers,each buffer representing a fixed size block of memory. This form of memorymanagement meets the requirements of most typical applications and is best suited forreal-time use in which memory block availability must be predictable and in which thepenalties for memory fragmentation cannot be tolerated.

You define a set of buffer pools, each pool containing a set of buffers of uniform size.Buffer Manager procedures are called to obtain a buffer from a particular pool and torelease it back to the pool when it is no longer required.

When released, the buffer is automatically returned by the Buffer Manager to the pool towhich the buffer belongs. Buffer ownership can be increased so that more than one taskcan simultaneously own a shared buffer. Special facilities are provided to assure that if abuffer is owned by more than one task, it is only returned to its pool when the slowestowner finally releases it.

Speed of execution is not dependent on the number of pools or buffers. The number ofbuffers in a pool is limited by the fact that all buffers of a particular pool must reside inone 64K segment. The number of pools which can be supported is limited only bymemory availability.

The AMX Buffer Manager provides the following buffer management services:

ajbcre AABCRE Create a buffer poolajbdel AABDEL Delete a buffer poolajbget AABGET Get a buffer from a specific buffer poolajbfre AABFRE Release a bufferajbgsz AABGSZ Get size of bufferajbau AABAU Add to buffer use countajbia AABIA Initialize all currently defined buffer poolsajbip AABIP Initialize one buffer poolajbtag AABTAG Find buffer pool id of a buffer pool with a specific tag

Your use of the Buffer Manager is optional. If you intend to use it you must indicate soin your System Configuration Module.

Buffer pools can be predefined in your System Configuration Module which is processedby the Buffer Manager at startup. Buffer pools which are predefined are automaticallycreated by the Buffer Manager. The buffer pool id assigned to each predefined bufferpool is stored in a variable which you must provide for that purpose.

120 KADAK AMX Buffer Manager

9.2 Buffer Pool UseThe Buffer Manager supports any number of pools of buffers. The maximum number ofbuffer pools in a system is defined in your System Configuration Module (see Chapter14.5). The defined maximum sets an upper limit on the number of actual buffer poolsthat can be created in your application.

A pool of buffers consists of any number of buffers of a uniform size measured in bytes.Any even buffer size greater than or equal to eight bytes is allowed, up to the limits of a64K memory segment. All of the buffers in a pool must reside in the same memorysegment.

Create Buffer Pool

A buffer pool must be created by an application before it can be used. RestartProcedures, tasks, ISPs and Timer Procedures can create buffer pools. It is recommendedthat only Restart Procedures and tasks be used to create buffer pools.

Buffer Manager procedure ajbcre is used to create a buffer pool. The Buffer Managerallocates a buffer pool and returns a buffer pool id to the caller. The pool id is a handlewhich uniquely identifies the buffer pool. It is the responsibility of the application tokeep track of the pool id for future reference to the buffer pool.

When a buffer pool is created, you must specify the following parameters: the number ofbuffers in the pool, the size of each buffer and a pointer to RAM storage for all of thebuffers in the pool.

When a buffer pool is created, you can provide a unique 4-character tag to identify thebuffer pool. The tag can be used subsequently in a call to ajbtag to find the buffer poolid allocated by the Buffer Manager to the particular buffer pool.

When the Buffer Manager creates a buffer pool, it subdivides the allocated RAM storageinto the required number of buffers.

All buffers in the pool are linked together on a free list. This free list is internal to theBuffer Manager, hidden from view. Associated with (but not part of) each buffer is a usecount, also internal to the Buffer Manager. The use count is set to zero for each buffer toshow that it is not in use.

AMX Buffer Manager KADAK 121

Get Buffer

Once a buffer pool has been created, you may call procedure ajbget to get a buffer fromthe pool. The Buffer Manager unlinks a buffer from the pool's free list, sets theassociated buffer use count to one and returns a pointer to the first byte of the buffer.You may then store and retrieve any data in the buffer as desired.

If there are no free buffers available in the pool when a request to get a buffer from thepool is made, the Buffer Manager returns an error indication to the caller.

Free Buffer

When the buffer is no longer required, you can call procedure ajbfre to release thebuffer. You indicate the buffer to be released by specifying the pointer to the first byte ofthe buffer, the same pointer that was received when you originally acquired the buffer.The Buffer Manager decrements the use count associated with the buffer by one. If theuse count becomes zero, the buffer is linked to the free list of the pool to which itbelongs.

Use Count

Once you own a buffer, you may call procedure ajbau to increase the use count. Recallthat when a buffer is first obtained, the use count is set to one. If the use count is thenincreased by one, the buffer will have to be released twice before it becomes free. Incertain applications such as described in Chapter 9.3, this feature is essential.

Size

You may also call procedure ajbgsz to obtain the size of the buffer. Because the bufferwas obtained from a pool with buffers of known size, this call is usually unnecessary.However, in applications in which the current owner of a buffer did not actually acquirethe buffer from the Buffer Manager, it is convenient to be able to determine the buffersize.

Delete

If at some point, there is no longer a need for any of the buffers in the buffer pool, theentire buffer pool can be deleted with a call to procedure ajbdel. It is your responsibilityto assure that none of the buffers in the pool are still being used at the time you delete thepool. Once a buffer pool has been deleted, all of the RAM storage provided by you whenthe buffer pool was created is available for reuse by the application.

You must be absolutely certain that no task, ISP or Timer Procedure is referencing thebuffer pool just as you go to delete it. Be aware that the deleted buffer pool id mayimmediately be reused by AMX for some other purpose.

122 KADAK AMX Buffer Manager

9.3 Buffer ApplicationsConsider the following example. A process control system using AMX has a printer onwhich errors and status messages are to be logged. These messages are generated byseveral tasks as they perform their process control functions. These tasks must not waitfor the printer because they have more important work to do. Furthermore, each messagesize may exceed the standard AMX message size.

A printer task receives the messages from the other tasks and outputs them to the printer.The problem is to get these messages from the process control tasks to the printer task.

The Buffer Manager provides an ideal solution. A pool of buffers is defined anddedicated to error logging. As each process control task detects an error, it calls theBuffer Manager to obtain a buffer, fills the buffer with an appropriate error message andmakes an AMX ajsend call, sending the buffer pointer in an AMX message envelope tothe task mailbox of a printer task.

The printer task automatically executes every time an AMX message arrives in its taskmailbox. The AMX message is delivered to the task on its stack. The printer taskextracts the buffer pointer from the AMX message, outputs the contents of the buffer tothe printer, calls the Buffer Manager to release the buffer and ends. Because the processcontrol tasks need never wait for the printer task or printer, they are always available toperform their intended functions.

Now consider the following addition to this example. Suppose it is desired to logmessages on both a display and printer. There are several ways this could be done.

1. Two buffers could be obtained from the Buffer Manager. The same messagewould be copied into both buffers. One would be sent to a printer task mailbox,the other to a display task mailbox.

2. A single buffer could be obtained from the Buffer Manager. It would be filledwith a message and sent to the display task mailbox. The display task wouldoutput the message to the display and send the buffer to the printer task mailbox.The printer task would output the message to the printer and release the buffer.

3. A single buffer could be obtained from the Buffer Manager. The message wouldbe copied into the buffer. The Buffer Manager would be called to increase thebuffer use count by one, for a total use count of two. The buffer pointer wouldthen be sent to both the printer task mailbox and the display task mailbox. Bothtasks would output the message to their output device and release the buffer.When the slowest of these two tasks released the buffer, the use count would bezero and the buffer would be free.

AMX Buffer Manager KADAK 123

These solutions each have their own advantages and disadvantages. Method 1 requirestwice as many buffers as the other methods and requires extra processor time to copy themessage twice. Method 2 cannot display the message simultaneously on both the CRTand printer. Also, method 2 requires the display task to know about the printer task'smailbox. Method 3 is the most desirable.

Can method 3 be improved? Having the process control tasks know about the displayand printer makes future system modification difficult. Instead, a single reentrantmessage routing procedure could be added to process all messages and determine if theyshould be sent to the display task mailbox or printer task mailbox or both. If the messagerouting procedure decided to send the buffer to both, it would call the Buffer Manager toincrease the buffer use count before passing the buffer on. As in method 3, the displayand printer tasks would only have to output the buffer, release it and then end. Theprocess control tasks would only have to get a buffer from the Buffer Manager, fill it witha message and call the message routing procedure to send it to the appropriate taskmailboxes.

What if the messages have to be sorted by priority? Just use the task mailbox prioritiesoffered by the AMX message passing services.

124 KADAK AMX Buffer Manager

9.4 Buffer Manager CaveatsAlthough the Buffer Manager attempts to check as many error conditions as possible, itcannot protect against a bad system design. However, if a little care is taken duringsystem design, the Buffer Manager can help make a system more reliable than one thatuses an ad hoc buffer management method.

The most important concept to understand about the Buffer Manager is bufferownership. The Buffer Manager owns all free buffers. You must never modify these inany way.

Once you get a buffer (with a call to the Buffer Manager), you own the buffer. You maymodify the contents of the buffer while it is owned. Once you release the buffer or pass itto another concurrently executing task or Interrupt Service Procedure, then the buffer isno longer owned by you and may not be modified or released or have its use countaltered by you in any way.

If the use count is increased by the owner of a buffer, then several simultaneous ownersare allowed. However, when there are several concurrently executing owners, the buffercontent must not be modified unless your design is such that each owner can write to itsown private portion of the buffer. The only permitted operations are reading the bufferand releasing it. Each owner should either release the buffer or pass the ownership on toanother routine that will release it.

These restrictions are characteristic of message passing between concurrently executingroutines in general, not just of the AMX Buffer Manager. To illustrate the necessity ofthese restrictions, a few examples of incorrect usage follow.

1. Task A gets a buffer, fills it, passes it to Task B and releases it. Task B attemptsto use the data in the buffer.

The problem is that Task A released the buffer after it passed ownership toTask B. Thus Task B will receive a buffer which it does not own. If Task Bmodifies the buffer, then the Buffer Manager may produce unpredictable resultsthe next time it tries to use the buffer.

The solution is to have Task B release the buffer when it is finished with it.Task B may do this because it owns the buffer after it receives it from Task A.

2. Task A gets a buffer, fills it, passes it to Task B, increments the use count by oneand passes the buffer to task C. Tasks B and C use the buffer and release it.

The problem is that Task A has passed ownership to Task B without first retainingthe ownership by increasing the use count. It then increases the use count of abuffer it doesn't own. In the meantime, Task B may have finished using thebuffer and released it.

The solution is to have Task A expand the ownership by increasing the use countbefore passing the buffer to Task B. Task A then retains one half of theownership and may pass this ownership on to Task C.

AMX Memory Manager KADAK rev9 125

10. AMX Memory Manager

10.1 IntroductionThe AMX Memory Manager simplifies the management of memory in an AMX system.It provides a general mechanism for the dynamic allocation and control of memory and isspecifically designed for use in a multitasking environment.

Multitasking adds particular difficulties to the general problem of memory allocation.For example, high level language memory management procedures, such as C's malloc,calloc or free, cannot be called from concurrently executing tasks since the proceduresare usually not reentrant.

The Memory Manager resolves these difficulties. The Memory Manager's generalallocation procedures allow concurrently executing tasks to allocate and free blocks ofmemory.

The Memory Manager allocates memory from a memory pool containing a set of one ormore sections of contiguous memory. Memory Manager procedures are called to obtaina memory block of any size from the memory pool and to release it back to the pool whenit is no longer required.

When released, the memory is automatically returned by the Memory Manager to itsmemory pool. A memory block use count is maintained to allow a single block to haveseveral owners and to prevent the block from being released until it is discarded by allowners. Hence, more than one task can simultaneously own a shared piece of memory.If a memory block is owned by more than one task, it is only returned to the memorypool when the slowest owner finally releases it.

The AMX Memory Manager maintains a single memory pool. The amount of memory inthe pool is limited only by memory availability.

A particular unique feature of the Memory Manager permits any block of memory(including those acquired from the memory pool controlled by the Memory Manager) tobe treated as a separate memory section from which smaller private blocks can bedynamically allocated. This feature allows a task which has well defined memoryrequirements to reserve a memory block for its own private use. The task can then callon the Memory Manager to control the allocation and release of smaller blocks fromwithin the larger private block.

Note

The AMX 86 Memory Manager provides fast and efficientallocation of paragraph (16-byte) aligned blocks of memoryfor 80x86 systems with 16-bit memory addressing.

When used with the VAutomation Turbo86 processors with24-bit memory addressing, memory blocks are allocatedwith 16-byte alignment, not page (256 byte) alignment.For additional information, see the AMX 86 Tool Guide forParadigm toolset PX.

126 KADAK AMX Memory Manager

The AMX Memory Manager provides the following memory management services:

ajmget AAMGET Get a block of memoryajmfre AAMFRE Release a block of memoryajmgsz AAMGSZ Get the size of a block of memoryajmau AAMAU Add to block use countajmset AAMSET Set memory to a patternajmsetf

ajmhan AAMHAN Create a handle to a private memory sectionajmgeh AAMGEH Get a block of memory from a private memory section

Your use of the Memory Manager is optional. If you intend to use it you must indicate soin your System Configuration Module.

The memory for the memory pool controlled by the Memory Manager is assigned to thepool by the Memory Assignment Procedure which you identify in your SystemConfiguration Module. The Memory Manager calls your procedure at startup to acquireall of the memory over which it will have control.

AMX Memory Manager KADAK 127

10.2 NomenclatureThe following nomenclature has been adopted by the Memory Manager.

A Memory Section is a contiguous, double word aligned area of Random AccessMemory Random (RAM) which has been specified by the user to be under the control ofthe Memory Manager. A section can exceed 64K bytes in size.

The AMX Memory Pool is the private collection of one or more memory sections underthe control of the Memory Manager from which tasks can request memory to be allocatedfor their private use.

A Memory Block is a double word aligned, contiguous portion of memory allocated bythe Memory Manager from a memory section for use by a task. A memory block canexceed 64K bytes in size.

A Header (i.e. Memory Block Header) is an area of RAM associated with (but not partof) a memory block. It contains control information which is private to the MemoryManager and not accessible to any task.

A Block Use Count is an integer associated with (but not part of) a memory block. It isused by the Memory Manager to keep track of the number of owners of the memoryblock.

A Memory Handle is a 32-bit identifier provided by the Memory Manager to identify amemory block which is private to a task but still under the control of the MemoryManager.

128 KADAK AMX Memory Manager

10.3 Memory AllocationThe Memory Manager maintains a single memory pool. The memory pool consists ofany number of memory sections of varying sizes measured in bytes. Any memorysection size which is a multiple of 4 and greater than or equal to 64 bytes is allowed.Usually the memory pool consists of a single large memory section.

Memory sections are given to the Memory Manager by your Memory AssignmentProcedure at startup. Once AMX is up and running, memory sections cannot be added orremoved from the memory pool.

When the Memory Manager assigns a memory section to its memory pool, it treats thememory section as one large free memory block linked together with other free blocks ona free list. This free list is internal to the Memory Manager, hidden from view.

Get Memory

Once the Memory Manager's memory pool has been initialized, a task can call theMemory Manager procedure ajmget to get a block of memory of any size from the pool.Only tasks are allowed to call the Memory Manager to acquire memory blocks.

If the Memory Manager is able to find a block of memory in the memory pool largeenough to meet the caller's requirements, the caller will be given a pointer to the memoryblock and an indication of the actual size of that block. The block may be marginallylarger than the size requested. The memory block use count is set to one.

If the Memory Manager cannot locate a memory block in the memory pool large enoughto meet the caller's requirement, it returns an error indication to the caller and identifiesthe largest block which is available in the pool at that instant. Note, however, that if thecalling task immediately requests a block of memory equal to this largest memory blocksize, the request may still fail because, in a multitasking system, other higher prioritytasks may have grabbed some of that memory before the task can make another request tothe Memory Manager.

Free Memory

When use of a memory block is no longer required, the owner can call procedure ajmfreto release the block. The caller specifies the block to be released by passing the MemoryManager the same pointer that it received when the Memory Manager originally allocatedthe block.

The Memory Manager decrements the memory block's use count and, if the count goes tozero, returns the block to its memory pool. If there are any free memory blocks adjacentto the released block, they are merged with the block being released to form a largerblock.

Once a block is released, no task in the system can make reference to it. The block entersthe private domain of the Memory Manager.

AMX Memory Manager KADAK 129

Use Count

When the Memory Manager allocates a block of memory for the use of a task, it sets theblock's use count to one. The block owner may call the Memory Manager procedureajmau to increase the use count. If the use count is increased by one, the block will haveto be released twice before it becomes free.

The block use count provides the key to memory block ownership. The MemoryManager owns all free blocks in its memory pool. One or more tasks can own an alreadyallocated memory block. This concept of block ownership is the same as that of bufferownership provided by the AMX Buffer Manager. Refer to Chapters 9.3 and 9.4 forexamples of the proper use of this ownership concept.

Size

The Memory Manager procedure ajmgsz can be used to obtain the size of a particularmemory block. This feature can be useful if one task is given ownership of a memoryblock by another task. The new block owner can check the size of the memory block tobe sure that it meets its requirements. If a task corrupts the contents of any memorylocation outside the bounds of the memory block, the effects are unpredictable andpotentially disastrous.

Once allocated, a memory block cannot grow or shrink in size. Hence, the size of amemory block cannot be dynamically adjusted by its owner.

130 KADAK AMX Memory Manager

10.4 Private Memory AllocationA particularly unique feature of the Memory Manager permits any block of memory(including those acquired from the Memory Manager) to be treated as a memory sectionfrom which smaller private blocks can be dynamically allocated.

To use this feature, a task calls procedure ajmhan giving it a pointer to a private area ofmemory whose access is to be controlled by the Memory Manager. Blocks allocated byprocedure ajmget or ajmgeh are suitable for this purpose. The caller must also specifythe size of the memory area provided.

The Memory Manager takes the memory area which it has been given and converts it intoa memory section for the private use of the task. This private section is identified by amemory handle, a 32-bit identifier which is returned to the caller. As long as the taskdoes not make the memory handle public, the section remains private to the task.

The memory handle must be used to allocate smaller blocks from the private memorysection. Memory Manager procedure ajmgeh is used to acquire a memory block from aprivate memory section identified with a handle. Once a private memory section hasbeen created, any task having the handle can acquire a memory block from the privatesection. It is up to the task which created the private memory section to determine whichtasks are given the handle.

AMX Memory Manager KADAK 131

10.5 Memory AssignmentThe sections of memory which make up the memory pool controlled by the MemoryManager must be provided by your application. The Memory Manager makes noassumptions concerning the whereabouts of the memory over which it has control.

Sections of memory are assigned to the Memory Manager by your application. You mustprovide a Memory Assignment Procedure which will be called by the Memory Managerto acquire the memory sections over which it is to have control. A definition of thisprocedure is provided in Chapter 10.6.

If no Memory Assignment Procedure is provided, the Memory Manager will alwaysreport that no memory is available whenever any task requests a memory block.

When your AMX system is first started, the Memory Manager has no memory to allocateto tasks. When AMX is started, the Memory Manager determines if you have provided aMemory Assignment Procedure. If one was provided, the Memory Manager calls it toacquire a memory section. Your procedure must return a pointer to a memory sectionand indicate its size. The manner in which your procedure derives section pointers is upto you.

The Memory Manager initializes the section returned by your Memory AssignmentProcedure. If the size of a section is less than the minimum required by the MemoryManager, the section is ignored. Your Memory Assignment Procedure is then calledagain. This process proceeds until your procedure returns an indication that no moresections are available.

Once your Memory Assignment Procedure indicates that there are no more sectionsavailable, the Memory Manager ceases its calls to your procedure. At that point, theMemory Manager has reached the upper limit of the memory over which it has control.

The Memory Manager will subsequently attempt to allocate a memory block for anycalling task from the memory sections which it has acquired. If the first memory sectionhas no free blocks large enough to meet the needs of the calling task, the next memorysection is checked to see if it meets the requirements of the caller. This process isrepeated until a block can be allocated to the caller or until all initialized sections havebeen exhausted.

Subsequent requests to the Memory Manager for a memory block will fail if a memoryblock of adequate size cannot be found in any of these initialized memory sections.

132 KADAK AMX Memory Manager

10.6 Memory Assignment ProcedureAn application Memory Assignment Procedure must be provided to dynamically assignmemory sections to the Memory Manager. The Memory Assignment Procedure is calledby the Memory Manager when AMX is started, prior to execution of any of your RestartProcedures.

The name of your Memory Assignment Procedure must be provided in your SystemConfiguration Module (see Chapter 14.5).

The Memory Assignment Procedure receives two pointers as parameters. The parameterspoint to storage for the size of the memory section and for a pointer to the section. TheMemory Assignment Procedure must return the size of the memory section in bytes and apointer to the memory section in the storage provided. The procedure must also return anon-zero integer if a valid memory section is provided. The minimum section size is 64bytes which, in practical terms, provides no useable memory.

If the Memory Assignment Procedure cannot assign another memory section, it mustreturn an integer result of zero without modifying the storage provided for the memorysize.

Upon entry to the procedure, the pointers to storage for the memory size and memorysection pointer are present on the stack. Upon entry to the procedure, the followingconditions exist:

Interrupts reflect the state specified at the time AMX waslaunched. If AMX was launched with launch parameterAMLPIE, interrupts will be enabled. Otherwise interrupts willbe disabled.

All registers are free for use.DS,ES DGROUP SegmentSS:SP AMX Kernel Stack ready for useBP Offset of parameters on stackThe direction flag is set to forward.

AMX Memory Manager KADAK 133

Your Memory Assignment Procedure can be coded as a Large or Medium model Cprocedure with formal parameters as follows.

int cdecl memproc(long *memsizep, /* Pointer to memory size storage */char **memptrp) /* Pointer to memory pointer storage */{

::if (another memory section is available) {

*memsizep = <size of memory section in bytes>;*memptrp = <pointer to memory section>;

return(1);}

return(0); /* No memory left */}

134 KADAK AMX Memory Manager

The Memory Assignment Procedure can be coded in assembler as a FAR procedure.

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;

PUBLIC MEMPROC;PARAM STRUC ;Define parameters on stack

DW ? ;Save BPDD ? ;Return address

MEMSIZEP DD ? ;A(storage for section size in bytes)MEMPTRP DD ? ;A(storage for memory section pointer)PARAM ENDS;MEMPROC PROC FAR

PUSH BPMOV BP,SP ;SS:BP = A(parameters on stack):Set AX = 0 if memory section is not available:OR AX,AXJZ MEMEXIT ;No section; AX = 0:Let DX:AX = size of memory section in bytesLES BX,[BP].MEMSIZEP ;ES:BX = A(memory size)MOV WORD PTR ES:[BX],AXMOV WORD PTR ES:[BX+2],DX:Let DS:SI = A(memory section)LES BX,[BP].MEMPTRP ;ES:BX = A(memory pointer)MOV WORD PTR ES:[BX],SIMOV WORD PTR ES:[BX+2],DSMOV AX,1 ;AX <> 0

;MEMEXIT: POP BP

RET;MEMPROC ENDP;USER_CODE ENDS

AMX Circular List Manager KADAK 135

11. AMX Circular List Manager

11.1 Circular ListsThe AMX Circular List Manager provides a general circular list facility for use byapplication program modules.

Circular lists must be located in alterable memory (RAM).

A circular list is a data structure used by an application to maintain an ordered list of8-bit, 16-bit or 32-bit elements. The elements are stored in slots in the list. Each listcontains a fixed, user defined number of slots.

The AMX Circular List Manager provides the following list manipulation procedures:

ajrstl AARSTL Reset (initialize) a circular listajabl AAABL Add to bottom of circular listajatl AAATL Add to top of circular listajrbl AARBL Remove from bottom of circular listajrtl AARTL Remove from top of circular list

The Circular List Manager procedures are reentrant permitting them to be shared byconcurrently executing tasks, ISPs and Timer Procedures.

Examples

Elements can be added to the top and removed from the bottom of a circular list. Thismakes these lists particularly attractive for character buffering by ISPs. Receivedcharacters can be added to the bottom of the circular list and removed from the top. If theprocess that removes a character decides that it cannot yet handle the character, it canreturn the character to the top of the circular list.

16-bit lists are useful for handling both a character and its receiver status. When acharacter is received, the character and its status are added to the bottom of a circular list.The task processing received characters pulls a 16-bit element from the top of the circularlist to get each character and its status.

32-bit lists can be used to manage pointers to more complex structures. For instance, asawmill application might use two lists to keep track of log measurements and resultinglumber counts in a Log Description Block, a private application structure. As logs aremeasured, their dimensions are inserted into a Log Description Block. A pointer to theblock is added to the bottom of a circular list which serves as input to the cutting process.This process removes a pointer to the next available Log Description Block from the topof this list. Once the log is cut, the log's lumber results are added to the block and theblock pointer is added to the bottom of another circular list for lumber tally processing.

136 KADAK AMX Circular List Manager

11.2 Circular List Use

A circular list is created by an application with a call to procedure ajrstl. The callermust provide three parameters: the number of slots in the list, the size of each slot (1, 2 or4 bytes) and a pointer to RAM storage for the circular list. The number of slots in acircular list is limited only by available memory and by the fact that the list must residewithin one 64K byte segment in memory.

The RAM storage area must be 16-bit aligned and provide (n*s)+8 bytes where n is thenumber of slots and s is the slot size (1, 2 or 4).

The Circular List Manager creates the list in the storage provided and sets the list empty.The Circular List Manager procedures can then be used to add and remove elements ofthe defined size at the top and/or bottom of the list.

The Circular List Manager procedures provide the caller with the status of the listfollowing each call. When adding an element to the list, the caller will receive notice ifthe list is already full. If the element is added to the list, the caller will be notified if thelist has just become full.

When removing an element from the list, the caller will receive notice if no element wason the list. If an element is retrieved from the list, the caller will be notified if the list hasjust gone empty.

AMX Circular List Manager KADAK 137

11.3 Circular List StructureCircular lists are application data structures which are only accessible by calls to theAMX Circular List Manager. The internal structure of the list is private to the CircularList Manager.

Lists can be created dynamically or statically by any application program.

The following examples illustrate 8-bit, 16-bit and 32-bit lists created in C. NSLOT isdefined to be the number of slots in each list.

typedef char SLOT1; /* 1 byte slot */typedef short int SLOT2; /* 2 byte slot */typedef long SLOT4; /* 4 byte slot */

#define NSLOT 64 /* 64 slots in the list */

struct { /* List of 1 byte slots */short int header[4];SLOT1 slots[NSLOT];} bytelist;

struct { /* List of 2 byte slots */short int header[4];SLOT2 slots[NSLOT];} shortlist;

struct { /* List of 4 byte slots */short int header[4];SLOT4 slots[NSLOT];} pntrlist;

Bytelist is a circular list of NSLOT 8-bit elements.Shortlist is a circular list of NSLOT 16-bit elements.Pntrlist is a circular list of NSLOT 32-bit elements.

138 KADAK AMX Circular List Manager

The same lists can be coded in assembly language as follows:

USER_DATA SEGMENT WORD 'DATA';; Circular Lists must be in program data;NSLOT EQU 64;

EVEN ;Force word alignmentBYTELIST LABEL WORD

DW 4 DUP(?) ;HeaderDB NSLOT DUP(?) ;Slots

;EVEN ;Force word alignment

WORDLIST LABEL WORDDW 4 DUP(?) ;HeaderDW NSLOT DUP(?) ;Slots

;EVEN ;Force word alignment

PNTRLIST LABEL WORDDW 4 DUP(?) ;HeaderDD NSLOT DUP(?) ;Slots

;USER_DATA ENDS

AMX Linked List Manager KADAK 139

12. AMX Linked List Manager

12.1 IntroductionThe Linked List Manager provides a general set of fast linked list services suitable foruse in real-time systems. The Linked List Manager removes the tedium and potential forserious error inherent in many applications in which list maintenance is implemented byeach programmer in unique and varying ways.

The Linked List Manager offers a feature not often found in similar utilities. Objectsmanipulated by the Linked List Manager can concurrently reside on more than one list.

The Linked List Manager also resolves list manipulation races which frequently occur inreal-time multitasking applications. The Linked List Manager assures that no listlinkages will be corrupted because of races between tasks, ISPs or Timer Proceduresattempting to manipulate the same list.

The Linked List Manager supports doubly linked lists in which all objects on a list arelinked in forward and backward directions.

The Linked List Manager also supports keyed lists in which the order of objects in the listis determined by an ordering key provided by the application.

The AMX Linked List Manager provides the following list manipulation procedures.The procedures are reentrant permitting them to be shared by concurrently executingtasks, ISPs and Timer Procedures.

ajlcre AALCRE Create an empty list

ajlinsh AALINSH Insert at the head of a listajlinst AALINST Insert at the tail of a listajlinsc AALINSC Insert before the specified object on list

ajlrmvh AALRMVH Remove from the head of a listajlrmvt AALRMVT Remove from the tail of a listajlrmvc AALRMVC Remove specified object from a list

ajlhead AALHEAD Find current head of a listajltail AALTAIL Find current tail of a listajlnext AALNEXT Find next object on a list (walk towards tail)ajlprev AALPREV Find previous object on a list (walk towards head)

ajlinsk AALINSK Insert into a keyed listajlordk AALORDK Reorder object in a keyed listajlmerg AALMERG Merge two lists

140 KADAK AMX Linked List Manager

12.2 Linked Lists

Terminology

A list header is a structure provided by the application to be used to anchor a list. Thelist header is used to identify a list. The content of the list header is private to the LinkedList Manager.

An object is an application data structure which represents the elements which reside ona list. For example, AMX maintains a list of Task Control Blocks (TCBs). Each TCB isan instance of a data structure representing the state of a task. Hence, the TCB qualifiesas an object.

A list node is a structure embedded in an object. The list node is used to link the objectinto a simple doubly linked list. The content of the list node is private to the Linked ListManager.

A key is a 16-bit unsigned integer which is used to determine the order of objects in akeyed list. Each object in a keyed list must have a key. Objects in a keyed list areordered such that key values are monotonically increasing from the head of the list to thetail of the list.

A key node is a structure embedded in an object. The key node is used to link the objectinto a keyed list. The object's key resides in the key node. The content of the key node isprivate to the Linked List Manager.

The head of a list is the first object on a list. The tail of a list is the last object on a list.An empty list has no head or tail. If only one object is on a list, it is both the head andtail of the list.

The node offset is the offset (i.e. displacement) into an object at which the list node (orkey node) resides. The node offset assigned for a particular list is fixed. Any objectwhich can reside on the list must have a list node (or key node) in the object at the nodeoffset assigned to that list.

AMX Linked List Manager KADAK 141

Figure 12.2-1 illustrates three doubly linked lists of apples and oranges. All apples andoranges reside on a fruit list. Fresh apples or oranges reside on a fresh list. Rotten applesor oranges reside on a rotten list.

The list objects are assumed to be data structures describing apples and oranges. Eachobject contains two list nodes: one for use with the fresh list or rotten list, the other foruse with the fruit list.

Note that a single list node can be used for the fresh and rotten lists since these lists aremutually exclusive. All fruit list nodes reside at the same node offset in apple or orangeobjects. All fresh and rotten list nodes reside at the same node offset in apple and orangeobjects. The Linked List Manager lets you mix objects of different types on the same listas long as each object has a link node in it at the correct node offset for the particular list.

FreshList Header

RottenList Header

FruitList Header

good good good bad badbad

Apple Apple AppleOrange Orange Orange

Figure 12.2-1 Doubly Linked Lists

142 KADAK AMX Linked List Manager

12.3 Linked List UseA list consists of a list header and objects linked to the list header by list nodes (or keynodes). Storage for the list header must be provided by you. A pointer to the list headeracts as the list identifier.

An empty list is created by calling procedure ajlcre with a pointer to the list headerstorage. When the list is created, you must specify the node offset (byte displacement) atwhich link nodes (key nodes) will be found in objects which can reside on the list.

Once a list has been created, any object which has a link node (or key node) at that list'snode offset can be added to the list.

Objects can be inserted at or removed from the head or tail of the list. You can alwaysfind the head or tail of the list. Given a pointer to any object on the list, you can find thenext or previous object, insert another object ahead of it or remove it from the list.

If the objects have a key node at the list's node offset, then the list is a keyed list. Allobjects on a keyed list must have key nodes at the list's node offset. A new object isadded to a keyed list according to the key provided in the call to ajlinsk. The objectwill be inserted into the list after all objects whose key is numerically less than or equalto the specified key. Thus keyed objects are added after all other objects with the same orlesser key.

The position of an object in a keyed list can be altered by calling ajlordk with a new keyfor the object. The list will be reordered moving the specified object to the correctposition in the list according to its new key value. Reordering is usually faster thanremoving the object with ajlrmvc and re-inserting with ajlinsk.

AMX Linked List Manager KADAK 143

The following example coded in C illustrates the use of the Linked List Manager. Anobject called uobject is defined with a key node at offset keynode in the object. Anarray of ten objects is provided. A keyed list keylist is created and the ten objects areadded to the list in random order. The list is then perused to locate the actual position inthe list of the sixth object in the array. The object is removed from the keyed list andadded to the tail of a simple doubly linked list called extlist.

#include "amx831sd.h" /* AMX Structure Definitions */

extern unsigned int random(); /* Random number generator */

struct uobject {int id; /* Object identifier */int data; /* Other application data */struct amxlks keynode; /* Key node */char moredata[10]; /* More application data */struct amxlns listnode; /* List node */int lastdata; /* Last application data */};

/* Local variables */

static struct amxlhs keylist; /* Keyed list header */static struct amxlhs extlist; /* Extraction list */

#define NUMOBJ 10 /* Ten objects */

/* Array of objects */static struct uobject objarray[NUMOBJ];

144 KADAK AMX Linked List Manager

void example(void){

int i;struct uobject *objp; /* Object pointer */int nodeofs; /* Node offset */

nodeofs = (char *)(&objarray[0].keynode) - (char *)&objarray[0];

ajlcre(&keylist, nodeofs); /* Create empty keyed list */

nodeofs = (char *)(&objarray[0].listnode) - (char *)&objarray[0];

ajlcre(&extlist, nodeofs); /* Create empty extraction list*/

objp = &objarray[0]; /* First object */

for (i = 1; i <= NUMOBJ; i++) {objp->id = i; /* Insert object id */

/* Add to list in random order */ajlinsk(&keylist, objp++, random());}

objp = ajlhead(&keylist); /* Find head of list */

while (objp != NULL) {if (objp->id == 6)

break; /* Found object of interest */

objp = ajlnext(&keylist, objp);}

if (objp != NULL) {ajlrmvc(&keylist, objp); /* Remove object from keylist */ajlinst(&extlist, objp); /* Add to extraction list */}

}

AMX Linked List Manager KADAK 145

The following example coded in assembler illustrates the use of the Linked List Manager.The example mimics the operation of the previous C implementation. It illustrates theoptimization effects which can be achieved by coding in assembler.

INCLUDE AMX831SD.DEF ;AMX Structure Definitions;UOBJECT STRUCID DW ? ;Object idDATA DD ? ;Other application dataKEYNODE DB (SIZE AMXLKS) DUP(?) ;Key nodeMOREDATA DB 10 DUP(?) ;More application dataLISTNODE DB (SIZE AMXLNS) DUP(?) ;List nodeLASTDATA DD ? ;Last application dataUOBJECT ENDS;OBJSIZ EQU SIZE UOBJECT ;Size of an objectNUMOBJ EQU 10 ;Ten objects;USER_DATA SEGMENT WORD 'DATA' ;Data segment;KEYLIST DB (SIZE AMXLHS) DUP(?) ;Keyed list headerEXTLIST DB (SIZE AMXLHS) DUP(?) ;Extraction list header;OBJARRAY DB (OBJSIZ*NUMOBJ) DUP(?) ;Array of objects;USER_DATA ENDS ;End of data segment;

PAGE

146 KADAK AMX Linked List Manager

USER_CODE SEGMENT BYTE 'CODE' ;Code segment;

ASSUME CS:USER_CODE, DS:USER_DATA, ES:USER_DATA;

EXTRN RANDOM:FAR ;Random number generator;EXAMPLE PROC FAR

MOV AX,SEG USER_DATAMOV DS,AX ;Assure data accessMOV ES,AX

;MOV CX,KEYNODE-(BYTE PTR ID) ;Offset to key nodeMOV SI,OFFSET KEYLIST ;A(Keyed list)CALL AALCRE ;Create keyed list

;MOV CX,LISTNODE-(BYTE PTR ID) ;Offset to list nodeMOV SI,OFFSET EXTLIST ;A(Extraction list)CALL AALCRE ;Create extraction list

;MOV SI,OFFSET KEYLIST ;A(keyed list)MOV BX,OFFSET OBJARRAY ;A(first object)MOV DI,1 ;i = 1

;EXLP1: MOV [BX].ID,DI ;Install object id

CALL RANDOM ;AX = random numberMOV CX,AX ;CX = key

; ;ES:BX = A(object)CALL AALINSK ;Insert in random orderADD BX,OBJSIZ ;Next objectINC DI ;i++CMP DI,NUMOBJJLE EXLP1 ;More to goCALL AALHEAD ;ES:BX = head of list

EXLP2: MOV AX,ESOR AX,BXJZ EXEND ;End of keyed list

CMP ES:[BX].ID,6JE EXFND ;Found object of interestCALL AALNEXT ;ES:BX = next objectJMP SHORT EXLP2

;EXFND: CALL AALRMVC ;Remove object from list

MOV SI,OFFSET EXTLIST ;A(Extraction list)CALL AALINST ;Add to tail of list

EXEND: RET;EXAMPLE ENDP;USER_CODE ENDS ;End of code segment

Advanced Topics KADAK 147

13. Advanced Topics

13.1 Fatal ExitThere are a number of conditions which, if encountered by AMX, are considered to befatal. Any attempt by AMX to continue execution will lead to unpredictable results atbest. All of these conditions cause AMX to force a branch to its fatal exit handler atajfatl.

Insufficient Memory

The most common of these conditions occurs at startup. Many of the AMX managersinclude a Restart Procedure which is executed by AMX during its startup phase. Some ofthese managers must initialize a portion of the AMX Data Segment which is private totheir needs. If any of these managers find that their needs exceed the size of the datasegment provided in your AMX System Configuration Module, AMX takes its fatal exit.To proceed would imply using memory which does not belong to AMX.

Task Error Traps

AMX will take its fatal exit if a processor dependent task trap exception such as divisionby zero, arithmetic overflow or an array bound error occurs in any Restart Procedure,Interrupt Service Procedure or Timer Procedure.

If any of these errors occur in a task which does not have a task trap handler (see Chapter4.5) for the corresponding error, AMX will take its fatal exit.

AMX and its managers avoid instructions which produce arithmetic overflow or arraybound error exceptions. In the rare occasions when AMX or its managers use division,the division is guaranteed not to produce a divide fault.

Invalid Shutdown

If you started AMX requesting permanent execution (see Chapter 2.4) and then attempt toshut down your AMX system by calling ajexit, AMX will take its fatal exit path.

AMX Breakpoint Manager

If you include the AMX Breakpoint Manager in your system, it will attempt to install itshandlers for the debug exception, breakpoint exception and possibly the NMI interruptexception. If it is unable to install its handlers, the AMX Breakpoint Manager will forcea fatal exit.

Application Faults

If your application encounters conditions which are deemed fatal, you can take the AMXfatal exit by calling procedure ajfatl or AAFATL. You can define your own negativefatal error codes to identify your fatal error conditions.

148 KADAK Advanced Topics

Fatal Exit Procedure

AMX allows you to provide a Fatal Exit Procedure of your own by specifying the nameof your procedure in your System Configuration Module (see Chapter 14.5).

Whenever AMX or your application forces a fatal exit, AMX checks to see if you haveprovided a Fatal Exit Procedure. If one is present, AMX calls the procedure.

If no Fatal Exit Procedure exists or if the procedure returns to AMX, AMX will disablethe external interrupt system and halt. Only a hardware reset can be used to recover.

The Fatal Exit Procedure must not make any use of AMX or any of its managers.

In general, there is little that the Fatal Exit Procedure can do. It certainly cannot rectifythe situation. Any processing that it does should be done with the interrupts disabled ifpossible. If not, all interrupt sources should be reset or otherwise inhibited if hardwarepermits. Once all interrupt sources have been eliminated, the external interrupt systemcan be enabled. Only then is it acceptable to try restarting your AMX system.

Your Fatal Exit Procedure can be coded in assembly language as a FAR procedure. Uponentry to your Fatal Exit Procedure, the following conditions exist:

Interrupts are disabled.All registers are free for use.AX Fatal error code (see AERFXn definitions)DS,ES DGROUP segmentSS:SP Stack in effect at the time of the fatal exitThe direction flag is set to forward.

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;

PUBLIC FATALEX;FATALEX PROC FAR

:Interpret fatal exit code in AX:RET ;AMX will halt at AMHALT

;FATALEX ENDP;USER_CODE ENDS

Advanced Topics KADAK 149

Your Fatal Exit Procedure can be coded as a Large model C procedure as illustrated inthe following example.

#include "amx831ec.h" /* AMX Error Code Definitions */

void cdecl fatalexit(int error) /* Fatal exit error code */{

:Inhibit all interrupt sourcesProvide an external indication of the fatal condition:}

Halt Locations

If AMX takes its fatal exit and you have not provided a Fatal Exit Procedure (or if yourprocedure returns to AMX), AMX will disable interrupts and halt at entry point AMHALT.

Entry point AMHALT, although private to AMX, is made PUBLIC to assist you in yoursystem development and testing. This one entry point is the only location within AMXwhere a programmed halt can occur.

150 KADAK Advanced Topics

13.2 User Error ProcedureMost AMX procedures return error status to the caller. The error status is a signedinteger.

AEREROK = 0 No errorAERxxx > 0 Warning: possible faultAERxxx < 0 Error: may be unrecoverable

The defined error codes are summarized in Appendix B.

AMX allows you to provide a User Error Procedure to trap all errors generated by calls toAMX functions. You do so by specifying the name of your procedure in your SystemConfiguration Module (see Chapter 14.5).

Before returning an error or warning condition to the caller, AMX calls your User ErrorProcedure, if one has been provided. The User Error Procedure receives the AMX errorcode and the task id of the task executing at the time of the error. The task id will be 0 ifthe error occurred in an ISP call to AMX.

Upon entry to your User Error Procedure, interrupts are disabled to prohibit deviceinterrupt, clock ISP and higher priority task activity until you have had an opportunity toexamine the error condition. Your procedure should not enable interrupts without firstdisabling or resetting all interrupt sources. In all but the simplest of systems this may beimpossible to do.

The User Error Procedure executes in the context of the task, ISP, Timer Procedure,Restart Procedure or Exit Procedure which made the errant AMX call. The User ErrorProcedure can only make AMX calls which an ISP is allowed to make.

In general, there is little that the User Error Procedure can do. It can, however, beextremely useful for locating faults in your application during initial testing. It is alsouseful for locating infrequently occurring error conditions which are not being checkedby your code and hence are going undetected in an otherwise working system.

Your User Error Procedure can be coded as a Large model C procedure with formalparameters as illustrated in the following example.

#include "amx831cf.h" /* AMX C Interface Header */

void cdecl userror(int error, /* AMX error code AERxxxx */AMXID taskid) /* Task id of current task */

/* (0 if error occurred in ISP) */{

:Interpret the error codeInterpret the task id:}

Advanced Topics KADAK 151

Your User Error Procedure can be coded in assembly language as a FAR procedure. Uponentry to your User Error Procedure, the following conditions exist:

Interrupts are disabled.All registers are free for use.AX AMX error code (see AERxxx definitions)DX Task id of current task (0 if error detected in ISP)DS,ES GROUP segmentSS:SP Stack in effect at the time of the errorThe direction flag is set to forward.

USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;

PUBLIC USERROR;USERROR PROC FAR

:Interpret error code in AXInterpret task id in DX:RET ;Resume

;USERROR ENDP;USER_CODE ENDS

Note

Warnings and timeouts are NOT trapped to your User ErrorProcedure. Appendix B identifies all AERxxxx codes whichare not trapped.

152 KADAK Advanced Topics

13.3 Task Scheduling HooksAMX does not provide direct support for specific hardware extensions such as a mathcoprocessor or a memory management unit. Instead, AMX allows a set of applicationprocedures to be connected to its Task Scheduler. These procedures can save and restorehardware dependent parameters specific to your application whenever a task switchoccurs.

There are four critical points within the AMX Task Scheduler. These critical pointsoccur when:

a task is starteda task endsa task is suspendeda task is allowed to resume.

AMX allows a unique application procedure to be provided for each of these criticalpoints. Pointers to your procedures are installed with a call to procedure ajhook. Youmust provide a separate procedure for each of the four critical points. Since theseprocedures execute as part of the AMX Task Scheduler, their operation is critical. Theseprocedures must be coded in assembler using techniques designed to assure that theyexecute as fast as possible.

The AMX Task Scheduler calls each of your procedures with the same callingconventions.. Your procedures must be coded as FAR procedures.

Upon entry to your scheduling procedures, the following conditions exist:

Interrupts are disabled and must remain so.DS:SI A(Task Control Block)SS:SP Task stack free for useAX,BX,CX,DX,ES Free for useAll other registers must be preserved.

Register pair DS:SI gives you a pointer to the Task Control Block of the task which isbeing started, ended, suspended or resumed. Your procedures are free to use the task'sstack. However, you must not attempt to use this stack to save information. For instance,popping the return address, pushing parameters onto the stack and then returning to AMXis not allowed.

If you have to save information as part of the task's state, you should use the storage inthe Task Control Block reserved for the private use of your application (see Chapter3.12). If necessary, provide an extension to your Task Control Block and install a pointerto the extension in the portion of the Task Control Block reserved for your use.

Once your procedures are installed, you will observe a degradation in the AMX taskswitching performance. Each call to your procedure will add the setup and callingoverhead plus the time it takes your procedure to execute.

Advanced Topics KADAK 153

13.4 Abnormal Task TerminationA task is a procedure which is called by the AMX Task Scheduler. The task endsexecution normally by returning to AMX. AMX provides procedure ajend which can beused by a task to end execution and return to AMX under circumstances in which itsstack is deeply nested.

These two methods by which a task may end execution are considered normaltermination. A task has to be running to end in this fashion. No other task can force atask, other than itself, to end.

AMX also provides a set of services which permit one task to force the abnormaltermination of another task. These services are not to be treated lightly. Theirdescription has been deferred to this chapter to indicate that they should be rarelyinvoked.

It is assumed that you have read Chapter 3 of this manual and are familiar with the AMXTask State Diagram presented in Figure 3.2-1.

The ability to arbitrarily terminate a task is one of the most abused privileges afforded bysome multitasking systems. The AMX philosophy is to encourage well structured taskdesigns in which there is rarely the need for an uncontrolled task termination. In manycases, a modification to your system design can eliminate the apparent need to arbitrarilyterminate a task. However, occasionally system design does demand that an erring taskbe eliminated for the good of all others. The availability of a controlled task terminationcan greatly enhance your options in this case.

AMX offers the following task termination services:

ajtkstp AATKSTP Force a task to stopajtkill AATKILL Kill a task by forcing it to stop; flush its message mailboxesajtkdel AATKDEL Delete a taskajtktrm AATKTRM Enable/disable abnormal task termination

The AMX termination services will not be included in your AMX system if your tasks donot call any of these procedures.

Stop a Task

A task can be stopped. The effect is the same as if the task had just issued a call to ajendto end its own operation. Only a task which is running, waiting or ready to execute canbe stopped. A task can stop itself.

A task that has been stopped does not cease to exist. It simply ends operation. If it hasoutstanding trigger requests for execution, the task will be allowed to run again.

You must not stop any task which is waiting for a semaphore, an event group or amessage exchange.

154 KADAK Advanced Topics

Kill a Task

A task can be killed. The task is first stopped as just described. All outstanding requeststo the task for its execution are purged. The effect is the same as if the task continued tomake calls to ajend to end its operation until finally there were no task executionrequests remaining. A task can kill itself.

A task that has been killed does not cease to exist. Any new requests to trigger the taskor to send messages to it will be honored.

You must not kill any task which is waiting for a semaphore, an event group or a messageexchange.

Delete a Task

A task can be deleted. A task which is deleted ceases to exist. Its task id becomesinvalid and may be assigned by AMX to some other newly created task. A task candelete itself.

You must not delete any task which is waiting for a semaphore, an event group or amessage exchange.

Task Termination Procedure

To safeguard against abuses of its task termination services, AMX inhibits any task frombeing stopped, killed or deleted until the task itself indicates its willingness to beabnormally terminated. A task does this by calling procedure ajtktrm to inform AMXthat it is prepared to be abnormally terminated.

When a task calls ajtktrm to allow its abnormal termination, it gives AMX a pointer to aTask Termination Procedure to be called by AMX whenever the task is stopped, killed ordeleted. A task can subsequently inhibit its own abnormal termination by callingajtktrm with a NULL procedure pointer.

Once a task enables abnormal termination, it remains enabled even if the task endsnormally. The next time the task executes, it will still be able to be abnormallyterminated. The previously defined Task Termination Procedure remains in effect until itis cancelled by calling ajtktrm to install a NULL pointer.

If a task is stopped or killed, AMX resets its Task Termination Procedure pointer to NULLthereby inhibiting any further requests to stop or kill the task until the task has had achance to execute again and specify a new Task Termination Procedure.

Advanced Topics KADAK 155

A Task Termination Procedure can be coded as a Large or Medium model C procedure asillustrated in the following example. The procedure receives an integer reason codeindicating whether the task is being stopped, killed or deleted. The mnemonics for thesereason codes are provided in the AMX header file AMX831SD.H.

Upon entry to the Task Termination Procedure, the following conditions exist:

Interrupts are enabled.All registers are free for use.A reason code is provided as a parameter.(see ajtktrm description in Chapter 16)The task's stack in effect at the time of the termination request is in use.

The Task Termination Procedure must return to AMX. It must not call procedure ajendto end task execution.

#include "amx831sd.h" /* AMX Definitions */

void cdecl termproc( /* Task Termination Procedure */int reason) /* Termination reason */{

switch(reason) {

case AMCFE::Stop task is occurring:break;

case AMCFK::Kill task is occurring:break;

case AMCFD::Delete task is occurring:break;

} /* end of switch */}

156 KADAK Advanced Topics

A Task Termination Procedure can be coded in assembler as a FAR procedure as indicatedin the following example. The procedure receives an integer reason code indicatingwhether the task is being stopped, killed or deleted. The mnemonics for these reasoncodes are provided in the AMX header file AMX831SD.DEF.

Upon entry to the procedure, the following conditions exist:

Interrupts are enabled.All registers are free for use.AX Reason code indicating stop, kill or delete task (AMCFx)DS,ES DGROUP segmentSS:SP Task stack in effect at the time of the termination requestThe direction flag is set to forward.

INCLUDE AMX831SD.DEF ;AMX Definitions;;USER_CODE SEGMENT BYTE 'CODE';

ASSUME CS:USER_CODE;TERMPROC PROC FAR ;Task Termination Procedure

:AX = AMCFE if stop task is occurringAX = AMCFK if kill task is occurringAX = AMCFD if delete task is occurring:RET

;TERMPROC ENDP;USER_CODE ENDS

Advanced Topics KADAK 157

Termination Processing

AMX will only stop or kill a task which is running, waiting or ready to execute. A taskcan be deleted if it is in any of these states or idle. Occasionally, a request to terminate atask will occur while that task is performing some operation which AMX deems to becritical. When this occurs, AMX allows the task to complete the critical operation andthen forces the abnormal termination. AMX does this so that none of its privateresources, such as message envelopes, are corrupted or lost.

When a task is stopped or killed, AMX ensures that a task waiting for its message to beprocessed by the task being terminated, resumes and is not left blocked forever.

When a task is killed, AMX flushes each of the task's mailboxes. When doing so, AMXexamines the message. If the message indicates that a task is waiting for the message tobe processed, AMX allows the task to resume.

Deleting a task is a complex operation. AMX must make certain that the task is notdeleted until all currently active transactions involving that task have been completed.For example, high priority Task A may be deleting medium priority Task B just as lowpriority Task C was interrupted in its attempt to trigger Task B. The task trigger must beallowed to complete in order that AMX task status not be compromised.

AMX meets these stringent requirements by requiring that you specify the priority atwhich a task is to be deleted. The task deletion priority must be below that of all othertasks with which it interacts but above any compute bound tasks which you may have.AMX drops the task to its deletion priority which forces all other tasks with which thetask can interact to complete any outstanding operations before the deletion takes place.AMX then deletes the task.

Once a request to delete a task has been made, no new transactions involving the deletedtask can occur. Any attempt to reference a task which has been marked for deletion willproduce an AERNST error indication since the deleted task no longer exists as far as youare concerned. The actual task deletion may be delayed by AMX until currenttransactions involving the task can be completed.

Termination Warning

When AMX stops, kills or deletes a task, it does not release any of the system resourceswhich that task may have within its control. Any interval timers, semaphores, eventgroups, message exchanges, buffers or memory blocks which the task has reserved mustbe released by the task's Task Termination Procedure when it is called by AMX.

158 KADAK Advanced Topics

13.5 Task Suspend/ResumeSome operating systems permit a task to suspend any task, including itself. This featureis then used to implement the equivalent of the AMX task wait procedure ajwait.

The ability to arbitrarily suspend a task is one of the most abused privileges afforded byother operating systems. The AMX philosophy is to encourage well structured taskdesigns using the wide range of task synchronization facilities offered by AMX in whichthere is rarely the need for an uncontrolled task suspension. In most cases, a modificationto your system design can eliminate the apparent need to arbitrarily suspend a task.

To facilitate porting system designs from other operating systems to AMX, theprocedures ajsusp and ajresum are provided.

Any Restart Procedure, task, Timer Procedure or Exit Procedure can suspend any task inthe system except the AMX Kernel Task. ISPs cannot suspend tasks. The task remainssuspended until some task, ISP or Timer Procedure calls ajresum to force resumption ofthat task.

If a task is blocked (waiting for a task trigger or AMX message or in any AMX waitstate) at the time it is suspended, the task will remain blocked (suspended) until anajresum call attempts to let the task resume. If, while the task was suspended, theblocking conditions were removed, the task will resume (start) at the point at which itwas blocked.

Note

Do not use ajsusp and ajresum for synchronization.

For task synchronization, see Chapter 3.6.For ISP synchronization, see Chapter 4.4.

Advanced Topics KADAK 159

13.6 Breakpoint ManagerThe AMX Breakpoint Manager can be used to improve the operation of the debugger thatyou use to test your AMX system. Your use of the Breakpoint Manager is optional; use itonly if it augments your debugger as described below.

If you enjoy the use of an in-circuit emulator or hardware assisted debugger, you will notneed to use the Breakpoint Manager. When breakpoints are encountered, operation of thetarget processor is suspended and you get a true snapshot of life in your AMX system atthe time of the breakpoint. Since the processor operation is suspended, no furtherprocessing by the system under test is possible.

If you are using a resident debugger such as Microsoft CodeView or Borland TurboDebugger operating on PC AT compatible hardware, then you should use the BreakpointManager to assist the debugger. Debuggers like these use software breakpoints and tracetraps to provide their services. In the debugger's attempt to remain reasonably passivewith respect to the underlying hardware, it leaves itself wide open to difficulties in testinginterrupt driven pre-emptive multitasking applications.

When a breakpoint is encountered, the debugger may not inhibit clock interrupts becauseit prefers not to be so intrusive. The implication is that all clock activity continues tooccur while you are stopped at a breakpoint. Consequently, in your AMX system, anytask of higher priority than the one in which the breakpoint occurred may preempt thedebugger and start (or resume) execution. This same effect will be noticed for allinterrupt driven activity involving higher priority tasks.

The Breakpoint Manager resolves this problem. When a breakpoint or debug exceptionoccurs, the Breakpoint Manager halts all AMX tasks and inhibits AMX clock servicewhile you are in the debugger.

Unfortunately, the Breakpoint Manager has no easy means of determining when you haveproceeded from a breakpoint. It monitors task switches and clock interrupts to detect anexit from the debugger. Once the exit has been detected, it removes all AMX tasks fromthe halt state and restores AMX clock service.

160 KADAK Advanced Topics

Using the Breakpoint Manager

The Breakpoint Manager is included in your application only if it is enabled in your UserParameter File. Use the AMX Configuration Builder to edit your User Parameter File(see Chapter 14.13). Enable the breakpoint support option in the Breakpoint parameterwindow and generate a new System Configuration Module. Then assemble the moduleand link your AMX system as described in the AMX 86 Tool Guide.

When you are finished testing your AMX system, you can remove the BreakpointManager. The simplest method is to relink your AMX system including object moduleAA831BKE.OBJ in your link specification prior to the AMX Library AMX831.LIB. Thisobject module contains procedure stubs which satisfy the link requirements withoutforcing the Breakpoint Manager to be loaded from the library.

Alternatively, you can alter your System Configuration Module to exclude breakpointsupport. Use the AMX Configuration Builder to edit your User Parameter File. Disablethe breakpoint support option in the Breakpoint parameter window and generate a newSystem Configuration Module. Then assemble the module and relink your AMX system.

Breakpoint Exit Detection

The Breakpoint Manager monitors the breakpointed task's state to detect when an exitfrom the debugger has occurred. Whenever the task ends, waits or attempts to readysome other task, the Breakpoint Manager concludes that you have left the debugger andallows your AMX system to resume execution.

If your debugger inhibits clock interrupts at breakpoints, you can improve the BreakpointManager's exit detection as follows. Use the AMX Configuration Builder to edit yourUser Parameter File. Set the breakpoint entry delay to -1 and the breakpoint exit delay to1 in the Breakpoint parameter window. Generate a new System Configuration Module,assemble the module and relink your system. The Breakpoint Manager will assume thatyou have left the breakpoint as soon as the next AMX clock tick is detected.

Advanced Topics KADAK 161

Interrupt Masking

The Breakpoint Manager must be tailored to inhibit interrupts at breakpoints. Whichinterrupts are to be inhibited and how this is done is both system and hardwaredependent.

When you include the Breakpoint Manager in your AMX system, module AA831BKA.OBJis included from the AMX Library. This module contains procedure AMBKOF to inhibitselective interrupts at a breakpoint and procedure AMBKON to restore these interrupts uponresumption from the breakpoint.

Module AA831BKA.OBJ supports the use of AMX on PC/AT compatible hardware inwhich two Intel 8259 interrupt controllers are used to mask interrupts.

The 8259 interrupt disable masks AMBKM1 and AMBKM2 identify the interrupt request lines(IRQs) which will be inhibited at breakpoints. Bits 0 to 7 of mask AMBKM1, if set to 1,inhibit interrupts on IRQ0 to IRQ7 respectively. Bits 0 to 7 of mask AMBKM2, if set to 1,inhibit interrupts on IRQ8 to IRQ15 respectively on the slave 8259. By default, maskAMBKM1 is set to 0FCH and mask AMBKM2 is set to 0FFH to inhibit all interrupts except theclock on IRQ0 and the keyboard on IRQ1.

You must leave the keyboard interrupt enabled (AMBKM1 mask bit 1 = 0) to permit PCdebuggers to use the keyboard. You must leave the clock interrupt enabled (AMBKM1mask bit = 0) to permit proper resumption from breakpoints. You may wish to leave theinterrupt enabled for the diskette (AMBKM1 mask bit 6 = 0) or the hard disk (AMBKM2 maskbit 6 = 0) to allow the debugger to access disk files.

If you are testing an AMX system on custom hardware, you may have to edit proceduresAMBKOF and AMBKON in module AA831BKA.ASM to meet the needs of your hardware.Assemble the module and rebuild the AMX 86 Library to include your version of thismodule. Follow the instructions provided in Appendix A of the AMX 86 Tool Guide.

162 KADAK Advanced Topics

NMI Breakpoints

Some hardware debuggers may use the non-maskable interrupt (NMI) to generatebreakpoints. The Breakpoint Manager can be tailored to support such debuggers byenabling its NMI handler.

When an NMI interrupt is detected, the Breakpoint Manager calls the NMI handler todetermine if the interrupt is actually a breakpoint. In some 8086 PC configurations, theNMI interrupt is multiplexed to detect memory parity errors and to service a numericcoprocessor such as the Intel 8087, 80287 or 80387.

The NMI handler must determine the actual source of the NMI interrupt. If the handlerdetermines that the interrupt is a breakpoint, the Breakpoint Manager halts all AMX taskactivity and then passes control to your NMI debugger.

If the NMI handler determines that the interrupt is not a breakpoint, the BreakpointManager allows your AMX system to continue execution and passes control on to thereal NMI Interrupt Service Procedure.

The version of module AA831BKA.OBJ which is delivered with AMX assumes that theNMI interrupt is not used for debugging. If you are using the NMI interrupt for thispurpose, you will have to edit file AA831BKA.ASM to enable NMI handling. The filecontains a simple NMI handler suitable for use on PC/AT compatible hardware. If youintend to use an NMI debugger, you will have to edit flag AMBKNM in the file to be nonzero. The file contains instructions defining how the editing should be done. Assemblethe module and rebuild the AMX 86 Library to include your version of this module.Follow the instructions provided in Appendix A of the AMX 86 Tool Guide.

Compatible Debuggers

The Breakpoint Manager will operate with any debugger which exhibits the followingcharacteristics.

The debugger must use breakpoint software interrupt (INT 3) or the NMI hardwareinterrupt (INT 2) to set breakpoints.

When a breakpoint is encountered, the debugger must switch to its own private internalstack which is different from all AMX task stacks.

The debugger must leave the interrupt controller (or equivalent) interrupt enable maskunaltered when it proceeds from a breakpoint.

AMX System Configuration KADAK 163

14. AMX System Configuration

14.1 System Configuration ModuleThe AMX System Configuration Module defines the characteristics of your AMXsystem. The AMX Configuration Builder, described in Chapter 14.2, will create thismodule for you.

The System Configuration Module includes the following components.

The User Parameter Table provides AMX with the following information pertinent tothe system you are creating.

Maximum number of tasks Number of message envelopesMaximum number of timers Message sizeMaximum number of semaphores Kernel and Interrupt Stack sizesMaximum number of event groups Clock frequencyMaximum number of message exchanges Time/Date Scheduling ProcedureMaximum number of buffer pools Memory Assignment Procedure

User Error ProcedureFatal Error Procedure

The Restart Procedure List defines all of your Restart Procedures and their order ofexecution. The Exit Procedure List defines all of your Exit Procedures and their orderof execution.

If you wish, you can predefine one or more of any of the following components of yoursystem. The object definition and memory storage, if any, required by AMX for thecomponent are provided in the System Configuration Module.

Tasks (including tasks with mailboxes)TimersSemaphores (resource or counting)Event groupsMessage exchangesBuffer pools

If you predefine any of these components, AMX will automatically create them whenyour system starts. The id assigned to each of the predefined components will be storedin unique id variables which are in the System Configuration Module.

If you predefine any tasks, the task stacks for these tasks will be in the SystemConfiguration Module.

If you predefine any buffer pools, the buffers for these buffer pools will be in the SystemConfiguration Module.

164 KADAK AMX System Configuration

14.2 System Configuration BuilderThe AMX Configuration Builder is a software generation tool which can be used tocreate your AMX System Configuration Module. The Builder helps to reduce totalsystem implementation time by eliminating the manual generation process by which yourSystem Configuration Module would otherwise have to be produced. The Builderconsists of two components: the Configuration Manager and the ConfigurationGenerator. The Configuration Manager is an interactive utility which allows you todefine and edit all of the parameters which must be included in your SystemConfiguration Module to use AMX and its Managers.

The configuration process is illustrated in the block diagram of Figure 14.2-1.

The Configuration Manager lets you define your system to meet your needs. It producesa text file called a User Parameter File. This file contains a cryptic representation of yourdescription of your system.

The Configuration Manager is also able to read a User Parameter File allowing you to usethe Configuration Manager to edit the content of a previously defined system description.

For convenience, the Configuration Manager has the ability to directly invoke its owncopy of the Configuration Generator. The Configuration Generator reads your UserParameter File and uses the information in it to produce a source file called the SystemConfiguration Module and a text file called the System Documentation Module.

The Configuration Generator uses a file called the System Configuration Template as amodel for your System Configuration Module. This template file is merged with theinformation in your User Parameter File to produce your System Configuration Module.

The Configuration Generator also merges a file called the System DocumentationTemplate with the information in your User Parameter File to produce your SystemDocumentation Module, a text file summarizing the characteristics of your AMXconfiguration.

The assembly language System Configuration Module must be assembled as described inthe toolset specific chapter of the AMX Tool Guide for inclusion in your AMX system.

If you are not using one of the toolsets supported by KADAK, you may still be able touse the AMX Configuration Builder by altering the System Configuration Template Fileas described in Appendix C.

The Configuration Generator is also available as a separate, stand alone DOS utility.This utility program can be used within your make files to generate and then compileyour System Configuration Module. Instructions for doing so are provided in the AMXTool Guide.

If you are not doing your development on a PC or compatible, you may still be able toport the Configuration Generator to your development system as described inAppendix C.

AMX System Configuration KADAK rev8 165

System DocumentationTemplate FileAM831CG.CTD

System ConfigurationTemplate FileAM831CG.CT

User Parameter FileSYSCFG.UP

ConfigurationManager

Enter/Edit/ViewAMX System Parameters

ConfigurationGenerator

SYSCFG.ASMSYSCFG.TXT

SystemConfigurationModuleFile

Figure 14.2-1 AMX Configuration Building Process

166 KADAK AMX System Configuration

14.3 Using the Builder

Starting the Builder

The AMX Configuration Builder will operate on a PC or compatible running theMicrosoft® Windows® operating system.

The Builder is delivered with the following files.

File Purpose

AM831CM .EXE AMX Configuration Manager (utility program)AM831CM .CNT AMX Configuration Manager Help Content FileAM831CM .HLP AMX Configuration Manager Help FileAM831CG .EXE AMX Configuration Generator (utility program)AM831CG .CT System Configuration Template FileAM831CG .CTD System Documentation Template File

When AMX is installed on your hard disk, the AMX Configuration Manager forWindows utility program and its related files are stored in directory CFGBLDW in yourAMX installation directory. To start the Configuration Manager, double click on itsfilename, AM831CM.EXE. Alternatively, you can create a Windows shortcut to themanager's filename and then simply double click the shortcut's icon.

To create a new User Parameter File, select New User Parameter File from the File menu.The Configuration Manager will create a new, as yet unnamed, file using its defaultAMX configuration parameters. When you have finished defining or editing your systemconfiguration, select Save As... from the File menu. The Configuration Manager will saveyour User Parameter File in the location which you identify using the filename which youprovide.

To open an existing User Parameter File, say SYSCFG.UP, select Open... from the Filemenu and enter the file's name and location or browse to find the file. When you havefinished defining or editing your system configuration, select Save from the File menu.The Configuration Manager will rename your original User Parameter File to beSYSCFG.BAK and create an updated version of the file called SYSCFG.UP.

To direct the Configuration Manager to use its Configuration Generator utility to producean updated copy of your System Configuration Module, say SYSCFG.C, select Generate...from the File menu.

The Configuration Manager can also be directed to use its Configuration Generator utilityto produce a System Documentation Module, say SYSCFG.TXT, a text file summarizingthe characteristics of your AMX configuration. Select Document... from the File menu.

AMX System Configuration KADAK 167

Screen Layout

Figure 14.3-1 illustrates the Configuration Manager's screen layout. The title baridentifies the User Parameter File being created or edited. Below the title bar is the menubar from which the operations you wish the Manager to perform can be selected. Belowthe menu bar is an optional Toolbar with buttons for many of the most frequently usedmenu commands.

At the bottom of the screen is the status bar. As you select menu items, a briefdescription of their purpose is displayed in the status bar. If the Configuration Managerencounters an error condition, it presents an error message on the status bar describingthe problem and, in many cases, the recommended solution.

Along the left margin of the screen are a set of one or more selector icons. These iconsidentify the type of output files which the Manager's Configuration Generator willproduce. The System Configuration Module selector must be active to generate theSystem Configuration Module and its related documentation file.

The center of the screen is used as an interactive viewing window through which you canview and modify your system configuration parameters.

Figure 14.3-1 Configuration Manager Screen Layout

168 rev9 KADAK AMX System Configuration

Menus

All commands to the Configuration Manager are available as items on the menus presenton the menu bar. The File menu provides the conventional New, Open, Save andSave As... commands for creating and editing your User Parameter File. It also providesthe Exit command.

When the System Configuration Module selector icon is the currently active selector, theGenerate... command on the File menu can be used to generate your System ConfigurationModule and the File, Document... command can be used to generate your SystemDocumentation Module. The paths to the template files required by the generator tocreate these products can be defined using the Templates... command on the File menu.

The Edit menu provides the conventional Cut, Copy, Paste and Undo editing commands.It also includes an Undo Page command to restore the content of all fields on a propertypage to undo a series of unwanted edits to the page. The Toolbar is hidden or madevisible using the View Toolbar command on the Edit menu.

The Help menu provides access to the complete AMX Configuration Manager referencemanual. Context sensitive help is also available by pressing the F1 function key orclicking the ? button on the Toolbar.

Field Editing

When the System Configuration Module selector icon is the currently active selector, theSystem Configuration Module's tabbed property sheet is displayed in the central region ofthe screen. Each tab provides access to a particular property page through which yoursystem configuration parameters can be declared. For instance, if you select the Taskstab, the Configuration Manager will present a task definition window (property page)containing all of the parameters you must provide to completely define a task.

Some fields are boolean options in which all you can do is turn the option on or off bychecking or unchecking the associated check box.

Some fields are option fields in which you must select one of a set of options identifiedwith radio buttons. Click on the option button which meets your preference.

Other fields may require numeric or text entry. Parameters are entered or edited in thesefields by typing new values or text to replace the current field content. Only displayablecharacters can be entered. New characters which you enter are inserted at the currentcursor position in the field. Right and left arrow, backspace and delete keys may be usedto edit the field.

When you are altering a numeric or text field, you tell the Configuration Manager thatyou are finished editing the field by striking the Enter key. At that point, theConfiguration Manager checks the numeric value or text string that you have entered forcorrectness in the context of the current field. If the value or text string that you haveentered is invalid, an error indication is provided on the status bar at the bottom of thescreen suggesting how the fault should be corrected.

The Tab and Shift-Tab keys can also be used to complete the editing of a field and move tothe next or previous field.

AMX System Configuration KADAK 169

If you have modified some of the fields on a property page and then decide that thesemodified values are not correct, use the Undo Page command on the Edit menu or Toolbarto force the Configuration Manager to restore the content of all fields on the page to thevalues which were in effect when you moved to that property page.

When you go to save your User Parameter File or prepare to move to another propertypage, the Configuration Manager will validate all parameters on the page which you areleaving. If any parameters are incomplete or inconsistent with each other, you will beforced to fix the problem before being allowed to proceed.

Add, Edit and Delete AMX Objects

Separate property pages are provided to allow your definition of one or more AMXobjects such as tasks and timers which will be prebuilt by AMX when AMX is launched.The maximum allowed quantities of each type of AMX object are defined by you on theObjects property page.

Pages of this type include a list box at the left side of the property page in which thecurrently defined objects are listed. At the bottom of the list box is a counter showing thenumber of objects in the list and the allowable maximum number of objects as defined onthe Objects property page.

Also below the list are two control buttons labeled Add and Delete. If the allowablemaximum number of objects is 0 or if all such objects have already been defined, the Addbutton will be disabled. If there are no objects defined, the Delete button and all otherfields on the page will be disabled.

To add a new object, click on the Add button. A new object named ---- will appear atthe bottom of the list and will be opened ready for editing. When you enter a valid tagfor the object, the tag will replace the name ---- in the object list.

To edit an existing object's definition, double click on the object's name in the object list.The current values of all of that object's parameters will appear in the property page andthe object will be opened ready for editing.

To delete an existing object, click on the object's name in the object list. Then click onthe Delete button. Be careful because you cannot undo an object deletion.

The objects in the object list can be rearranged by dragging an object's name to thedesired position in the list. You cannot drag an object directly to the end of the list. Todo so, first drag the object to precede the last object on the list. Then drag the last objecton the list to precede its predecessor on the list.

Tasks are ordered in their object list by task priority. The highest priority task resides atthe top of the list. Tasks cannot be rearranged in their list by dragging the object. To doso, change the task's priority.

170 KADAK AMX System Configuration

14.4 System Parameter DefinitionThe System Parameter window allows you to define the general operating parameters ofyour AMX system. The layout of the window is shown in Figure 14.3-1 in Chapter 14.3.

Kernel Options

AMX Message Envelopes

AMX passes a message to a mailbox or message exchange in a message envelope. Theapplication parameters which form the message are copied into the envelope and added tothe task mailbox or message exchange.

The number of message envelopes required by your application must be defined. Theupper limit of the maximum number of envelopes is established by the fact that allmessage envelopes must reside in one segment which is limited to 64K bytes. For eachof these message envelopes, the Builder will allocate storage for private AMX use.

Unfortunately, no hard and fast rule can be provided to determine the number of messageenvelopes needed. For simple systems with little message queuing and few tasksexecuting concurrently, the number of required message envelopes can range from one totwice the number of tasks in the system. More complex systems with significant queuingrequirements may require many more envelopes.

AMX Message Size

The maximum size of the message to be passed in a message envelope must also bedefined by you. The minimum message size is 12 bytes. The message size must be amultiple of 4.

AMX Kernel Stack Size

The AMX Kernel Task requires a minimum stack size of 128 bytes. In addition to thisminimum, you must allocate sufficient stack to satisfy the worst case requirements of allapplication Restart Procedures and Timer Procedures. If you have any nonconformingISPs, you must increase the Kernel Stack size to meet the interrupt overhead expected.No increase is needed if the ISP uses fewer than 40 bytes of stack. The stack size mustbe a multiple of 4 bytes.

AMX System Configuration KADAK 171

AMX Interrupt Stack Size

The AMX Interrupt Supervisor requires a minimum Interrupt Stack size of 128 bytes.The stack size must be a multiple of 4 bytes.

In addition to this minimum, you must allocate sufficient stack to satisfy the applicationISP with the greatest stack usage. If nested interrupts are possible, then the worst caseinterrupt nesting must be analyzed and additional interrupt stack size allocated. If nlevels of nesting are permitted, then the interrupt stack size must be increased by(64*n)+x bytes, where x is the sum of the worst case stack use by each of the nestedISPs.

AMX and Managers in Separate ROM

AMX and its managers can be installed in a private ROM and accessed by yourapplication via the AMX ROM access module. If you are using AMX this way, checkthis box.

If you are linking your application with AMX and its managers, leave this box uncheckedeven if you are going to burn your linked AMX system into a ROM.

Medium Model

If you have created any Medium model Restart Procedure, Exit Procedure or TimerProcedure, check this box. Otherwise leave this box unchecked.

24-bit Address Space

If you are using the Paradigm toolset (see AMX 86 Tool Guide, toolset PX) to create anAMX application for the VAutomation Turbo186 processor (or equivalent) with its 24-bitmemory addressing, check this box. Otherwise leave this box unchecked.

172 KADAK AMX System Configuration

Timing Options

Hardware Clock Frequency

This parameter defines the frequency of the AMX hardware clock in hertz. It is used byAMX to convert milliseconds to equivalent AMX system ticks. If your hardware clockfrequency is not integral, round the clock frequency to the nearest non-zero integer.

AMX Clock Conversion Factor

The AMX system tick is measured in multiples of hardware clock interrupts. Thisparameter specifies the number of hardware clock interrupts required for each systemtick. For example, a 100 Hz clock will generate interrupts at 10 millisecond intervals. Ifa 50 ms system tick is required, then this parameter must be set to 5.

Time Slicing Required

If you wish to allow tasks which share a priority level to be time sliced, check this box.Leave this box unchecked if time slicing of tasks is not required.

If time slicing has been enabled and a task has been defined to have a non-zero time slice,you will not be able to remove the check from this box. You must first set the time slicevalue for all defined tasks to 0. Then you will be able to remove the check from this box,thereby disabling time slicing.

Use Time/Date Manager

If you wish to include the Time/Date Manager, check this box. Otherwise leave the boxunchecked. Be sure to increase the maximum number of timers in your system by one toaccount for the AMX Time/Date timer.

Scheduling Procedure Name

If you use the Time/Date Manager, then you may wish to define a Time/Date SchedulingProcedure (see Chapter 5.5). This parameter defines that procedure name. If noprocedure is required, leave this field empty (blank).

This field is ignored if the Use Time/Date Manager check box is unchecked.

Note

When entering C procedure and variable names, be sure toadd a leading underscore character ( _ ) to the name ifrequired for reference from assembly language to symbolsgenerated by your C compiler.

AMX System Configuration KADAK 173

14.5 AMX Object AllocationThe AMX Object Allocation window allows you to define the number of private AMXobjects required for each of the optional AMX managers to be included in your system.The layout of the window is shown below.

Maximum Number of Tasks

This parameter defines the maximum number of application tasks which your system cansupport concurrently. The upper limit for this parameter is 100 tasks. The value for thisparameter should be the number of predefined tasks (see Chapter 14.7) plus themaximum number of tasks that you will dynamically create using ajtkcre. You do nothave to account for the AMX Kernel Task.

Maximum Number of Timers

This parameter defines the maximum number of timers which your system can supportconcurrently. If you do not require any timers, set this parameter to 0. Otherwise, thisparameter should be set to the number of predefined timers (see Chapter 14.8) plus themaximum number of timers that you dynamically create using ajtmcre.

174 KADAK AMX System Configuration

Maximum Number of Semaphores

This parameter defines the maximum number of resource and counting semaphoreswhich your system can support concurrently. If you do not require any semaphores, setthis parameter to 0. Otherwise, the parameter should be set to the number of predefinedsemaphores (see Chapter 14.9) plus the maximum number of resource or countingsemaphores that you will dynamically create using ajsmcre.

Maximum Number of Event Groups

This parameter defines the maximum number of event groups which your system cansupport concurrently. If you do not require any event groups, set this parameter to 0.Otherwise, the parameter should be set to the number of predefined event groups (seeChapter 14.10) plus the maximum number of event groups that you will dynamicallycreate using ajevcre.

Maximum Number of Message Exchanges

This parameter defines the maximum number of message exchanges which your systemcan support concurrently. If you do not require any message exchanges, set thisparameter to 0. Otherwise, the parameter should be set to the number of predefinedmessage exchanges (see Chapter 14.11) plus the maximum number of messageexchanges that you will dynamically create using ajmxcre.

Maximum Number of Buffer Pools

This parameter defines the maximum number of buffer pools which your system cansupport concurrently. If you do not require any buffer pools, set this parameter to 0.Otherwise, the parameter should be set to the number of predefined buffer pools (seeChapter 14.12) plus the maximum number of buffer pools that you will dynamicallycreate using ajbcre.

AMX System Configuration KADAK 175

Memory Assignment Procedure Name

If you use the AMX Memory Manager, you must provide a Memory AssignmentProcedure to assign memory sections to its memory pool for allocation to tasks (seeChapter 10.6). This parameter specifies the name of that procedure. If you are not usingthe AMX Memory Manager, leave this field empty (blank).

User Error Procedure Name

This parameter specifies the name of the User Error Procedure which AMX will callwhenever any AMX service procedure posts an error indication (see Chapter 13.2). Ifyou have no such procedure, leave this field empty (blank).

Fatal Exit Procedure Name

This parameter specifies the name of the Fatal Exit Procedure which is called by AMXwhenever a fatal error condition is detected (see Chapter 13.1). If you have no suchprocedure, leave this field empty (blank).

Note

When entering C procedure and variable names, be sure toadd a leading underscore character ( _ ) to the name ifrequired for reference from assembly language to symbolsgenerated by your C compiler.

176 KADAK AMX System Configuration

14.6 Restart/Exit Procedure DefinitionThe Launch/Shutdown window displays all of your application Restart and ExitProcedures which will be called by AMX at system startup and shutdown. The layout ofthe window is shown below.

The Restart Procedure List is used to define all of your application Restart Procedureswhich will be called by AMX at system startup. The Restart Procedures will be called byAMX in the order in which they appear in the list.

The Exit Procedure List is used to define all of your application Exit Procedures whichwill be called by AMX at system shutdown. The Exit Procedures will be called by AMXin the order in which they appear in the list.

AMX System Configuration KADAK 177

Add, Edit and Delete Restart and Exit Procedures

To add a new procedure, click on the Add button below the list. A new procedure named---New--- will appear at the bottom of the list. Click on the name ---New--- and it willbe opened ready for editing. Enter the name of your procedure.

To edit an existing procedure's name, double click on the name in the object list. Thename will be opened ready for editing.

To delete an existing procedure, click on the procedure's name in the object list. Thenclick on the Delete button below the list. Be careful because you cannot undo a deletion.

The procedure names in the object list can be rearranged by dragging a procedure's nameto the desired position in the list. You cannot drag a procedure directly to the end of thelist. To do so, first drag the procedure name to precede the last name on the list. Thendrag the last name on the list to precede its predecessor on the list.

Note

The Restart and Exit Procedures for all AMX Managerswill be automatically provided by the ConfigurationManager. You MUST NOT repeat them in your list ofapplication Restart or Exit Procedures.

178 KADAK AMX System Configuration

14.7 Task DefinitionThe Task Definition window allows you to define the tasks to be automatically created byAMX at system startup. You do not have to predefine all of your tasks in this manner;you may also create tasks dynamically using ajtkcre. The layout of the window isshown below.

AMX System Configuration KADAK 179

Task Tag

Each task can have a unique 4-character task tag. This parameter defines that tag.Although AMX does not restrict the content of the task tag field, the ConfigurationManager only supports 4 ASCII characters as a tag.

Priority

This parameter defines the execution priority of the task. Application task prioritiesrange from 1 (highest) to 127 (lowest). More than one task can be given the same taskpriority. Unless the task is time sliced, AMX will assign relative task priorities accordingto the order in which the task definitions appear on the screen.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the task id of the task.

Task Procedure Name

This parameter defines the name of the procedure to be called when AMX starts the task.

Stack Size

Each application task requires a block of RAM storage for use as a stack. The minimumstack size is 128 bytes. The stack size parameter must be a multiple of 4 bytes. If youincrease the AMX message size beyond the minimum allowed (see Chapter 14.4), youmust increase the size of all of your task stacks accordingly. In addition to this minimum,you must allocate sufficient stack to satisfy the worst case requirements of the task.

If your task installs its own task trap handlers (see Chapter 4.5), increase your task's stackby 64 bytes.

If you have any nonconforming ISPs, you must increase the stack size of all tasks to meetthe needs of these ISPs. No increase is needed if the ISP uses fewer than 40 bytes ofstack.

Time Slice

If the task is to be time sliced, you may specify the time slice interval in the taskdefinition. If time slicing is not required, set this parameter to 0.

This field will be disabled unless you have enabled the AMX time slice option bychecking the Time Slicing Required box on the System Parameter Window.

Time slicing is only effective if the task will be compute bound in competition with othertasks of equal priority.

The task's time slice may also be altered dynamically by calling ajtslv when yoursystem is running.

180 KADAK AMX System Configuration

Medium Model

Tasks can be either Large or Medium. If your task is Medium model, check this box.Otherwise, leave this box unchecked.

If you declare the task to be Medium, the Builder will allocate the task's stack in asegment which is part of group DGROUP so that DS = SS = DGROUP when the taskexecutes.

Task Message Queues (Mailboxes)

AMX allows creation of a task with a set of four private message queues (mailboxes) onwhich the task can receive AMX messages. To declare a task of this type, check this boxand fill in the required queue depths for the task's private message queues. Otherwiseleave the box unchecked.

Queue Depths

These four parameters define the maximum number of message envelopes which canreside in each of the task's four private message queues. Queue 0 is the highest priorityqueue; queue 3 is the lowest priority.

Depths may range from 0 to 32767. The maximum depth of a queue does not affectAMX memory requirements. If a particular message queue is to be unused, set its depthto zero. At least one message queue depth must be non-zero if the task is to be defined asrequiring message queues.

AMX System Configuration KADAK 181

14.8 Timer DefinitionThe Timer Definition window allows you to define the timers to be automatically createdby AMX at system startup. You do not have to predefine all of your timers in thismanner; you may also create timers dynamically using ajtmcre. Note that AMX doesnot automatically start timers defined this way. Your application must call ajtmwr toactually start the timer. The layout of the window is shown below.

182 KADAK AMX System Configuration

Tag

Each timer can have a unique 4-character timer tag. This parameter defines that tag.Although AMX does not restrict the content of the timer tag field, the ConfigurationManager only supports 4 ASCII characters as a tag.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the timer id of the timer.

Timer Procedure Name

This parameter defines the name of the Timer Procedure to be called whenever the timerexpires.

Timer Parameter Name

This parameter defines the name of a public pointer variable whose address will bepassed as a parameter to the Timer Procedure. If your timer does not require such aparameter, leave this field empty (blank).

Assume that your application includes a C variable tmparam declared as follows:

void *tmrparam;

Enter the name _tmrparam as the name of the timer parameter. Your Timer Procedure,coded in C, will then receive &tmrparam as its parameter.

Period

If the timer is a periodic timer, this parameter defines its period in multiples of AMXsystem ticks. If the timer is a one-shot timer, this parameter must be set to 0.

AMX System Configuration KADAK 183

14.9 Semaphore DefinitionThe Semaphore Definition window allows you to define the semaphores to beautomatically created by AMX at system startup. You do not have to predefine all ofyour semaphores in this manner; you may also dynamically create resource semaphoresand counting semaphores using ajsmcre. The layout of the window is shown below.

184 KADAK AMX System Configuration

Tag

Each semaphore can have a unique 4-character semaphore tag. This parameter definesthat tag. Although AMX does not restrict the content of the semaphore tag field, theConfiguration Manager only supports 4 ASCII characters as a tag.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the semaphore id of the semaphore.

Type

This option field defines the type of semaphore to be created, resource or counting. Theinitial value field is ignored for resource semaphores.

Initial Value

Counting semaphores may be given an initial value between 0 and 32767.

AMX System Configuration KADAK 185

14.10 Event Group DefinitionThe Event Group Definition window allows you to define the event groups to beautomatically created by AMX at system startup. You do not have to predefine all ofyour event groups in this manner; you may also create event groups dynamically usingajevcre. The layout of the window is shown below.

186 KADAK AMX System Configuration

Tag

Each event group can have a unique 4-character event group tag. This parameter definesthat tag. Although AMX does not restrict the content of the event group tag field, theConfiguration Manager only supports 4 ASCII characters as a tag.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the event group id of the event group.

Initial Value

This parameter defines the initial value of the 16 event flags in the event group. Thisparameter must be entered as 0 or as an unsigned hexadecimal number of the form0xdddd.

AMX System Configuration KADAK 187

14.11 Message Exchange DefinitionThe Message Exchange Definition window allows you to define the message exchangesto be automatically created by AMX at system startup. You do not have to predefine allof your message exchanges in this manner; you may also create message exchangesdynamically using ajmxcre. The layout of the window is shown below.

188 KADAK AMX System Configuration

Tag

Each message exchange can have a unique 4-character message exchange tag. Thisparameter defines that tag. Although AMX does not restrict the content of the messageexchange tag field, the Configuration Manager only supports 4 ASCII characters as a tag.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the message exchange id of the messageexchange.

Message Queue Depths

These four parameters define the maximum number of message envelopes which canreside in each of the four message queues of the message exchange. Message queue 0 isthe highest priority queue; queue 3 is the lowest priority.

Depths may range from 0 to 32767. If a particular message queue for a messageexchange is to be unused, set its depth to zero. Other message queues may still be used.At least one message queue must be used. The maximum depth for a message queuedoes not affect AMX memory requirements.

AMX System Configuration KADAK 189

14.12 Buffer Pool DefinitionThe Buffer Pool Definition window allows you to define the buffer pools to beautomatically created by AMX at system startup. You do not have to predefine all ofyour buffer pools in this manner; you may also create buffer pools dynamically usingajbcre. The layout of the window is shown below.

190 KADAK AMX System Configuration

Tag

Each buffer pool can have a unique 4-character buffer pool tag. This parameter definesthat tag. Although AMX does not restrict the content of the buffer pool tag field, theConfiguration Manager only supports 4 ASCII characters as a tag.

Id Variable

This parameter defines the name of a public variable of type AMXID in the SystemConfiguration Module in which AMX will save the buffer pool id of the buffer pool.

Buffer Size

This parameter defines the useable size (in bytes) of each buffer in the buffer pool. Theminimum buffer size is 8 bytes. The buffer size must be a multiple of 4.

Number of Buffers

This parameter defines the total number of buffers to be available in this buffer pool. Thepool must contain at least one buffer.

AMX System Configuration KADAK 191

14.13 Breakpoint Manager DefinitionThe AMX Breakpoint Manager can be used to improve the operation of your debugger inthe AMX multitasking environment. Your use of the Breakpoint Manager is optional.The layout of the window is shown below.

Include Breakpoint Manager

If you need to use the AMX Breakpoint Manager to shut off all task activity when yourdebugger hits a breakpoint, check this box. Otherwise, leave the box unchecked.

Entry/Exit Delay

If your debugger inhibits clock interrupts at breakpoints, you can improve the BreakpointManager's exit detection as follows. Set the breakpoint entry delay to -1 and thebreakpoint exit delay to 1. The Breakpoint Manager will assume that you have left thebreakpoint as soon as the next AMX clock tick is detected.

Otherwise, set both of these parameters to 0 or to the values specified in the toolsetdependent chapters of the AMX 86 Tool Guide.

192 KADAK AMX System Configuration

This page left blank intentionally.

AMX Service Procedures KADAK 193

15. AMX Service Procedures

15.1 IntroductionThe AMX Library provides a wide variety of services from which the real-time systemdesigner can choose. Many of the services are optional and, if not used, will not even bepresent in your final AMX system.

This section of the AMX User's Guide differs from the others because it is intended foruse as a programming guide. The remainder of this chapter introduces you to the AMXprogramming environment. Chapter 16 provides descriptions of all of the procedureswhich are available in the AMX Runtime Library in alphabetic order for easy reference.

All of the AMX procedures are described using the C programming language. It istherefore recommended that you be at least superficially familiar with C.

A functional list of procedures is presented in Chapter 15.2. It is recommended that youuse that chapter in conjunction with the procedure descriptions in Chapter 16 as follows.If you remember a procedure name but require information concerning its operation, gostraight to the procedure description in the alphabetic list of procedures in Chapter 16. Ifyou know what you wish to do functionally, but cannot remember the procedure name,go to Chapter 15.2 to quickly locate the procedure and then proceed to Chapter 16 to findits detailed description.

194 KADAK AMX Service Procedures

15.2 Summary of ServicesAMX provides a wide variety of services from which the real-time system designer canchoose. Many of the services are optional and, if not used, will not even be present inyour AMX system. The AMX managers are all optional.

All of AMX and its managers are fully reentrant and may be placed in Read OnlyMemory (ROM).

The following lists summarize all of the AMX procedures which are accessible to theuser. They are grouped functionally for easy reference.

Procedures are described in Chapter 16.

System Control Kernel Services

ajentr AAENTR Enter AMX multitasking worldajexit AAEXIT Leave AMX multitasking worldajfatl AAFATL Fatal exitajhook AAHOOK Install user hooks to AMX Schedulerajprvl AAPRVL Lower privilege levelajprvr AAPRVR Raise privilege levelajupt Find User Parameter Tableajver AAVER Get AMX version number

Interrupt Control for AMX 86

ajint AAINT Begin interrupt serviceajinx AAINX End interrupt serviceajispm AAISPM Make an ISP rootajitrp AAITRP Install task trap handlerajivtr AAIVTR Read entry in IVTajivtw AAIVTW Write entry in IVTajivtx AAIVTX Exchange entry in IVT

AMX Service Procedures KADAK 195

Task Control

ajend AAEND End task executionajgmsg AAGMSG Get the highest priority message available

Optionally get a message of a specific priorityajresum AARESUM Resume a suspended taskajsend AASEND Start a task by sending it a message at one of 4 prioritiesajsendpajsenw Optionally wait for that task to receive the messageajsenwpajsgnl AASGNL Signal a taskajsgrd AASGRD Read pending task signalsajsgres AASGRES Reset pending task signalsajsgwat AASGWAT Wait for task signalsajsusp AASUSP Suspend a taskajtkcre AATKCRE Create a new taskajtkid AATKID Get task identifier of current taskajtkpry AATKPRY Change a task's execution priorityajtksts AJTKSTS Fetch task statusajtktag AATKTAG Find task id of task with a specific task tagajtktcb AATKTCB Fetch pointer to a Task Control Blockajtrig AATRIG Start (trigger) a task with no messageajwait AAWAIT Wait for a wake requestajwakc AAWAKC Wake a task upon receipt of its messageajwakcs AAWAKCS Wake a task upon receipt of its message;

return status to that taskajwake AAWAKE Wake a task which is waitingajwapr AAWAPR Reset pending wake for current taskajwatm AAWATM Wait for a timed interval or until a wake request occurs

Task Termination Services

ajtkdel AATKDEL Delete a taskajtkill AATKILL Kill a task by forcing it to stop; flush its message mailboxesajtkstp AATKSTP Force a task to stopajtktrm AATKTRM Enable/disable abnormal task termination

196 KADAK AMX Service Procedures

Timing Control

ajclk AACLK AMX Clock Handlerajtick AATICK Read elapsed system ticksajtmcnv AATMCNV Convert milliseconds to system ticksajtmcre AATMCRE Create an interval timerajtmdel AATMDEL Delete an interval timerajtmrd AATMRD Read an interval timerajtmtag AATMTAG Find timer id of timer with a specific tagajtmwr AATMWR Start/stop an interval timerajtslv AATSLV Change a task's time slice intervalajtsof AATSOF Disable time slicingajtson AATSON Enable time slicing

Time/Date Manager

ajtdf AATDF Format calendar time/date as an ASCII stringajtdg AATDG Get calendar time/dateajtds AATDS Set calendar time/date

Semaphore Manager

ajsmcre AASMCRE Create a semaphoreajsmdel AASMDEL Delete a semaphoreajsmfre AASMFRE Free a resource (unconditional)ajsmget AASMGET Get use of a semaphore (no wait)ajsmrls AASMRLS Release a resource (nested)ajsmrsv AASMRSV Reserve a resource (optional timeout)ajsmsig AASMSIG Signal to a semaphoreajsmtag AASMTAG Find semaphore id of semaphore with a specific tagajsmwat AASMWAT Wait on a semaphore (optional timeout)

Event Manager

ajevcre AAEVCRE Create an event groupajevdel AAEVDEL Delete an event groupajevnt AAEVNT Get saved event flagsajevrd AAEVRD Read current state of events in a groupajevsig AAEVSIG Signal one or more events in a groupajevtag AAEVTAG Find group id of event group with a specific tagajevwat AAEVWAT Wait for all/any of a set of events in a group

(optional timeout)

AMX Service Procedures KADAK 197

Message Exchange Manager

ajmxcre AAMXCRE Create a message exchangeajmxdel AAMXDEL Delete a message exchangeajmxget AAMXGET Get a message from a message exchange (no wait)ajmxsnd AAMXSND Send message to a message exchangeajmxsndpajmxtag AAMXTAG Find exchange id of message exchange with a specific tagajmxwat AAMXWAT Wait for message to arrive at a message exchange

(optional timeout)

Buffer Manager

ajbau AABAU Add to buffer use countajbcre AABCRE Create a buffer poolajbdel AABDEL Delete a buffer poolajbfre AABFRE Free a bufferajbget AABGET Get a buffer from a specific poolajbgsz AABGSZ Get size of bufferajbia AABIA Initialize all currently defined buffer poolsajbip AABIP Initialize one buffer poolajbtag AABTAG Find pool id of a buffer pool with a specific tag

Memory Manager

ajmau AAMAU Add to block use countajmfre AAMFRE Free a block of memoryajmgeh AAMGEH Get a block of memory from a private memory sectionajmget AAMGET Get a block of memoryajmgsz AAMGSZ Get size of block of memoryajmhan AAMHAN Create a handle to a private memory sectionajmset AAMSET Fill a block of memory with a pattern

198 KADAK AMX Service Procedures

Circular List Manager

ajabl AAABL Add to bottom of circular listajatl AAATL Add to top of circular listajrbl AARBL Remove from bottom of circular listajrstl AARSTL Reset a circular listajrtl AARTL Remove from top of circular list

Linked List Manager

ajlcre AALCRE Create an empty listajlhead AALHEAD Find head of a listajlinsc AALINSC Insert before the specified object on a listajlinsh AALINSH Insert at the head of a listajlinsk AALINSK Insert into a keyed listajlinst AALINST Insert at the tail of a listajlmerg AALMERG Merge two listsajlnext AALNEXT Find next object on a list (walk towards tail)ajlordk AALORDK Reorder object on a keyed listajlprev AALPREV Find previous object on a list (walk towards head)ajlrmvc AALRMVC Remove specified object from a listajlrmvh AALRMVH Remove object from the head of a listajlrmvt AALRMVT Remove object from the tail of a listajltail AALTAIL Find tail of a list

AMX Service Procedures KADAK 199

Processor and C Interface Procedures

In addition to the services provided by AMX and its managers, the AMX Libraryincludes several C procedures of a general nature which simplify applicationprogramming in real-time systems on your target processor.

ajcfjlong Long jump to a mark set by ajcfjsetajcfjset Set a mark for a subsequent long jump by ajcfjlongajcfstkjmp Switch stacks and jump to a new procedure

ajdi Disable interruptsajei Enable interruptsajflagrd Read the processor flags register (FLAGS)ajflagrddi Read the processor flags register (FLAGS); then disable interruptsajflagwr Write to the processor flags register (EFLAGS)

ajgofs Get FAR pointer offsetajgseg Get FAR pointer selectorajgsreg Get (read) all segment registersajmodl Set DS to the DGROUP segment valueajproc Generate assembler procedure CALLajprocqajsint Generate software interruptajsintqajsofs Set FAR pointer offsetajsseg Set FAR pointer selectorajssreg Set all segment registers (except CS, SS)

Hardware I/O port operationsajinb Read from an 8-bit input I/O portajinw Read from a 16-bit input I/O portajoutb Write an 8-bit value to an output I/O portajoutw Write a 16-bit value to an output I/O port

200 KADAK AMX Service Procedures

AMX 86 PC Supervisor Service Procedures

In addition to the services provided by AMX and its managers, the AMX 86 PCSupervisor Library includes several C procedures which are of use only if the AMX 86PC Supervisor is used by your application. These procedures are documented in Chapter3.9 of the AMX 86 PC Supervisor Reference Manual.

ajbeep AABEEP Beep speakerajboot AABOOT Boot DOSajkbgc AAKBGC Get keyboard characterajkbof AAKBOF Clear specific keyboard featuresajkbon AAKBON Set specific keyboard featuresajkbss AAKBSS Sense keyboard statusajpdrl AAPDRL Release DOSajpdrp AAPDRP Reserve DOS (with priority)ajpdrs AAPDRS Reserve DOSajspof AASPOF Turn speaker offajspon AASPON Turn speaker on

AMX 86 Procedures KADAK 201

16. AMX 86 Procedures

16.1 IntroductionA description of every AMX Library procedure is provided in this chapter. Thedescriptions are ordered alphabetically for easy reference.

Italics are used to distinguish programming examples. Procedure names and variablenames which appear in narrative text are also displayed in italics. Occasionally a lowercase procedure name or variable name may appear capitalized if it occurs as the firstword in a sentence.

Vertical ellipses are used in program examples to indicate that a portion of the programcode is missing. Most frequently this will occur in examples where fragments ofapplication dependent code are missing.

:: /* Dismiss device interrupt */:

Capitals are used for all defined AMX filenames, constants and error codes. All AMXprocedure, structure and constant names can be readily identified according to thenomenclature introduced in Chapter 1.3.

A consistent style has been adopted for each description. The procedure name ispresented at the extreme top right and left as in a dictionary. This method of presentationhas been chosen to make it easy to find procedures since they are ordered alphabetically.

Purpose A one-line statement of purpose is always provided.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

This block is used to indicate which of your AMX application procedurescan call the AMX procedure. The term ISP refers to the Interrupt Handlerof a conforming ISP. A filled in box indicates that the procedure isallowed to call the AMX procedure. In the above example, only tasks andRestart Procedures would be allowed to call the procedure.

Setup Defines all input parameters to the procedure and gives an example of thecalling sequence.

If you are programming in C, you must include AMX header filesAMX831SD.H and AMX831EC.H so that you will have access to all structure,constant and error code definitions. File AMX831SD.H automaticallyincludes AMX header file AMX831CF.H to give you access to all AMXfunction prototypes. Within this chapter, header files are not shown in thesetup unless the function references an AMX structure or constant.

If you are programming in assembly language, you must include AMXheader files AMX831SD.DEF and AMX831EC.DEF so that you will haveaccess to all structure, constant and error code definitions. In yourmodules, AMX functions must be declared as external FAR procedures.

202 KADAK AMX 86 Procedures

Where If the procedure has input parameters, they will be described narratively.

Results The outputs produced by the procedure are always defined.

The state of the carry, parity, auxiliary, zero, sign and overflow flags areof no consequence when programming in C. In assembly language, thezero and sign flags reflect the value of the error code AERxxxx, if any,returned by AMX in register AX. The direction flag, if used, is alwaysrestored to its original state.

AMX procedures frequently must deal with the processor interrupt enableflag. The state of this flag upon exit from each AMX procedure isdefined.

All other 8086 processor flags are untouched by AMX.

Used By Some procedures such as ajentr cannot be called by any of yourapplication procedures listed at the top right corner of the page. Theallowable caller is explicitly identified.

Restrictions If any restrictions on the use of the procedure exist, they are described.

Note Special notes, suggestions or warnings are offered where necessary.

See Also A cross reference to other related AMX procedures is always provided ifapplicable.

All AMX procedures are coded as FAR procedures. Be sure that your C proceduresfollow Medium or Large model conventions when calling AMX procedures.

Almost all AMX procedures only return integers, the default assumed by the C language.

All AMX procedures assume that an integer or unsigned integer is a 16-bit word value.This assumption is consistent with the conventions adopted by most currently available16-bit C compilers for the 80x86.

AMX 86 Procedures KADAK 203

Assembly Language Programming

If you are programming in assembly language, refer to Appendix E for a description ofthe AMX assembly language calling conventions. The appendix includes a summary ofthe input and output register specifications for every AMX procedure. ExperiencedAMX programmers will usually find that the appendix is all that is required as aprogrammer's reference guide.

New AMX users will want to reference the detailed AMX procedure descriptionsprovided in this chapter. For their benefit, the assembly language input and outputregister specifications have been included in a cryptic form along with the C languagecall specifications.

Notational Conventions

The following example illustrates the notational conventions used for assembly languagecalling sequences.

AMXID semid;int value;char tag[4];int status;..

status = ajsmcre(&semid, value, tag);AX BX= BX [DX:CX]

Let reg be the assembly language mnemonic for any general 8 or 16-bit 8086 register.Let seg be the assembly language mnemonic for any 8086 segment register.

If reg appears underneath any input or output parameter name, then the value of thatparameter is presented or received in register reg. In the example, value is presented toassembly language procedure AASMCRE in BX and status is received from it in AX.

Some AMX procedures must return more than a single integer result to the caller. Whenprogramming in C, the caller must provide a pointer to a variable into which AMX canstore the result (&semid for example). The syntax reg= is used to indicate that at theassembler level, the result is returned in register reg, not in storage referenced by reg. Inthe example, the value which would be assigned to C variable semid is received fromAASMCRE in register BX.

Occasionally, parameters are passed by reference in C but by value in assembly language.For example, 4-character tags are passed as string pointers in C but are passed in aregister pair in assembly language. The syntax [reg] underneath a pointer to aparameter indicates that the actual parameter referenced by the pointer is passed inregister reg. In the example, the four bytes referenced by pointer tag are passed toAASMCRE in register DX:CX.

204 KADAK AMX 86 Procedures

FAR pointers are passed to AMX as seg:reg as in the following example.

status = ajsenw(taskid, priority, (void FAR *)msg);AX AASEND DX CX[14..0] ES:BX

CX[15]=1

Specific bits in a register reg are referenced using the syntax reg[bit] orreg[highbit..lowbit]. In this example, CX[15] is bit 15 of register CX. CX[14..0] isbits 0 to 14 inclusive of register CX. Unspecified bits in a register must be 0.

The above example also illustrates that procedure AASEND is the assembly languagecounterpart of ajsenw, not AASENW as might otherwise be expected.

One final notational syntax is illustrated by the following example.

status = ajmxsndp(exchange, priority, parm1, parm2...);AX AAMXSND BX DX @ES:SI

Procedure AAMXSND requires a FAR pointer to an AMX message in ES:SI. The messageis on the stack as parm1, parm2.... The syntax @seg:reg underneath a parametermeans that seg:reg will contain a FAR pointer to that parameter on the stack. In thisexample, ES:SI will point to the copy of parm1 on the stack. Hence, procedure AAMXSNDwill receive a FAR pointer to the AMX message parm1, parm2... in ES:SI as required.

AMX 86 Procedures KADAK 205

ajabl ajabl

Purpose Add to Bottom of Circular List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char item; /* one byte item */int status;..

status = ajabl(&list, item);AX ES:BX CL,CX or DX:CX

Where &list is a pointer to a circular list (see ajrstl).

item is the 1, 2 or 4 byte item to be added to the list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.0 = Added OK; list not full1 = Added OK; list now full

-1 = Cannot add item; list is full

See Also ajrstl, ajatl, ajrtl, ajrbl

206 KADAK AMX 86 Procedures

ajatl ajatl

Purpose Add to Top of Circular List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char item; /* one byte item */int status;..

status = ajatl(&list, item);AX ES:BX CL,CX or DX:CX

Where &list is a pointer to a circular list (see ajrstl).

item is the 1, 2 or 4 byte item to be added to the list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.0 = Added OK; list not full1 = Added OK; list now full

-1 = Cannot add item; list is full

See Also ajrstl, ajabl, ajrtl, ajrbl

AMX 86 Procedures KADAK 207

ajbau ajbau

Purpose Add to Buffer's Use Count

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int increment;char *buffp;int status;..

status = ajbau(buffp, increment);AX ES:BX DX

Where buffp is a pointer to a buffer obtained with an ajbget call.

increment is the signed value to be added to the buffer use count.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

use count = use count + incrementAERBNU = Buffer not in useAERBUV = Use count + increment >= 216

AERNSP = Buffer does not belong to a buffer pool

Once a buffer's use count is increased to n, the buffer will not be returnedto the free list of its pool until n calls to ajbfre are made to release thebuffer.

See Also ajbget, ajbfre

208 KADAK AMX 86 Procedures

ajbcre ajbcre

Purpose Create a Buffer Pool

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

AMXID poolid;struct amxbps pooldef;int status;..

status = ajbcre(&pooldef, &poolid);AX ES:BX DX=

Where &pooldef is a pointer to the pool definition which describes the bufferpool to be created.

The pool definition structure amxbps is defined in header fileAMX831SD.H (see Appendix D).

All parameters in the pool definition must be valid before ajbcre iscalled. The Buffer Manager will not modify your pool definition.

pooldef.ambpnb = NPN = number of buffers in the pool

pooldef.ambpbs = SPN = usable size of each buffer in bytes >= 8SPN must be even.

pooldef.ambpbp = a pointer to a word aligned region ofN = (SPN+4)*NPN bytes of contiguous alterable memory (RAM) forthe buffer pool.

pooldef.ambptagi = a 4-character name tag for the buffer pool.

&poolid is a pointer to storage for the buffer pool id of the buffer poolallocated to the caller.

AMX 86 Procedures KADAK 209

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNFP = No free buffer poolAERNBF = No buffers defined in your pool definitionAERBTS = Buffer size defined in your pool definition is too small

If the call is unsuccessful, poolid will be undefined.

See Also ajbdel, ajbtag

210 KADAK AMX 86 Procedures

ajbdel ajbdel

Purpose Delete a Buffer Pool

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID poolid;int status;..

status = ajbdel(poolid);AX DX

Where poolid is the pool id of the buffer pool to be deleted.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSP = Invalid pool id

Restrictions No buffer management operations affecting buffers in the pool oralteration of the content of any of the buffers in the pool may take placeduring or after deletion of the pool.

Only recommended for applications where it is certain that all buffers inthe pool are no longer in use.

See Also ajbcre

AMX 86 Procedures KADAK 211

ajbfre ajbfre

Purpose Free a Buffer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *buffp;int status;..

status = ajbfre(buffp);AX ES:BX

Where buffp is a pointer to a buffer obtained by an ajbget call.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERBNU = Buffer not in useAERNSP = Buffer does not belong to a buffer pool

The buffer use count is decremented by one. If the use count goes to zero,the buffer is returned to its pool's list of free buffers.

See Also ajbget, ajbau

212 KADAK AMX 86 Procedures

ajbget ajbget

Purpose Get a Buffer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID poolid;char *buffp;int status;..

status = ajbget(poolid, &buffp);AX DX ES:BX=

Where poolid is the pool id of the pool from which the buffer is to be obtained.

&buffp is a pointer to storage for the returned pointer to the buffer.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSP = Invalid pool idAERWNB = No free buffer available

If a buffer cannot be obtained, the value of buffp will be undefined.

If a buffer is allocated, the buffer use count is set to one.

See Also ajbfre, ajbau, ajbgsz

AMX 86 Procedures KADAK 213

ajbgsz ajbgsz

Purpose Get Size of Buffer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *buffp;unsigned int size;int status;..status = ajbgsz(buffp, &size);AX ES:BX CX=

Where buffp is a pointer to a buffer obtained with an ajbget call.

size is the size of the buffer in bytes.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERBNU = Buffer not in useAERNSP = Buffer does not belong to a buffer pool

If the buffer is not in use, a size of 0 is returned.

See Also ajbget

214 KADAK AMX 86 Procedures

ajbia ajbia

Purpose Initialize (Reset) All Buffer Pools

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int status;..

status = ajbia();AX

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERBTS = Buffer size defined for some pool is too small

If this error occurs, the Buffer Manager's private data hasbeen corrupted. You should consider this error to be fatal.

Restrictions This procedure would only be called when your AMX system is running ifit is your intent to reset ALL of your currently defined buffer pools. It iscalled automatically by the Buffer Manager when your AMX system isstarted.

No buffer management operations or alteration of buffer contents maytake place during initialization. All buffers in all pools are initialized evenif they are currently in use. Contents of buffers will be altered.

See Also ajbip

AMX 86 Procedures KADAK 215

ajbip ajbip

Purpose Initialize (Reset) One Buffer Pool

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID poolid;int status;..

status = ajbip(poolid);AX DX

Where poolid is the pool id of the buffer pool to be initialized.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSP = Invalid pool idAERBTS = Buffer size defined for the pool is too small

If this error occurs, the Buffer Manager's private data hasbeen corrupted. You should consider this error to be fatal.

Restrictions This procedure should only be used in applications in which it is certainthat buffers will not be used or released during the initialization of thebuffer pool.

No buffer management operations or alteration of buffer contents for anyof the buffers in the pool may take place during initialization. All buffersin the pool are initialized even if they are currently in use. Contents ofbuffers will be altered.

See Also ajbia

216 KADAK AMX 86 Procedures

ajbtag ajbtag

Purpose Find a Buffer Pool

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char tag[4];AMXID poolid;int status;..

status = ajbtag(&poolid, tag);AX DX= [DX:CX] see note

Where &poolid is a pointer to storage for the pool id of the buffer pool ofinterest.

tag is a pointer to a 4-character name identifying the buffer pool ofinterest.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSP = No buffer pool with matching tag can be found

If more than one buffer pool was created with the same tag, you will getback the pool id of one of them, but which one is not certain.

If a buffer pool with the given tag cannot be located, the pool id in poolidwill be undefined.

Buffer pool tags are 4 characters long. All characters must match yoursearch tag exactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajbcre

AMX 86 Procedures KADAK 217

ajcfjlong ajcfjlongajcfjset ajcfjset

Purpose ajcfjset Sets a Mark for a Long Jumpajcfjlong Long Jumps to that Mark

These procedures are provided for AMX portability. They are notreplacements for C library procedures longjmp or setjmp although theyfunction in a similar manner.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup Prototype is in file AMX831CF.H.#include "AMX831CF.H"void cdecl ajcfjlong(struct ajxjbuf *jbuf, int value);int cdecl ajcfjset(struct ajxjbuf *jbuf);

Where jbuf is a pointer to a jump buffer to be used to mark the processor state atthe time ajcfjset is called and to restore that state when ajcfjlong issubsequently called.

The processor dependent structure ajxjbuf is defined in fileAMX831SD.H.

value is an integer value to be returned to the ajcfjset caller whenajcfjlong initiates the long jump return. Value cannot be 0. If value= 0, ajcfjlong will replace it with value = 1.

Returns Ajcfjset returns 0 when initially called to establish the mark. Ajcfjsetreturns value (non 0) when ajcfjlong is called to do the long jump to themark established by the initial ajcfjset call.

There is no return from ajcfjlong.

Interrupts are not touched by ajcfjset or ajcfjlong.

Restrictions Ajcfjset must be called prior to any call to ajcfjlong. Each call mustreference the same jump buffer. The jump buffer must remain unalteredbetween the initial ajcfjset call and the subsequent ajcfjlong longjump return.

Under no circumstances should one task attempt a long jump using a jumpbuffer set by another task.

218 KADAK AMX 86 Procedures

Example #include "AMX831CF.H"

void cdecl dowork(struct ajxjbuf *jbp);

static struct ajxjbuf jumpbuffer;

#define STACKSIZE 512 /* Stack size (longs) */static long newstack[STACKSIZE];

/* Top of stack (grows down) */#define STACKP (&newstack[STACKSIZE - 1])

void cdecl taskbody(void) {

if (ajcfjset(&jumpbuffer) == 0)

/* Switch to new stack and do work */ajcfstkjmp(&jumpbuffer, STACKP,

(void (*)())dowork);/* Never returns to here */

/* Do work using original stack */dowork(NULL);}

void cdecl dowork(struct ajxjbuf *jbp) {

/* Do work */

/* If jump buffer provided, then use long jump to *//* restore the original stack and return */if (jbp != NULL)

ajcfjlong(jbp, 1);}

See Also ajcfstkjmp

AMX 86 Procedures KADAK 219

ajcfstkjmp ajcfstkjmp

Purpose Switch Stacks and Jump to a New Procedure

This procedure is provided for AMX portability.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup Prototype is in file AMX831CF.H.#include "AMX831CF.H"void cdecl ajcfstkjmp(void *vp, void *stackp,

void (*procp)());

Where vp is a pointer which is passed as a parameter to the new procedure.

stackp is a pointer to a properly aligned block of memory for use as astack. For the 80x86 family, the stack must be 16-bit word aligned.

Stackp must point to the top of the memory block since the processorstack builds downward.

procp is a pointer to the new procedure which is prototyped as follows:

void cdecl newfunc(void *vp);

For portability using different C compilers, cast your procedure pointeras (void (*)())newfunc in your call to ajcfstkjmp.

Interrupts � Disabled � Enabled � Restored

Returns There is no return from ajcfstkjmp. Use ajcfjset and ajcfjlong ifthere is a requirement to return to the original stack.

Interrupts are not touched by ajcfstkjmp.

Restrictions The new procedure referenced by procp must never return. Theprocedure can call ajend to end the calling task.

Example See the example provided with ajcfjset and ajcfjlong.

See Also ajcfjlong, ajcfjset, ajend

220 KADAK AMX 86 Procedures

ajclk ajclk

Purpose AMX Clock Handler

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup Interrupts must be disabled.ajclk();

Results Interrupts may be enabled and/or disabled and will then be restored totheir state at the time of the call.

Note This procedure is for Clock Interrupt Service Procedure use only.

Restrictions If you code your clock ISP in C, it must be coded as a C interruptprocedure as described in Chapter 5.2. The ISP must dismiss the clockinterrupt and call ajclk.

Interrupts must be disabled upon entry to ajclk or AACLK.

AMX 86 Procedures KADAK 221

ajdi ajdiajei ajei

Purpose Disable or Enable Interrupts

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajdi();ajei();

Results Interrupts are disabled by ajdi() or enabled by ajei().

The interrupt enable flag (IF) in the processor status register (FLAGS) isreset to 0 to disable interrupts or set to 1 to enable interrupts.

Restrictions Interrupts should be enabled within a short time after they are disabled orsystem performance will be degraded.

ISPs must not enable interrupts unless nested interrupts are supported inyour application by hardware such as an Intel 8259 Interrupt Controller.

Note These functions can be called from your main() program before AMX hasbeen launched or after AMX has been shut down.

See Also ajei, ajflagrd, ajflagrddi, ajflagwr

222 KADAK AMX 86 Procedures

ajend ajend

Purpose End Execution of a Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajend();

Results There is no return from ajend.

If any task is waiting for this task to finish processing its message, AMXwill automatically call ajwakc to wake that task.

Restrictions Ajend can only be used to terminate the task which is making the call.

See Also ajsend, ajtrig, ajwakc, ajtkstp, ajtkill, ajtkdel

AMX 86 Procedures KADAK 223

ajentr ajentr

Purpose Launch (Enter) the AMX Multitasking System

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxupts FAR *uptp;int launchparm;char *result;int status;..

ajupt(&uptp);status = ajentr(launchparm, uptp, &result);AX BX ES:SI DX:BX=

Where launchparm is a launch parameter bit mask.

bit 0 Exit control= 0 permanent launch= AMLPTMP temporary launch

bit 1 Interrupt Vector Table access= 0 IVT cannot be accessed= AMLPVA entries in IVT can be altered

bit 2 Interrupt state during launch= 0 interrupts disabled= AMLPIE interrupts enabled

uptp is a FAR pointer to your User Parameter Table.

The structure amxupts and mnemonics AMLPxxx are defined in headerfile AMX831SD.H (see Appendix D).

&result is a pointer to 4 bytes of storage for the exit information returnedby your ajexit call. If &result is NULL (0L), the parameter given toajexit is not returned to the ajentr caller. In this example, resultwill receive a pointer to a character.

224 KADAK AMX 86 Procedures

Results No return unless a task calls ajexit.

status = errcode given to ajexitresult = 4 byte parameter exitinfo given to ajexit

Upon return, interrupts are restored to their state upon entry to thisprocedure.

Used By Must only be called by a C main() procedure to start an AMX system.

See Also ajexit

AMX 86 Procedures KADAK 225

ajevcre ajevcre

Purpose Create an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;unsigned int ivalue;int status;char tag[4];..

status = ajevcre(&group, ivalue, tag);AX BX= BX [DX:CX]

Where &group is a pointer to storage for the event group id of the event groupallocated to the caller.

ivalue is the initial value of the 16 event flags in the group.

tag is a 4-character name tag for the event group.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNEB = No free event group

If the call is unsuccessful, group will be undefined.

See Also ajevdel, ajevtag

226 KADAK AMX 86 Procedures

ajevdel ajevdel

Purpose Delete an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;int status;..

status = ajevdel(group);AX BX

Where group is the group id of an event group acquired with a call to ajevcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAEREVU = Event group is still in use

One or more tasks are still waiting for events in the group.AERNSG = Invalid event group id

Restrictions You must be absolutely certain that no other task, ISP or Timer Procedureis in any way using or about to use the event group. Failure to observethis restriction may lead to unexpected and unpredictable faults.

See Also ajevcre

AMX 86 Procedures KADAK 227

ajevnt ajevnt

Purpose Get the Saved Event Flags

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int value;..

value = ajevnt();AX

Where value is the state of the 16 event flags at the time the calling task mostrecently completed a call to ajevwat.

Results Interrupts are untouched.

A task can wait for events in an event group by calling ajevwat. Ajevntis used to retrieve the state of the event flags at the time the ajevwat callcompleted.

Ajevwat saves a copy of the current state of all 16 event flags in thecalling task's Task Control Block at the moment the calling task's eventmatch occurs or its wait interval expires. Subsequent calls by the task toajevnt will retrieve these saved event flags.

Ajevnt is paired with a task's most recent ajevwat call. Ajevwat onlyupdates the saved event flag copy if an event match or timeout occurs. Ifajevwat has never updated the task's saved event flag copy, then thevalue returned by ajevnt will be undefined. Ajevnt will continue toreturn the same value until the task makes another call to ajevwat whichresults in an update of the saved event flag copy.

A task can only retrieve its own saved event flags. A task cannot retrievethe saved event flags of another task.

See Also ajevwat, ajevrd

228 KADAK AMX 86 Procedures

ajevrd ajevrd

Purpose Read the Current Event States in an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;unsigned int value;int status;..

status = ajevrd(group, &value);AX BX CX=

Where group is the group id of an event group acquired with a call to ajevcre.

&value is a pointer to storage to receive the current state of the 16 eventflags of the particular event group.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERNSG = Invalid event group id

If status is not AEROK, the variable value is unaltered.

Note Ajevrd differs from ajevnt. Ajevrd gives you the current state of all 16event flags of a particular event group. Ajevnt gives a task the state of all16 event flags at the completion of that task's most recent call to ajevwat.

See Also ajevnt

AMX 86 Procedures KADAK 229

ajevsig ajevsig

Purpose Signal Event(s) in an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;unsigned int mask;unsigned int value;int status;..

status = ajevsig(group, mask, value);AX see note

Where group is the group id of an event group acquired with a call to ajevcre.

mask is a 16-bit mask identifying the event flags of interest in the group.

value is a 16-bit value which specifies the desired states for each of theevent flags selected by the mask. The states of flags not specified bythe mask can be either set or clear.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Task switching is disabled and then restored to its state at the time of thecall.

Status is returned.AEROK = Call successfulAERNME = Cannot signal the event(s)

Probably implies that no AMX message envelopes areavailable for use.

AERNSG = Invalid event group id

An immediate task switch will occur if a task which was waiting for thenew event state is of higher priority than the current task.

Note Assembly language call is:PUSH valuePUSH maskPUSH groupCALL AAEVSIGADD SP,6

See Also ajevwat

230 KADAK AMX 86 Procedures

ajevtag ajevtag

Purpose Find an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;char tag[4];int status;..

status = ajevtag(&group, tag);AX BX= [DX:CX] see note

Where &group is a pointer to storage for the event group id if the event group ofinterest.

tag is a pointer to a 4-character name identifying the event group ofinterest.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSG = No event group with matching tag can be found

If more than one event group was created with the same tag, you will getback the event group id of one of them, but which one is not certain.

If an event group with the given tag cannot be located, the event group idin group will be undefined.

Event group tags are 4 characters long. All characters must match yoursearch tag exactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajevcre

AMX 86 Procedures KADAK 231

ajevwat ajevwat

Purpose Wait for Event(s) in an Event Group

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID group;unsigned int mask;unsigned int value;int match;long timeout;int status;..

status = ajevwat(group, mask, value, match, timeout);AX see note

Where group is the group id of an event group acquired with a call to ajevcre.

mask is a 16-bit mask identifying the event flags of interest in the group.

value is a 16-bit value which specifies the states of interest for each of theevent flags selected by the mask. The states of flags not specified bythe mask can be either set or clear.

match defines the event match requirements:0 Any selected flag in its required state is considered the event of

interest.<> 0 All selected flags must be in the state specified by value to be

considered the event of interest.

timeout is the maximum interval measured in AMX system ticks whichthe caller is prepared to wait for an event match. Timeout must bepositive. If timeout = 0, the caller will wait forever for the specifiedevent match.

232 KADAK AMX 86 Procedures

Results Interrupts are disabled and then enabled upon return.

Status is returned.AEROK = Call successful; event match occurredAERTMO = Timed out before event match occurredAERTMV = Invalid timeout interval (<0)AERNSG = Invalid event group id

If the events in the group match your event selection criterion when youcall ajevwat, the calling task continues execution immediately withoutwaiting.

Upon return from ajevwat after a match or a timeout, the state of all 16event flags at the time of the return are saved in the calling task's TaskControl Block. Procedure ajevnt can be called to retrieve the saved copyof the event flags. If you waited for any one of several events, you caninterpret these flags to determine which of the events caused your task toresume. If you timed out waiting for all of several events to occur, youcan interpret these flags to determine which events did not occur.

Note Assembly language call is:PUSH MS word of timeoutPUSH LS word of timeoutPUSH matchPUSH valuePUSH maskPUSH groupCALL AAEVWATADD SP,12

See Also ajevnt, ajevsig

AMX 86 Procedures KADAK 233

ajexit ajexit

Purpose Leave (Exit) the AMX Multitasking System

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *exitinfo;int errcode;..

ajexit(errcode, exitinfo);CX DX:BX

Where errcode is the error code to be returned to the ajentr caller as status.

exitinfo is any 4-byte parameter to be copied to the ajentr caller'sresult variable. In this example, the pointer value exitinfo will bereturned to the ajentr caller.

Results There is no return from ajexit.

Execution resumes in procedure ajentr.errcode is returned to the ajentr caller as status.exitinfo is copied to the ajentr caller's result variable.

Restrictions Your AMX system must be shut down. All task operation and device I/Omust be terminated before ajexit is called.

If AMX was started for permanent execution (launchparm[0] = 0 onentry to ajentr), AMX will take its fatal exit via ajfatl with error codeAERFX4 if you try to stop AMX.

See Also ajentr, ajfatl

Note

If any Exit Procedure is coded using the Medium model,any task which calls ajexit MUST also use the Mediummodel.

234 KADAK AMX 86 Procedures

ajfatl ajfatl

Purpose Fatal Exit from AMX

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int errcode;..

ajfatl(errcode);CX

Where errcode is an error code which will be passed to your Fatal Exit Procedureif one was provided in your User Parameter File.

Results There is no return from ajfatl.

If you have not provided a Fatal Exit Procedure or if it returns to AMX,AMX will halt at location AMHALT.

See Also ajexit

AMX 86 Procedures KADAK 235

ajflagrd, ajflagrddi ajflagrd, ajflagrddiajflagwr ajflagwr

Purpose Read Processor FlagsRead Processor Flags and Disable InterruptsWrite Processor Flags

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int flags;..

flags = ajflagrd(); /* Read current flags */flags = ajflagrddi(); /* Read current flags and */

/* then inhibit interrupts */..

ajflagwr(flags); /* Restore flags */

Results Ajflagrd and ajflagrddi return the state of the processor status register(FLAGS) at the time of the call.

Upon return from ajflagrddi, interrupts are disabled.

Upon return from ajflagrd, interrupts are untouched.

Ajflagwr writes parameter flags to the processor status register (FLAGS)and returns nothing.

Upon return from ajflagwr, interrupts are enabled or disabled accordingto the state of the interrupt enable flag (IF) in parameter flags.

Restrictions Interrupts should be enabled within a short time after they are disabled orsystem performance will be degraded.

Note The assembly language sequence for ajflagrd and ajflagrddi is:PUSHFPOP AX ;AX = processor flagsCLI ;Omit for ajflagrd

The assembly language sequence for ajflagwr is:PUSH <flags>POPF

Note These functions can be called from your main() program before AMX hasbeen launched or after AMX has been shut down.

See Also ajdi, ajei

236 KADAK AMX 86 Procedures

ajgmsg ajgmsg

Purpose Get Message from Task Mailbox

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int priority;char msg[AMXMSZ];int status;..

status = ajgmsg(priority, msg);AX CX ES:BX

Where priority is the priority of the task mailbox from which the message is tobe fetched.(0 = highest; 3 = lowest)(4 = highest priority available message)

msg is an array name or pointer to AMXMSZ consecutive bytes of storageinto which the message will be copied if it is available. The messagestorage variable may be any AMXMSZ byte structure. AMXMSZ isconfigured in the User Parameter File.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERCWT = Task's caller is still waitingAERNMG = No message waiting in the specified task mailbox

If status is not AEROK, the variable msg is unaltered.

If you get status AERCWT, the task which is making the ajgmsg call iscurrently processing a message sent from a task which is waiting foracknowledgement that its message has been received. You cannot get anew message until you finish with the current one. Call ajwakc to wakethe waiting task and then call ajgmsg again.

See Also ajsend, ajsenw, ajwakc

AMX 86 Procedures KADAK 237

ajgofs ajgofs

Purpose Get Pointer Offset

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int ofs;char FAR *pntr;..

ofs = ajgofs(pntr);

Results Interrupts are untouched.

The 16-bit unsigned integer value of the offset part of the FAR pointervariable pntr is returned in ofs.

See Also ajgseg, ajsofs, ajsseg

238 KADAK AMX 86 Procedures

ajgseg ajgseg

Purpose Get Pointer Segment

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned short int seg;char FAR *pntr;..

seg = ajgseg(pntr);

Results Interrupts are untouched.

The 16-bit unsigned integer value of the segment selector part of the FARpointer variable pntr is returned in seg.

See Also ajgofs, ajsofs, ajsseg

AMX 86 Procedures KADAK 239

ajgsreg ajgsreg

Purpose Get Segment Registers

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxsregs sregarray;..

ajgsreg(&sregarray);

Where &sregarray is a pointer to storage to receive the current contents of the8086 segment registers. The structure amxsregs is defined in headerfile AMX831SD.H (see Appendix D).

Results Interrupts are untouched.

See Also ajssreg

240 KADAK AMX 86 Procedures

ajhook ajhook

Purpose Install Task Scheduler Hooks

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup struct {int (*uhstart)();int (*uhend)();int (*uhsuspend)();int (*uhresume)();

} userhooks;..

ajhook((void FAR *)&userhooks); /* Install hooks */ES:BX

.

.ajhook(NULL); /* Remove hooks */

ES:BX=0

Where &userhooks is a FAR pointer to an array of four pointers to your schedulerprocedures.

Your procedures are called by the AMX Task Scheduler whenevertasks start, end, suspend or resume execution.

To inhibit the AMX Task Scheduler from any further calls to yourprocedures, call ajhook with a NULL (0L) pointer having a nullselector as illustrated.

Results Interrupts are untouched.

AMX 86 Procedures KADAK 241

ajinb ajinbajinw ajinw

Purpose Read an 8-Bit Input Port (Byte)Read a 16-Bit Input Port (Word)

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int portno;char portbyte;short int portword;..

portbyte = ajinb(portno);portword = ajinw(portno);

Where portno is the port number.

portbyte is the data byte read.

portword is the data word read.

Results Interrupts are untouched.

See Also ajoutb, ajoutw

242 KADAK AMX 86 Procedures

ajint ajintajinx ajinx

Purpose Begin Interrupt Service

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajint();

Results Interrupts are disabled.

The AMX Interrupt Supervisor saves all registers on the caller's stack. If atask has just been interrupted, AMX switches to the AMX Interrupt Stackbefore returning to the ajint caller.

Purpose End Interrupt Service

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajinx();

Results Interrupts are disabled.

The AMX Interrupt Supervisor checks to see if the ISP is returning to aninterrupted task. If so, it switches back to the task's stack. The savedregisters are restored from the stack before returning to the ajinx caller.

Restrictions Upon entry to ajinx, the stack must be as it was upon return fromprocedure ajint.

AMX 86 Procedures KADAK 243

ajispm ajispm

Purpose Make a Conforming ISP Root

This procedure creates an AMX root ISP permitting a standard C functionto serve as an AMX Interrupt Service Procedure.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxisps isproot;void intproc();..

ajispm(intproc, &isproot);CX:DX ES:BX

Where intproc is a pointer to a C procedure to be called from the root ISP.

&isproot is a pointer to storage in which a conforming AMX root ISP canbe constructed. The structure amxisps is defined in header fileAMX831SD.H (see Appendix D).

Results Interrupts are untouched.

The pointer to the root ISP, &isproot, can be installed in the InterruptVector Table using ajivtw or ajivtx.

Restrictions Procedure intproc is NOT an interrupt procedure. It is a standard Cfunction which is called from the ISP created in isproot. Therefore,intproc must NOT call AAINT or AAINX and must not end with an IRETinstruction.

See Also ajivtw, ajivtx

244 KADAK AMX 86 Procedures

ajitrp ajitrp

Purpose Install a Task Trap Handler

Install a task trap handler to service divide error, overflow or bound checkerror traps.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int inttype;void handler();int status;..

status = ajitrp(inttype, handler);AX DX ES:BX

Where inttype is the 8086 interrupt type

0 = Divide by 0 trap4 = INTO overflow trap5 = BOUND bounds trap

handler is a pointer to the task's trap handler for the particular error trap.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERITT = Interrupt type is not one for which task traps are allowed.

AMX 86 Procedures KADAK 245

ajivtr ajivtr

Purpose Read an Interrupt Vector

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int inttype;void (*oldproc)();int status;..

status = ajivtr(inttype, &oldproc);AX DX ES:BX

Where inttype is the 8086 interrupt type (0-255).

&oldproc is a pointer to storage for a copy of the function pointer fromthe specified entry in the Interrupt Vector Table.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERIPR = Vector table is not accessible

AMX was launched with access to the Interrupt VectorTable denied.

See Also ajivtw, ajivtx

246 KADAK AMX 86 Procedures

ajivtw ajivtw

Purpose Write an Interrupt Vector

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int inttype;void newproc();int status;..

status = ajivtw(inttype, newproc);AX DX ES:BX

Where inttype is the 8086 interrupt type (0-255).

newproc is a pointer to the new interrupt handler.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERIPR = Vector table is not accessible

AMX was launched with access to the Interrupt VectorTable denied.

Restrictions You must NOT use this procedure to alter the vector entries for the divideerror, overflow trap or bounds error. Use ajitrp for that purpose.

See Also ajitrp, ajivtr, ajivtx

AMX 86 Procedures KADAK 247

ajivtx ajivtx

Purpose Exchange an Interrupt Vector

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int inttype;void (*oldproc)();void newproc();int status;..

status = ajivtx(inttype, newproc, &oldproc);AX DX ES:BX DS:DI

Where inttype is the 8086 interrupt type (0-255).

newproc is a pointer to the new interrupt handler.

&oldproc is a pointer to storage for the pointer to the current interrupthandler.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERIPR = Vector table is not accessible

AMX was launched with access to the Interrupt VectorTable denied.

Note oldproc can be used as newproc in a subsequent call to ajivtx.

status = ajivtx(inttype, oldproc, &oldproc);

Restrictions You must NOT use this procedure to alter the vector entries for the divideerror, overflow trap or bounds error. Use ajitrp for that purpose.

See Also ajitrp, ajivtr, ajivtw

248 KADAK AMX 86 Procedures

ajlcre ajlcre

Purpose Create an Empty List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;int offset;..

ajlcre(&list, offset);DS:SI CX

Where &list is a pointer to the list header.

offset is the node offset (in bytes) at which the list node is located inapplication objects to be linked in this list.

Results Interrupts are untouched.

The list header is initialized to define an empty list.

AMX 86 Procedures KADAK 249

ajlhead ajlhead

Purpose Find First Object on List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

object = ajlhead(&list);ES:BX DS:SI

Where &list is a pointer to the list header.

Results Interrupts are untouched.

object = pointer to the first object on the list.

object = NULL if the list is empty.

The object remains on the list.

250 KADAK AMX 86 Procedures

ajlinsc ajlinsc

Purpose Insert Object before Current Object on List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *newobj, *curobj;..

ajlinsc(&list, newobj, curobj);DS:SI ES:BX CX:DI

Where &list is a pointer to the list header.

newobj is a pointer to the new object to be inserted before the objectspecified by curobj.

curobj is a pointer to a particular object on the list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

AMX 86 Procedures KADAK 251

ajlinsh ajlinsh

Purpose Insert Object at Head of List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

ajlinsh(&list, object);DS:SI ES:BX

Where &list is a pointer to the list header.

object is a pointer to the object to be inserted as the new head of the list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

252 KADAK AMX 86 Procedures

ajlinsk ajlinsk

Purpose Insert Object into Keyed List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;unsigned int key;..

ajlinsk(&list, object, key);DS:SI ES:BX CX

Where &list is a pointer to the list header.

object is a pointer to the object to be inserted into the list.

key is the insertion key. Objects are inserted in order of ascending keyvalues. The object with the smallest key will be at the head of the list.If other objects with the same key value already reside on the list, thenew object will be inserted after all other objects with that key.

Results Interrupts are disabled and then restored to their state at the time of thelist.

Restrictions The caller must own the list. The list must not be manipulated by othertasks, ISPs or Timer Procedures while this call is in progress. You can usethe Semaphore Manager to control ownership of the list if necessary.

ISPs should avoid the use of this procedure unless dealing with very shortlists. Use of this procedure with long lists may cause unacceptable timingeffects in ISPs.

AMX 86 Procedures KADAK 253

ajlinst ajlinst

Purpose Insert Object at Tail of List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

ajlinst(&list, object);DS:SI ES:BX

Where &list is a pointer to the list header.

object is a pointer to the object to be inserted as the new tail of the list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

254 KADAK AMX 86 Procedures

ajlmerg ajlmerg

Purpose Merge Two Lists

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs destlist, srclist;struct appobj *destobj, *srcobj;..

ajlmerg(&destlist, &srclist, destobj, srcobj);see note

Where &destlist is a pointer to the destination list header.

&srclist is a pointer to the source list header.

destobj is a pointer to the insertion point on the destination list.

srcobj is a pointer to the extraction point on the source list.

Results Interrupts are disabled and then restored to their state at the time of thecall.

All of the objects on the source list are inserted on the destination listbefore destobj. Objects are removed from the source list starting withsrcobj, wrapping around from the tail to the head, and ending with theobject immediately previous to srcobj. This list of source objects is theninserted in order before destobj. The following example illustrates thisprocess.

Beforesrcobj

srclist --- X -- Y -- Zdestlist -- A -- B -- C -- D -- E

destobj

Aftersrclist --- emptydestlist -- A -- B -- Y -- Z -- X -- C -- D -- E

AMX 86 Procedures KADAK 255

Note Assembly language call is:PUSH <segment srcobj>PUSH <offset srcobj>PUSH <segment destobj>PUSH <offset destobj>PUSH <segment scrlist>PUSH <offset scrlist>PUSH <segment destlist>PUSH <offset destlist>CALL AALMERGADD SP,16

Restrictions You must not merge two lists if either of the lists is a keyed list.

256 KADAK AMX 86 Procedures

ajlnext ajlnext

Purpose Find Next Object on List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx83lsd.h"..

struct amxlhs list;struct appobj *object, *curobj;..

object = ajlnext(&list, curobj);ES:BX DS:SI ES:BX

Where &list is a pointer to the list header.

curobj is a pointer to an object on this list.

Results Interrupts are untouched.

object = pointer to the next object on the list following the objectspecified by curobj.

object = NULL if curobj is at the tail of the list.

The object remains on the list.

AMX 86 Procedures KADAK 257

ajlordk ajlordk

Purpose Reorder an Object in a Keyed List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;unsigned int key;..

ajlordk(&list, object, key);DS:SI ES:BX CX

Where &list is a pointer to the list header.

object is a pointer to the object on the list which is to be moved withinthe list.

key is the value of the new key for object.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Restrictions The caller must own the list. The list must not be manipulated by othertasks, ISPs or Timer Procedures while this call is in progress. You can usethe Semaphore Manager to control ownership of the list if necessary.

ISPs should avoid the use of this procedure unless dealing with very shortlists. Use of this procedure with long lists may cause unacceptable timingeffects in ISPs.

See Also ajlinsk

258 KADAK AMX 86 Procedures

ajlprev ajlprev

Purpose Find Previous Object on List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object, *curobj;..

object = ajlprev(&list, curobj);ES:BX DS:SI ES:BX

Where &list is a pointer to the list header.

curobj is a pointer to an object on this list.

Results Interrupts are untouched.

object = pointer to the object on the list immediately preceding theobject specified by curobj.

object = NULL if curobj is at head of the list.

The object remains on the list.

AMX 86 Procedures KADAK 259

ajlrmvc ajlrmvc

Purpose Remove Object from List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

ajlrmvc(&list, object);DS:SI ES:BX

Where &list is a pointer to the list header.

object is a pointer to the object to be removed from the list.

Results Interrupts are disabled and then restored to their state at the time of call.

260 KADAK AMX 86 Procedures

ajlrmvh ajlrmvh

Purpose Remove Object from Head of List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

object = ajlrmvh(&list);ES:BX DS:SI

Where &list is a pointer to the list header.

Results Interrupts are disabled and then restored to their state at the time of thecall.

object = pointer to the object removed from the head of the list.

object = NULL if the list was empty.

AMX 86 Procedures KADAK 261

ajlrmvt ajlrmvt

Purpose Remove Object from Tail of List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

object = ajlrmvt(&list);ES:BX DS:SI

Where &list is a pointer to the list header.

Results Interrupts are disabled and then restored to their state at the time of thecall.

object = pointer to the object removed from the tail of the list.

object = NULL if the list was empty.

262 KADAK AMX 86 Procedures

ajltail ajltail

Purpose Find Last Object on List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxlhs list;struct appobj *object;..

object = ajltail(&list);ES:BX DS:SI

Where &list is a pointer to the list header.

Results Interrupts are untouched.

object = pointer to the last object on the list.

object = NULL if the list is empty.

The object remains on the list.

AMX 86 Procedures KADAK 263

ajmau ajmau

Purpose Add to Memory Block Use Count

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *blockp;int increment;int status;..

status = ajmau(blockp, increment);AX ES:BX DX

Where blockp is a pointer to a memory block allocated by ajmget or ajmgeh.

increment is the signed value to be added to the memory block's usecount.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

use count = use count + incrementAERMIB = Invalid memory block pointerAERMNU = Memory block not in useAERMOV = Memory block use count overflow

If the call is not successful, the memory block use count is unaltered.

Once a memory block's use count is increased to n, the memory will notbe freed until n calls to ajmfre are made to release the memory block.

See Also ajmget, ajmgeh, ajmfre

264 KADAK AMX 86 Procedures

ajmfre ajmfre

Purpose Free Previously Allocated Block

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *blockp;int status;..

status = ajmfre(blockp);AX ES:BX

Where blockp is a pointer to a memory block allocated by ajmget or ajmgeh.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERMIB = Invalid memory block pointerAERMNU = Memory block not in use

The memory block use count is decremented by one. If the use count goesto zero, the memory block is released for reuse.

See Also ajmget, ajmgeh, ajmau

AMX 86 Procedures KADAK 265

ajmgeh ajmgeh

Purpose Get a Memory Block Using a Memory Handle

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup long size;char *blockp;long memsize;char *handle;int status;..

status = ajmgeh(size, &blockp, &memsize, handle);AX DX:CX ES:BX= DX:CX= ES:BX

Where size is the number of bytes of memory required.

&blockp is a pointer to storage for the returned pointer to the memoryblock.

&memsize is a pointer to storage for the actual usable size in bytes of thememory block at blockp. memsize may be slightly larger than size.It is valid to replace &memsize with &size to update your sizevariable.

handle is a memory handle assigned by the Memory Manager in aprevious call to ajmhan. Note that the handle is a pointer.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

blockp is a pointer to a block of memory.memsize is the actual size of that block.

AERMNA = Memory not availableblockp is undefined.memsize is the size of the largest block of memory which iscurrently available using the given handle.

AERMIB = handle is an invalid memory handle.blockp and memsize are undefined.

If memory is allocated, the use count for the memory block is set to one.

See Also ajmau, ajmfre, ajmhan

266 KADAK AMX 86 Procedures

ajmget ajmget

Purpose Get a Memory Block

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup long size;char *blockp;long memsize;int status;..

status = ajmget(size, &blockp, &memsize);AX DX:CX ES:BX= DX:CX=

Where size is the number of bytes of memory required.

&blockp is a pointer to storage for the returned pointer to the memoryblock.

&memsize is a pointer to storage for the actual usable size in bytes of thememory block at blockp. memsize may be slightly larger than size.It is valid to replace &memsize with &size to update your sizevariable.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

blockp is a pointer to a block of memory.memsize is the actual size of that block.

AERMNA = Memory not availableblockp is undefined.memsize is the size of the largest currently available blockof memory.

If memory is allocated, the use count for the memory block is set to one.

See Also ajmau, ajmfre

AMX 86 Procedures KADAK 267

ajmgsz ajmgsz

Purpose Get Size of Memory Block

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *blockp;long blksize;int status;..

status = ajmgsz(blockp, &blksize);AX ES:BX DX:CX=

Where blockp is a pointer to a memory block allocated by ajmget or ajmgeh.

&blksize is a pointer to storage for the usable size in bytes of the memoryblock at blockp.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

blksize is the size of the block in bytes.AERMIB = Invalid memory block pointerAERMNU = Memory block not in use

If the call is not successful, the value of blksize is undefined.

See Also ajmget, ajmgeh

268 KADAK AMX 86 Procedures

ajmhan ajmhan

Purpose Create Memory Handle for Private Allocation

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *blockp;long memsize;char *handle;int status;..

status = ajmhan(blockp, memsize, &handle);AX ES:BX DX:CX ES:BX=

Where blockp is a pointer to an area of memory whose access is to be controlledby the Memory Manager. Blocks allocated by ajmget or ajmgeh aresuitable.

memsize is the size of the memory block at blockp.

&handle is a pointer to storage for a memory handle which must be usedfor subsequent access to smaller blocks within the larger block. Notethat the handle which is returned is a pointer.

Results Interrupts are untouched.

Status is returned.AEROK = Call successful

handle can be used for access to the block of memoryusing ajmgeh.

AERMNA = Memory size is too small

If the handle cannot be created, the value of handle is undefined.

See Also ajmgeh, ajmfre, ajmau

AMX 86 Procedures KADAK 269

ajmodl ajmodl

Purpose Get the DGROUP Segment Value

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajmodl();

Results Interrupts are untouched.

The data segment register DS is set to the base segment of group DGROUP.

This procedure is provided for use with mixed memory models.

270 KADAK AMX 86 Procedures

ajmset ajmset

Purpose Set (Fill) Memory

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char *mempntr;long memsize;unsigned short int pattern;int status;..

status = ajmset(mempntr, memsize, pattern);AX ES:BX DX:CX SI

Where mempntr is a pointer to the memory area which is to be filled with thepattern.

memsize is the size in bytes of the memory area at mempntr.

pattern is the 16-bit fill pattern.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERMMV = Memory overflow

Memsize is too large. An attempt to fill the memory regionwould exceed the 1 Mb addressing range.

This procedure is optimized for speed in filling large regions of memory.

The procedure will fill any even or odd sized region of byte or wordaligned memory. The least significant 8 bits of pattern are stored at*mempntr. The most significant 8 bits of pattern are stored at*(mempntr+1) provided memsize is greater than one. The pattern thenrepeats up to the extent indicated by memsize.

AMX 86 Procedures KADAK 271

ajmxcre ajmxcre

Purpose Create a Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;int mb0, mb1, mb2, mb3;char tag[4];int status;..

status = ajmxcre(&exchange, mb0, mb1, mb2, mb3, tag);AX BX= @ES:BX (see note) [DX:CX]

Where &exchange is a pointer to storage for the message exchange id of themessage exchange allocated to the caller.

mb0, mb1, mb2, mb3 are integers defining the maximum number ofmessage envelopes which can reside in each of the message exchangemessage queues (0 <= mbi <= 32767).

tag is the 4-character tag for the message exchange.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful.

exchange contains a valid message exchange id.AERNXB = No free message exchangeAERMBZ = Invalid message queue (mailbox) depth

If the call is unsuccessful, exchange is undefined.

Note For assembly language users, ES:BX contains a pointer to four 16-bitintegers defining the maximum depth of each of the four message queues.

See Also ajmxdel, ajmxtag

272 KADAK AMX 86 Procedures

ajmxdel ajmxdel

Purpose Delete a Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;int status;..

status = ajmxdel(exchange);AX BX

Where exchange is the exchange id of the message exchange to be deleted.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSX = Invalid message exchange idAERXIU = Message exchange is still in use

Messages may still be present in the message exchange orone or more tasks may be waiting for a message to arrive atthe message exchange.

Restrictions You must be absolutely certain that no other task, ISP or Timer Procedureis in any way using or about to use the message exchange. Failure toobserve this restriction may lead to unexpected and unpredictable faults.

See Also ajmxcre

AMX 86 Procedures KADAK 273

ajmxget ajmxget

Purpose Get a Message from a Message Exchange (no wait)

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;char msg[AMXMSZ];int status;..

status = ajmxget(exchange, msg);AX BX ES:SI

Where exchange is the message exchange id acquired by a call to ajmxcre.

msg is an array name or pointer to AMXMSZ consecutive bytes of storageinto which the message will be copied if it is available. The messagestorage variable may be any AMXMSZ byte structure. AMXMSZ isconfigured in the User Parameter File.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSX = Invalid message exchange idAERNMG = No message available

Note This procedure returns immediately with an error indication if no messageis available. Tasks can wait for a message by calling ajmxwat.

See Also ajmxwat, ajmxsnd

274 KADAK AMX 86 Procedures

ajmxsnd ajmxsnd

Purpose Send Message to Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;char msg[AMXMSZ];int priority;int status;..

status = ajmxsnd(exchange, priority, msg);AX BX DX ES:SI

Where exchange is the message exchange id acquired by a call to ajmxcre.

priority is the priority of the message.(0 = highest, 3 = lowest)

msg is an array name or pointer to AMXMSZ consecutive bytes that form themessage to be copied to the message exchange. The message may beany AMXMSZ byte structure. AMXMSZ is configured in the UserParameter File. If msg does not reside in the data segment, useprocedure ajmxsndf with a FAR pointer to the msg.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSX = Invalid message exchange idAERNME = No free message envelopeAERMBF = Message queue (mailbox) is fullAERNMB = No message queue (mailbox) of the specified priority

If one or more tasks are waiting at the exchange for a message, themessage will be given immediately to the task waiting at the head of theexchange's wait queue. Task rescheduling occurs immediately ifnecessary.

See Also ajmxsndp, ajmxwat, ajmxget

AMX 86 Procedures KADAK 275

ajmxsndp ajmxsndp

Purpose Send Message to a Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;int priority;int status;int parm1;int parm2;..

status = ajmxsndp(exchange, priority, parm1, parm2...);AX AAMXSND BX DX @ES:SI

Where exchange is the message exchange id acquired by a call to ajmxcre.

priority is the priority of the message.(0 = highest, 3 = lowest)

parm1, parm2... on the stack form the message to be copied to themessage exchange. The number of bytes copied from the stackdepends on the AMX message size which is AMXMSZ bytes. AMXMSZ isconfigured in the User Parameter File.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSX = Invalid message exchange idAERNME = No free message envelopeAERMBF = Message queue (mailbox) is fullAERNMB = No message queue (mailbox) of the specified priority

If one or more tasks are waiting at the exchange for a message, themessage will be given immediately to the task waiting at the head of theexchange's wait queue. Task rescheduling occurs immediately ifnecessary.

Note The equivalent assembly language procedure is AAMXSND which receivesthe parameters shown above.

See Also ajmxsnd, ajmxwat, ajmxget

276 KADAK AMX 86 Procedures

ajmxtag ajmxtag

Purpose Find a Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;char tag[4];int status;..

status = ajmxtag(&exchange, tag);AX BX= [DX:CX] see note

Where &exchange is a pointer to storage for the message exchange id of themessage exchange of interest.

tag is a pointer to a 4-character name identifying the message exchange ofinterest.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSX = No message exchange with matching tag can be found

If more than one message exchange was created with the same tag, youwill get back the message exchange id of one of them, but which one isnot certain.

If a message exchange with the given tag cannot be located, the messageexchange id in exchange will be undefined.

Message exchange tags are 4 characters long. All characters must matchyour search tag exactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajmxcre

AMX 86 Procedures KADAK 277

ajmxwat ajmxwat

Purpose Wait for a Message from a Message Exchange

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID exchange;char msg[AMXMSZ];long timeout;unsigned int priority;..

status = ajmxwat(exchange, msg, timeout, priority);AX BX ES:SI DX:CX DI

Where exchange is the message exchange id acquired by a call to ajmxcre.

msg is an array name or pointer to AMXMSZ consecutive bytes of storageinto which the message will be copied if it is available. The messagestorage variable may be any AMXMSZ byte structure. AMXMSZ isconfigured in the User Parameter File.

timeout is the maximum interval measured in AMX system ticks whichthe caller is prepared to wait for a message. Timeout must bepositive. If timeout = 0, the caller will wait forever for a message toarrive.

priority is the priority at which the caller wishes to wait (0 = highest).To wait in FIFO order, have all callers use the same value forpriority.

Results Interrupts are disabled and enabled and then restored to their state at thetime of the call.

Status is returned.AEROK = Call successfulAERNSX = Invalid message exchange idAERTMO = Timed out before message availableAERTMV = Invalid timeout interval (<0)

See Also ajmxget, ajmxsnd

278 KADAK AMX 86 Procedures

ajoutb ajoutbajoutw ajoutw

Purpose Write to an 8-Bit Output Port (Byte)Write to a 16-Bit Output Port (Word)

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int portno;char portbyte;short int portword;..

ajoutb(portno, portbyte);ajoutw(portno, portword);

Where portno is the port number.

portbyte is the data byte to be written.

portword is the data word to be written.

Results Interrupts are untouched.

See Also ajinb, ajinw

AMX 86 Procedures KADAK 279

ajproc ajprocajprocq ajprocq

Purpose Call Software Procedure

You can use this procedure to call any software procedure which, becauseof register setup requirements, cannot otherwise be called from C.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

void someproc();struct amxregs regarray;unsigned int regeax:..

regeax = ajproc(someproc, &regarray);orregeax = ajprocq(someproc, &regarray);

Where someproc is the name of the FAR procedure which you wish to call. Theprocedure must end with a FAR return.

regarray is a structure containing the processor register values which arerequired for the particular software procedure being called. Ajprocrequires that all of the segment registers in regarray be initializedwith valid selectors. Ajprocq unconditionally copies the contents ofthe current hardware segment registers into the segment registers inregarray. General register values which are not required by theprocedure do not have to be provided.

If registers DS and/or ES are not required by procedure someproc, set theirvalues to 0 in regarray.

The structure amxregs is defined in header file AMX831SD.H (seeAppendix D).

regeax is the value which was in register AX when the called procedureended.

280 KADAK AMX 86 Procedures

Results Interrupts will be in the state in which they are left by the called procedurewhen it exits.

All registers in regarray reflect the values in the processor registers at thetime the called procedure ended.

The real processor registers are only affected at the instant the softwareprocedure call is made.

Restrictions The flags register in regarray can be set prior to calling ajproc. Onlythe least significant 8 bits of the real flags register are altered to match thevalue specified in regarray.

Upon return, all 16 bits of the flags register in regarray are valid.

See Also ajsint

AMX 86 Procedures KADAK 281

ajprvl ajprvl

Purpose Lower Task Privilege

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajprvl();

Results Interrupts are disabled and then restored to their state at the time of thecall.

Restrictions Must follow every call to ajprvr. Once ajprvr is called, task switchingis inhibited until ajprvl is called.

See Also ajprvr

282 KADAK AMX 86 Procedures

ajprvr ajprvr

Purpose Raise Task Privilege

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajprvr();

Results Interrupts are disabled and then restored to their state at the time of thecall.

Restrictions Must be followed by a call to ajprvl as soon as possible to lower theprivilege level.

Task switching is inhibited until ajprvl is called.

Once ajprvr has been called, the task must not issue any AMX callswhich would force the task to wait or end. The task must remain computebound until it calls ajprvl to lower the task's privilege.

See Also ajprvl

AMX 86 Procedures KADAK 283

ajrbl ajrbl

Purpose Remove from Bottom of Circular List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char item; /* one byte item */int status;..

status = ajrbl(&list, &item);AX ES:BX CL=, CX= or DX:CX=

Where &list is a pointer to a circular list (see ajrstl).

&item is a pointer to storage for the 1, 2 or 4 byte item to be removed fromthe list. If &item is NULL (0L), the item is deleted from the list but isnot returned to the caller.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned..0 = Removed OK; list not empty1 = Removed OK; list now empty

-1 = Cannot remove item; list is empty

See Also ajrstl, ajatl, ajabl, ajrtl

284 KADAK AMX 86 Procedures

ajresum ajresum

Purpose Resume a Suspended Task

Resume a task known to be suspended as a result of an ajsusp call.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajresum(taskid);AX DX

Where taskid is the task id of the task to be resumed.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

An immediate task switch will occur if the task being resumed is of higherpriority than the current task.

See Also ajsusp

AMX 86 Procedures KADAK 285

ajrstl ajrstl

Purpose Initialize (Reset) a Circular List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup /* define type of slots */typedef char SLOT1; /* byte slot */typedef short int SLOT2; /* word slot */typedef long SLOT4; /* double word slot */

/* define number of slots in list */

#define NSLOT 64

struct {int header[4];SLOT4 slots[NSLOT];} list;

.

.ajrstl(&list, sizeof(SLOT4), NSLOT);

ES:BX DX CX

Where &list is a pointer to storage for use as a circular list.

sizeof(SLOT4) is the slot size of the circular list (1, 2, or 4 bytescorresponding to byte, word or double word slots).

NSLOT is the number of slots in the list. (0 < NSLOT < 16380)

Results Interrupts are disabled and then restored to their state at the time of thecall.

See Also ajatl, ajabl, ajrtl, ajrbl

286 KADAK AMX 86 Procedures

ajrtl ajrtl

Purpose Remove from Top of Circular List

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char item; /* one byte item */int status;..

status = ajrtl(&list, &item);AX BX CL=, CX= or DX:CX=

Where &list is a pointer to a circular list (see ajrstl).

&item is a pointer to storage for the 1, 2 or 4 byte item to be removed fromthe list. If &item is NULL (0L), the item is deleted from the list but isnot returned to the caller.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.0 = Removed OK; list not empty1 = Removed OK; list now empty

-1 = Cannot remove item; list is empty

See Also ajrstl, ajatl, ajabl, ajrbl

AMX 86 Procedures KADAK 287

ajsend ajsend

Purpose Send a Message to a Task Mailbox

To request AMX to send a message to a task at a given priority and tobegin execution of that task as soon as possible.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;char msg[AMXMSZ];int status;..

status = ajsend(taskid, priority, msg);AX DX CX ES:BX

Where taskid is the task id of the task to whom the message is to be sent.

priority is the priority of the message.(0 = highest; 3 = lowest).

msg is an array name or pointer to AMXMSZ consecutive bytes that form themessage to be copied to the destination task. The message may be anyAMXMSZ byte structure. AMXMSZ is configured in the User ParameterFile.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERNME = No free message envelopeAERNMB = No task mailbox of the specified priorityAERMBF = Task mailbox is full

An immediate task switch will occur if the task to whom the message isbeing sent is idle and is of higher priority than the current task.

See Also ajsendp, ajsenw

288 KADAK AMX 86 Procedures

ajsendp ajsendp

Purpose Send a Message to a Task Mailbox

To request AMX to send a message to a task at a given priority and tobegin execution of that task as soon as possible.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;int status;int parm1;int parm2;..

status = ajsendp(taskid, priority, parm1, parm2...);AX AASEND DX CX @ES:BX

Where taskid is the task id of the task to whom the message is to be sent.

priority is the priority of the message.(0 = highest; 3 = lowest).

parm1, parm2... on the stack form the message to be copied to thedestination task. The number of bytes copied from the stack dependson the AMX message size which is AMXMSZ bytes. AMXMSZ isconfigured in the User Parameter File.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERNME = No free message envelopeAERNMB = No task mailbox of the specified priorityAERMBF = Task mailbox is full

An immediate task switch will occur if the task to whom the message isbeing sent is idle and is of higher priority than the current task.

Note The equivalent assembly language procedure is AASEND which receives theparameters shown above.

See Also ajsend, ajsenw

AMX 86 Procedures KADAK 289

ajsenw ajsenw

Purpose Send a Message to a Task Mailbox (Wait for Ack)

To request AMX to send a message to a task at a given priority and tobegin execution of that task as soon as possible. The task making therequest is placed into the wait state until either:

1. the called task receives the message and makes an ajwakc call, or

2. the called task receives the message and ends by making an ajendcall or by returning to AMX.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;char msg[AMXMSZ];int status;..

status = ajsenw(taskid, priority, msg);AX AASEND DX CX[14..0] ES:BX

CX[15]=1

Where taskid is the task id of the task to whom the message is to be sent.

priority is the priority of the message.(0 = highest; 3 = lowest).

msg is an array name or pointer to AMXMSZ consecutive bytes that form themessage to be copied to the destination task. The message may be anyAMXMSZ byte structure. AMXMSZ is configured in the User ParameterFile.

290 KADAK AMX 86 Procedures

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERNME = No free message envelopeAERNMB = No task mailbox of the specified priorityAERMBF = Task mailbox is full

An immediate switch to the highest priority ready task will occur.

If the call is successful, status will be >= 0. By definition, the value 0 isthe AMX error code AEROK. If status > 0, it implies that the task towhom the message was sent wakened the caller using ajwakcs to return aresult to the caller. The positive value in variable status is the responsereturned by that task.

Note The equivalent assembly language procedure is AASEND which receives theparameters shown above.

See Also ajsenwp, ajsend, ajwakc, ajwakcs

AMX 86 Procedures KADAK 291

ajsenwp ajsenwp

Purpose Send a Message to a Task Mailbox (Wait for Ack)

To request AMX to send a message to a task at a given priority and tobegin execution of that task as soon as possible.

The task making the request is placed into the wait state until either:

1. the called task receives the message and makes an ajwakc call, or

2. the called task receives the message and ends by making an ajendcall or by returning to AMX.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;int status;int parm1;int parm2;..

status = ajsenwp(taskid, priority, parm1, parm2...);AX AASEND DX CX[14..0] @ES:BX

CX[15]=1

Where taskid is the task id of the task to whom the message is to be sent.

priority is the priority of the message.(0 = highest; 3 = lowest).

parm1, parm2... on the stack form the message to be copied to thedestination task. The number of bytes copied from the stack dependson the AMX message size which is AMXMSZ bytes. AMXMSZ isconfigured in the User Parameter File.

292 KADAK AMX 86 Procedures

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERNME = No free message envelopeAERNMB = No task mailbox of the specified priorityAERMBF = Task mailbox is full

An immediate switch to the highest priority ready task will occur.

If the call is successful, status will be >= 0. By definition, the value 0 isthe AMX error code AEROK. If status > 0, it implies that the task towhom the message was sent wakened the caller using ajwakcs to return aresult to the caller. The positive value in variable status is the responsereturned by that task.

Note The equivalent assembly language procedure is AASEND which receives theparameters shown above.

See Also ajsenw, ajsend, ajwakc, ajwakcs

AMX 86 Procedures KADAK 293

ajsgnl ajsgnl

Purpose Signal a Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;unsigned int tsignals;unsigned long siginfo;int status;..

status = ajsgnl(taskid, tsignals, &siginfo);AX DX BX[14..0] BX:CX=

BX[15]=0

Where taskid is the task id of the task to be signalled.

tsignals is a 15-bit mask identifying the task signals to be sent to thespecified task. Only the least significant 15 bits of tsignals (bits 0 to14) are used. The meaning of each of these signal bits is up to you.Set a bit to cause the corresponding task signal. Multiple task signalscan be specified in the mask. All other bits must be 0.

&siginfo is a pointer to storage for 32 bits of information about the stateof the task's 15 task signals at the instant this ajsgnl call completes.

If you are signalling only one task signal or are not interested in theadditional status returned in siginfo, replace &siginfo withNULL (0L).

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successful

Task was waiting for one or more of these signals.The task is no longer waiting. (See Note).

AERWAT = Warning: Task was waiting for one or more of thesesignals. The task is still waiting for othersignals. (See Note).

AERWKP = Warning: Task was not waiting for any of thesesignals. These signals are now pending forthe task. No signal overruns occurred.

AERNST = Invalid task id

294 KADAK AMX 86 Procedures

Results (continued)

AERTNW = Task was not waiting for any of these signals. Thesesignals are now pending for the task. At least one of thesesignals was already pending implying a signal overrun.Variable siginfo can be examined to see which signalscaused the overrun.

Siginfo provides additional information concerning the results of thesignal. Bits 0 to 14 identify signal overruns. If any of these bits is set, itimplies that the task was not waiting for that task signal and that the tasksignal was already pending.

Bits 16 to 30 of siginfo indicate which, if any, of all of the task's 15 tasksignals remain pending after this ajsgnl call. Bits 16 to 30 correspond totask signal bits 0 to 14 respectively.

An immediate task switch will occur if the task being signalled is ofhigher priority than the current task and its signal wait condition has beensatisfied as a result of this call.

Note When signalling multiple task signals at once, it is possible to generate asignal overrun and still get the AEROK or AERWAT result in status.

For example, if you generate task signals A and B and the task is waitingfor signal A and signal B is already pending, then status will returnAEROK because the task's signal wait condition has been satisfied.However, an overrun on task signal B did occur and will be indicated invariable siginfo.

If tsignals only specifies one task signal, then status completelydefines the result. You can replace &siginfo with NULL if so desired.

AEROK Task resumedAERWKP Task not waiting; signal now pendingAERTNW Task not waiting; signal overrun

AMX procedure ajwake is a simplified form of procedure ajsgnl inwhich one predefined private AMX task signal is used.

See Also ajsgwat, ajsgrd, ajsgres, ajwake

AMX 86 Procedures KADAK 295

ajsgrd ajsgrd

Purpose Read Pending Task Signals

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int tsignals;..

tsignals = ajsgrd();AX

Where tsignals is the current state of the calling task's task signals.

Results Interrupts are untouched.

tsignals contains the current value of each of the task's 15 task signals inthe least significant 15 bits (bits 0 to 14). All other bits of tsignals willbe 0.

If a task signal bit in tsignals is set, it means that the corresponding tasksignal has been signalled at least once (by some call to ajsgnl) followingthe most recent call by this task to ajsgres to reset that task signal OR toajsgwat to wait for that task signal.

Restriction A task can only read its own task signals. It cannot read the task signals ofany other task.

See Also ajsgwat, ajsgnl, ajsgres

296 KADAK AMX 86 Procedures

ajsgres ajsgres

Purpose Reset Pending Task Signals

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int tsignals;..

ajsgres(tsignals);BX[14..0]BX[15]=0

Where tsignals is a 15-bit mask identifying the task signals to be reset. Onlythe least significant 15 bits of tsignals (bits 0 to 14) are used. Set abit to force the reset of the corresponding task signal. All other bitsmust be 0.

Results Interrupts are untouched.

The task signals specified by tsignals are reset. All other task signalsare unaltered.

Restriction A task can only reset its own task signals. It cannot reset the task signalsof any other task.

Note AMX procedure ajwapr is a simplified form of procedure ajsgres inwhich one predefined private AMX task signal is used.

See Also ajsgwat, ajsgnl, ajsgrd, ajwapr

AMX 86 Procedures KADAK 297

ajsgwat ajsgwat

Purpose Wait for Task Signal(s)

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int tsignals;long timeout;int match;int status;unsigned int sigrecv;..

status = ajsgwat(tsignals, match, timeout, &sigrecv);AX BX[14..0] BX[15] DX:CX BX=

Where tsignals is a 15-bit mask identifying the task signals of interest. Onlythe least significant 15 bits of tsignals (bits 0 to 14) are used. Set abit to wait for the corresponding task signal. All other bits must be 0.

match defines the task signal match requirements:0 Wait for any of the selected task signals to occur.

<> 0 Wait for all of the selected task signals to occur.

timeout is the maximum interval measured in AMX system ticks whichthe caller is prepared to wait for the task signal match to occur.Timeout must be positive. If timeout = 0, the caller will wait foreverfor the specified task signal match. (See Note).

&sigrecv is a pointer to storage for a 15-bit mask identifying the tasksignals satisfied by this call. If &sigrecv = NULL (0L), no task signalinformation is returned.

298 KADAK AMX 86 Procedures

Results Interrupts are disabled and then enabled upon return.

Status is returned.AEROK = Call successfulAERTM0 = Timed out before required signals occurredAERTMV = Invalid timeout interval (<0)

sigrecv identifies the received task signals which satisfied the matchcriteria or those which had occurred prior to timeout.

If waiting for any of n task signals (match = 0),AEROK: sigrecv identifies which of the n task

signals occurred.AERTMO: sigrecv = 0.

If waiting for all of n task signals (match = 0),AEROK: sigrecv = tsignals.AERTMO: sigrecv identifies which of the n task

signals, if any, occurred beforethe timeout.

Note Some or all of the task signals specified by tsignals may already bepending at the time of the ajsgwat call. If these pending task signalssatisfy the match criteria, the calling task will resume instantly withstatus = AEROK and sigrecv set as described.

Upon return from ajsgwat, the task's task signals, if any, indicated bysigrecv will have been reset. All other task signals remain unaltered.

If tsignals = 0 and timeout = 0, the calling task will resume instantlywith status = AEROK and sigrecv = 0.

AMX procedures ajwait and ajwatm are a simplified form of procedureajsgwat in which one predefined private AMX task signal is used.

Delay If tsignals = 0 and a timeout interval is specified, the task willunconditionally delay until the interval has expired. No task signal viaajsgnl or ajwake call can end the delay prematurely.

See Also ajsgnl, ajsgrd, ajsgres, ajwait, ajwatm

AMX 86 Procedures KADAK 299

ajsint ajsintajsintq ajsintq

Purpose Generate Software Interrupt

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxregs regarray;int inttype;unsigned int regeax:..

regeax = ajsint(inttype, &regarray);orregeax = ajsintq(inttype, &regarray);

Where inttype is the interrupt type (number 0 to 255).

regarray is a structure containing the processor register values which arerequired for the particular software interrupt being generated. Ajsintrequires that all of the segment registers in regarray be initializedwith valid selectors. Ajsintq unconditionally copies the contents ofthe current hardware segment registers into the segment registers inregarray. General register values which are not required by theinterrupt procedure do not have to be provided.

If registers DS and/or ES are not required by the interrupt procedure, settheir values to 0 in regarray.

The structure amxregs is defined in header file AMX831SD.H (seeAppendix D).

regeax is the value which was in register AX when the interrupt procedureended.

300 KADAK AMX 86 Procedures

Results Interrupts will be in the state in which they are left by the interruptprocedure when it exits.

All registers in regarray reflect the values in the processor registers at thetime the interrupt procedure ended.

The real processor registers are only affected at the instant the softwareinterrupt call is made.

Restrictions The flags register in regarray can be set prior to calling ajsint. Onlythe least significant 8 bits of the real flags register are altered to match thevalue specified in regarray.

Upon return, all 16 bits of the flags register in regarray are valid.

See Also ajproc

AMX 86 Procedures KADAK 301

ajsmcre ajsmcre

Purpose Create a Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int value;char tag[4];int status;..

status = ajsmcre(&semid, value, tag);AX BX= BX [DX:CX]

Where &semid is a pointer to storage for the semaphore id of the semaphoreallocated to the caller.

value is the initial value of the semaphore.(-1 <= value <= 32767)

If value is -1, then a resource semaphore is created with an initialvalue of 1, making the resource free for use. Otherwise, a countingsemaphore is created with the initial count specified by parametervalue.

tag is a 4-character name tag for the semaphore.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERISV = Invalid semaphore valueAERNSB = No free semaphore

If the call is unsuccessful, semid is undefined.

See Also ajsmdel, ajsmtag

302 KADAK AMX 86 Procedures

ajsmdel ajsmdel

Purpose Delete a Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int status;..

status = ajsmdel(semid);AX BX

Where semid is the semaphore id of a resource or counting semaphore acquiredby a call to ajsmcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERSIU = Semaphore is in use

One or more tasks may be waiting on the semaphore.

Restriction You must be absolutely certain that no other task, ISP or Timer Procedureis in any way using or about to use the semaphore. Failure to observe thisrestriction may lead to unexpected and unpredictable faults.

See Also ajsmcre

AMX 86 Procedures KADAK 303

ajsmfre ajsmfre

Purpose Unconditionally Free a Resource Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int status;..

status = ajsmfre(semid);AX BX

Where semid is the semaphore id of a resource semaphore acquired by a call toajsmcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERRNY = Resource semaphore cannot be released since the calling

task does not own the resource.

Note The resource's use count is immediately set to zero and the resource freed.

The resource will immediately be given to the task (if any) which iswaiting at the head of the resource semaphore wait queue. Taskrescheduling occurs immediately if necessary.

Restriction You must not attempt to free a counting semaphore. Use ajsmsig for thatpurpose.

See Also ajsmrls, ajsmrsv

304 KADAK AMX 86 Procedures

ajsmget ajsmget

Purpose Get Use of a Semaphore (no wait)

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int status; . .status = ajsmget(semid);AX BX

Where semid is the semaphore id of a counting semaphore acquired by a call toajsmcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERSBY = Semaphore already in use

Use of the semaphore is not granted to caller.

Note This procedure returns immediately with an error indication if thesemaphore is in use. Tasks can wait for the use of the semaphore bycalling ajsmwat.

Restriction You must not attempt to get the use of a resource semaphore. Useajsmrsv for that purpose.

See Also ajsmwat, ajsmsig

AMX 86 Procedures KADAK 305

ajsmrls ajsmrls

Purpose Release a Resource Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int status;..

status = ajsmrls(semid); /* nested release */AX BX

Where semid is the semaphore id of a resource semaphore acquired by a call toajsmcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERRNY = Resource semaphore cannot be released since the calling

task does not own the resource.

Note The resource's use count is decremented by one for each call to ajsmrls.The resource is not freed until the use count becomes zero.

Once freed, the resource will immediately be given to the task (if any)which is waiting at the head of the resource semaphore wait queue. Taskrescheduling occurs immediately if necessary.

Restriction You must not attempt to release a counting semaphore. Use ajsmsig forthat purpose.

See Also ajsmfre, ajsmrsv

306 KADAK AMX 86 Procedures

ajsmrsv ajsmrsv

Purpose Reserve a Resource Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;long timeout;unsigned int priority;int status;..

status = ajsmrsv(semid, timeout, priority);AX BX DX:CX DI

Where semid is the semaphore id of a resource semaphore acquired by a call toajsmcre.

timeout is the maximum interval measured in AMX system ticks whichthe caller is prepared to wait for the resource. Timeout must bepositive. If timeout = 0, the caller will wait forever for the resource.

priority is the priority at which the caller wishes to wait (0 = highest).To wait in FIFO order, have all callers use the same value forpriority.

AMX 86 Procedures KADAK 307

Results Interrupts are disabled and then enabled upon return.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERTMO = Timed out without being granted the resourceAERTMV = Invalid timeout interval (<0)

The calling task will be suspended waiting for the resource if the resourceis owned by some other task.

When the resource is finally available for use by the caller, the procedurewill return with status = AEROK.

Upon first acquiring ownership of the resource, the resource's use count isset to one.

It is permissible for a task to call ajsmrsv even if the calling task alreadyowns the resource. The resource use count is incremented by one for eachsubsequent call by the resource owner.

Restriction You must not attempt to reserve a counting semaphore. Use ajsmwat orajsmget for that purpose.

See Also ajsmrls, ajsmfre

308 KADAK AMX 86 Procedures

ajsmsig ajsmsig

Purpose Signal a Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;int status;..

status = ajsmsig(semid);AX BX

Where semid is the semaphore id of a counting semaphore acquired by a call toajsmcre.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERNME = Cannot signal the semaphore because no AMX message

envelopes are available for use

The semaphore will immediately be given to the task (if any) which iswaiting at the head of the semaphore wait queue. Task reschedulingoccurs immediately if necessary.

Restriction You must not attempt to signal a resource semaphore. Use ajsmfre orajsmrls for that purpose.

See Also ajsmwat

AMX 86 Procedures KADAK 309

ajsmtag ajsmtag

Purpose Find a Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;char tag[4];int status;..

status = ajsmtag(&semid, tag);AX BX= [DX:CX] see note

Where semid is a pointer to storage for the semaphore id of the semaphore ofinterest.

tag is a pointer to a 4-character name identifying the semaphore ofinterest.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSS = No semaphore with matching tag can be found

If more than one semaphore was created with the same tag, you will getback the semaphore id of one of them, but which one is not certain.

If a semaphore with the given tag cannot be located, the semaphore id insemid will be undefined.

Semaphore tags are 4 characters long. All characters must match yoursearch tag exactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajsmcre

310 KADAK AMX 86 Procedures

ajsmwat ajsmwat

Purpose Wait on a Semaphore

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID semid;long timeout;unsigned int priority;int status;..

status = ajsmwat(semid, timeout, priority);AX BX DX:CX DI

Where semid is the semaphore id of a counting semaphore acquired by a call toajsmcre.

timeout is the maximum interval measured in AMX system ticks whichthe caller is prepared to wait for the semaphore. Timeout must bepositive. If timeout = 0, the caller will wait forever for thesemaphore.

priority is the priority at which the caller wishes to wait (0 = highest).To wait in FIFO order, have all callers use the same value forpriority.

Results Interrupts are disabled and then enabled upon return.

Status is returned.AEROK = Call successfulAERNSS = Invalid semaphore idAERTMO = Timed out without being granted use of the semaphoreAERTMV = Invalid timeout interval (<0)

Restriction You must not attempt to wait on a resource semaphore. Use ajsmrsv forthat purpose.

See Also ajsmget, ajsmsig

AMX 86 Procedures KADAK 311

ajsofs ajsofs

Purpose Set Pointer Offset

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned int ofs;char FAR *pntr;..

ajsofs(&pntr, ofs);

Results Interrupts are untouched.

The offset part of the FAR pointer variable pntr is set to the 16-bitunsigned value of ofs.

See Also ajsseg, ajgofs, ajgseg

312 KADAK AMX 86 Procedures

ajsseg ajsseg

Purpose Set Pointer Segment

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned short int seg;char FAR *pntr;..

ajsseg(&pntr, seg);

Results Interrupts are untouched.

The segment selector part of the FAR pointer variable pntr is set to the16-bit unsigned value of seg.

See Also ajssof, ajgofs, ajgseg

AMX 86 Procedures KADAK 313

ajssreg ajssreg

Purpose Set Segment Registers

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxsregs sregarray;..

ajssreg(&sregarray);

Where &sregarray is a pointer to a structure defining the selector values to be setin segment registers DS and ES. Structure amxsregs is defined inheader file AMX831SD.H (see Appendix D).

Results Interrupts are untouched.

Restriction This procedure does NOT modify segment registers CS or SS to reflect thevalues in structure sregarray.

See Also ajgsreg

314 KADAK AMX 86 Procedures

ajsusp ajsusp

Purpose Suspend a Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajsusp(taskid);AX DX

Where taskid is the task id of the task to be suspended.

Results Interrupts are disabled and then restored to their state at the time of thecall.

The task will be suspended until some other task, ISP or Timer Procedureissues an ajresum call to resume this task.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

Note A task can suspend itself using ajsusp. However, it is preferred that youuse ajwait for this purpose.

See Chapter 13.5 for a description of the intended purpose and use of thisprocedure.

Restriction You must not suspend the AMX Kernel Task.

See Also ajresum

AMX 86 Procedures KADAK 315

ajtdf ajtdf

Purpose Format Time and Date as an ASCII String

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxtds tdbuf;char ascii[26];int format;int n;..

n = ajtdf(&tdbuf, format, ascii);AX ES:BX DL DS:DI

Where tdbuf is an AMX time/date structure containing the time and date(returned by ajtdg) which is to be formatted. The structure amxtds isdefined in header file AMX831SD.H (see Appendix D).

format is the format specification value described in Chapter 5.5. Onlythe least significant 8 bits of format are used.

ascii is a 26-byte character array into which time and/or date will beformatted as a null ('\0') terminated ASCII string.

Results Interrupts are untouched.

n is the number of characters stored in the ascii array, not including theterminating null ('\0').

See Also ajtdg

316 KADAK AMX 86 Procedures

ajtdg ajtdg

Purpose Get Current Time and Date

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxtds tdbuf;..

ajtdg(&tdbuf);ES:BX

Where &tdbuf is a pointer to the structure which is to receive the current time anddate. The structure amxtds is defined in header file AMX831SD.H (seeAppendix D).

Results Interrupts are disabled and then restored to their state at the time of thecall.

See Also ajtds, ajtdf

AMX 86 Procedures KADAK 317

ajtds ajtds

Purpose Set the Time and Date

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxtds tdbuf;..

Initialize tdbuf with new time and date...

ajtds(&tdbuf);ES:BX

Where &tdbuf is a pointer to the structure which contains the new time and date.The structure amxtds is defined in header file AMX831SD.H (seeAppendix D).

Results Interrupts are disabled and then restored to their state at the time of thecall.

The AMX system time and date is set to that specified by the caller instructure tdbuf.

The values for time and date supplied by the caller are not checked forvalidity.

See Also ajtdg

318 KADAK AMX 86 Procedures

ajtick ajtick

Purpose Read System Tick Counter

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned long tickcnt;..

tickcnt = ajtick();DX:AX

Results Interrupts are untouched.

tickcnt is the current value of the AMX system tick counter.

Note The AMX system tick counter is set to 0 when your AMX system islaunched. It is incremented once for every elapsed system tick. It wrapsfrom 232-1 to 0.

AMX 86 Procedures KADAK 319

ajtkcre ajtkcre

Purpose Create a New Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxtdts tdt;AMXID taskid;int status;..

status = ajtkcre(&tdt, &taskid);AX ES:BX DX=

Where &tdt is a pointer to the task's definition. All fields in structure tdt mustbe valid before ajtkcre is called.

The structure amxtdts is defined in header file AMX831SD.H (seeAppendix D). The fields in the task definition structure correspond tothe parameters you must enter in the Task Definition window topredefine a task using the Configuration Manager (see Chapter 14.7).

The task attributes in structure member amtdtat must be set to 0 tocreate a Large model task or to 1 to create a Medium model task. Ifyou create a Medium model task, the task's stack MUST be located inthe DGROUP data segment.

&taskid is a pointer to storage for the task id of the created task.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNTC = No free Task Control Block availableAERITP = Invalid task priority (0 or > 127)AERMBZ = Invalid task mailbox depth (<0 or > 32767)

If the task cannot be created, taskid will be undefined.

See Also ajtkdel

320 KADAK AMX 86 Procedures

ajtkdel ajtkdel

Purpose Delete a Task

This procedure removes a task from your AMX system. Its task id will nolonger be valid.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;int status;..

status = ajtkdel(taskid, priority);AX DX CX

Where taskid is the task id of the task to be deleted.

priority is the task execution priority at which the deletion is to occur.The deletion priority must be lower than the priority of any task whichcan affect the task being deleted. The deletion priority must be higherthan the priority of any permanently active compute bound task.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERANA = Task deletion is not allowed

The task has not yet given its permission to be deleted by calling ajtktrm to specify a Task Termination Procedure.

A task can delete itself.

Restriction You must not delete a task which is waiting, or is about to wait, for aresource or counting semaphore, events in an event group or a message ona message exchange. Failure to observe this restriction may lead tounexpected and unpredictable faults.

See Also ajtkcre, ajtktrm

AMX 86 Procedures KADAK 321

ajtkid ajtkid

Purpose Get Task Id of Current Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;..

taskid = ajtkid();AX

Where taskid is the task id of the currently executing task.

Results Interrupts are untouched.

See Also ajtktcb, ajtktag

322 KADAK AMX 86 Procedures

ajtkill ajtkill

Purpose Kill a Task

This procedure will force a ready, executing or suspended task to end. Allmessages in the task's mailboxes at the time of the kill request will beflushed. All requests for task execution pending at the time of the killrequest will be erased.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajtkill(taskid);AX DX

Where taskid is the task id of the task to be killed.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERANA = Task termination is not allowed

The task has not yet given its permission to be killed by calling ajtktrm to specify a Task Termination Procedure.

Any task which is waiting for the task being killed to acknowledge receiptof its message sent via ajsenw will be allowed to resume execution.

A task can kill itself.

Restriction You must not kill a task which is waiting, or is about to wait, for aresource or counting semaphore, events in an event group or a message ona message exchange. Failure to observe this restriction may lead tounexpected and unpredictable faults.

See Also ajtkstp, ajtkdel, ajtktrm

AMX 86 Procedures KADAK 323

ajtkpry ajtkpry

Purpose Change Task Priority

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int priority;int status;..

status = ajtkpry(taskid, priority);AX DX CX

Where taskid is the task id of the task whose priority is to be changed.

priority is the desired priority of the task (1 to 127).

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERITP = Invalid task priority (0 or > 127)

See Also ajtkcre, ajtkdel

324 KADAK AMX 86 Procedures

ajtkstp ajtkstp

Purpose Stop Execution of Task

This procedure will force a ready, executing or suspended task to end.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajtkstp(taskid);AX DX

Where taskid is the task id of the task to be stopped.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERANA = Task termination is not allowed

The task has not yet given its permission to be stopped by calling ajtktrm to specify a Task Termination Procedure.

If a task is waiting for the task being stopped to acknowledge receipt of itsmessage sent via ajsenw, that task will be allowed to resume execution.

A task can stop itself.

Restriction You must not stop a task which is waiting, or is about to wait, for aresource or counting semaphore, events in an event group or a message ona message exchange. Failure to observe this restriction may lead tounexpected and unpredictable faults.

See Also ajtkill, ajtkdel, ajtktrm

AMX 86 Procedures KADAK 325

ajtksts ajtksts

Purpose Get Status of a Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxsbs tasksts;AMXID taskid;int status;..

status = ajtksts(taskid, &tasksts);AX DX ES:BX

Where taskid is the task id of the task for which status is required.

&tasksts is a pointer to storage for the task status.

The structure amxsbs is defined in header file AMX831SD.H (seeAppendix D).

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

If the call is unsuccessful, the task status in tasksts is undefined.

326 KADAK AMX 86 Procedures

ajtktag ajtktag

Purpose Find a Task

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup char tag[4];AMXID taskid;int status;..

status = ajtktag(&taskid, tag);AX DX= [CX:DX] see note

Where &taskid is a pointer to storage for the task id of the task of interest.

tag is a pointer to a 4-character name identifying the task of interest.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERNST = No task with matching task tag can be found

If more than one task was created with the same task tag, you will get backthe task id of one of them, but which one is not certain.

If the task with the given tag cannot be located, the task id in taskid willbe undefined.

Task tags are 4 characters long. All characters must match your search tagexactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajtkid, ajtktcb, ajtkcre

AMX 86 Procedures KADAK 327

ajtktcb ajtktcb

Purpose Get Task Control Block Pointer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxtcbs *tcbp;AMXID taskid;int status;..

status = ajtktcb(taskid, &tcbp);AX DX ES:BX=

Where taskid is the task id of the task for which the Task Control Block pointeris required.

&tcbp is a pointer to storage for the pointer to the Task Control Block.

The structure amxtcbs is defined in header file AMX831SD.H (seeAppendix D).

Results Interrupts are untouched.

If the taskid is invalid, NULL (0L) is returned in tcbp.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

Do not use the Task Control Block pointer provided by this procedure ifthere is any chance that the corresponding task could be deleted while theTCB pointer is in your possession.

See Also ajtkid, ajtktag, ajtkdel

328 KADAK AMX 86 Procedures

ajtktrm ajtktrm

Purpose Enable/Disable External Task Termination

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;void ttproc();int status;..

status = ajtktrm(taskid, ttproc);AX DX ES:BX

Where taskid is the task id of the task whose Termination Procedure is to be set.

ttproc is a pointer to the Task Termination Procedure which is to beexecuted by the task whenever the task is stopped, killed or deleted(see ajtkstp, ajtkill, ajtkdel).

If ttproc = NULL (0L), termination of the task is inhibited until a validTask Termination Procedure is set with ajtktrm.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERNST = Invalid task idAERANA = Installation is not allowed

The task is in the process of being stopped, killed or deleted.

See Also ajtkdel, ajtkstp, ajtkill

AMX 86 Procedures KADAK 329

ajtmcnv ajtmcnv

Purpose Convert Milliseconds to System Ticks

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned long ms;long ntick;..

ntick = ajtmcnv(ms);DX:CX DX:CX

Where ms is the number of milliseconds.

ntick is the equivalent interval in AMX system ticks.

Results Interrupts are untouched.

ntick is the interval value in system ticks.

If the clock frequency is such that ms milliseconds requires more than 231

system ticks, ntick will be set to 231-1.

If the clock frequency is such that ms milliseconds is less than one half ofa system tick, ntick will be set to 0.

Note This procedure is frequently used when starting a timer as in the followingexamples:

ajtmwr(ajtmcnv(ms));ajwatm(ajtmcnv(ms));

Avoid using this procedure in ISPs or Timer Procedures where executionspeed is critical. For example, if an ISP must start a timer, use ajtmcnvduring initialization to derive ntick. The ISP can then use ntick to startthe timer without the execution penalty imposed by ajtmcnv.

330 KADAK AMX 86 Procedures

ajtmcre ajtmcre

Purpose Create an Interval Timer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup void tproc();AMXID timerid;long tperiod;struct tuser *tparam;char tag[4];int status;..

status = ajtmcre(&timerid, tperiod, tproc, tparam, tag);AX DX= ES:BX is A(Timer Definition Structure)

See structure AMXTMS defined in header file AMX831SD.DEF (see Appendix D).

Where &timerid is a pointer to storage for the timer id of the timer allocated tothe caller.

tperiod is the timer interval (in AMX system ticks) to be used if the timeris periodic. Tperiod must be positive. tperiod = 0 for a one-shottimer.

tproc is a pointer to the Timer Procedure to be executed whenever thetimer expires.

tparam is a 4-byte parameter which will be passed to the Timer Procedurewhenever it is called by AMX. It is usually a pointer to someapplication variable or structure such as tuser in the above example.

tag is a 4-character name tag for the timer.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNTM = No free timerAERTMV = Invalid period (<0)

If the call is unsuccessful, timerid is undefined.

Note Creating an interval timer does not automatically start the timer. Useajtmwr to start the timer.

See Also ajtmdel, ajtmtag

AMX 86 Procedures KADAK 331

ajtmdel ajtmdel

Purpose Delete an Interval Timer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID timerid;..

status = ajtmdel(timerid);AX DX

Where timerid is the timer id identifying the timer to be deleted.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSTM = Invalid timer id

Note A Timer Procedure can delete the interval timer with which it isassociated.

An active interval timer can be deleted.

Restriction You must be absolutely certain that no other task, ISP or Timer Procedureis in any way using or about to use the interval timer. Failure to observethis restriction may lead to unexpected and unpredictable faults.

See Also ajtmcre

332 KADAK AMX 86 Procedures

ajtmrd ajtmrd

Purpose Read the Current Value of an Interval Timer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID timerid;long tval;..

tval = ajtmrd(timerid);DX:CX DX

Where timerid is the timer id identifying the timer whose value is required.

tval is the timer value in system ticks.

Results Interrupts are disabled and then restored to their state at the time of thecall.

tval >= 0 Call successfultval is the current timer value measured in AMXsystem ticks. tval is the time remaining before thetimer expires.

tval < 0 Call not successful (tval is an error code)

tval = AERNSTM Invalid timer id

See Also ajtmcre, ajtmdel, ajtmwr

AMX 86 Procedures KADAK 333

ajtmtag ajtmtag

Purpose Find an Interval Timer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID timerid;char tag[4];int status;..

status = ajtmtag(&timerid, tag);AX DX= [DX:CX] see note

Where &timerid is a pointer to storage for the timer id of the interval timer ofinterest.

tag is a pointer to a 4-character name identifying the timer of interest.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSTM = No timer with matching tag can be found

If more than one timer was created with the same tag, you will get backthe timer id of one of them, but which one is not certain.

If an interval timer with the given tag cannot be located, the timer id intimerid will be undefined.

Timer tags are 4 characters long. All characters must match your searchtag exactly.

Note A tag 'ABCD' is presented in register DX:CX with 'A' in CL and 'D' inDH.

See Also ajtmcre

334 KADAK AMX 86 Procedures

ajtmwr ajtmwr

Purpose Start/Stop an Interval Timer

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID timerid;long tval;int status;..

status = ajtmwr(timerid, tval);AX DX BX:CX

Where timerid is the timer id identifying the timer to be started or stopped.

tval is the timer interval measured in AMX system ticks. Tval must bepositive. Set tval to 0 to stop a timer.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNSTM = Invalid timer idAERTMV = Invalid interval (<0)

Note A Timer Procedure associated with a periodic timer can stop the timer bycalling ajtmwr with tval = 0. The periodic timer can be restarted bycalling ajtmwr with tval = n. The timer will expire after n system ticksand resume periodic operation with its predefined period.

Non periodic timers (one-shots) can be retriggered by their associatedTimer Procedure using ajtmwr to restart the timer.

See Also ajtmcre, ajtmrd

AMX 86 Procedures KADAK 335

ajtrig ajtrig

Purpose Trigger a Task

To request AMX to start a task without sending a message to the task.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajtrig(taskid);AX DX

Where taskid is the task id of the task to be triggered.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

An immediate task switch will occur if the task being triggered is ofhigher priority than the current task.

See Also ajsend, ajend

336 KADAK AMX 86 Procedures

ajtslv ajtslv

Purpose Change a Task's Time Slice Interval

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;unsigned int tslice;int status;..

status = ajtslv(taskid, tslice);AX DX CX

Where taskid is the task id of the task whose time slice interval is to be altered.

tslice is the new time slice interval in AMX system ticks.(0 <= tslice < 65536)Set tslice to 0 to stop time slicing the task.

Results Interrupts are untouched.

Status is returned.AEROK = Call successfulAERNST = Invalid task id

See Also ajtson, ajtsof

AMX 86 Procedures KADAK 337

ajtsof ajtsofajtson ajtson

Purpose Disable Time SlicingEnable Time Slicing

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajtsof(); /* Disable time slicing */orajtson(); /* Enable time slicing */

Results Interrupts are untouched.

See Also ajtslv

338 KADAK AMX 86 Procedures

ajupt ajupt

Purpose Fetch Pointer to User Parameter Table

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup #include "amx831sd.h"..

struct amxupts FAR *uptp; /* User Parameter Table pointer */..

ajupt(&uptp);

Where &uptp is a FAR pointer to storage for a FAR pointer to your system's UserParameter Table.

The structure amxupts is defined in header file AMX831SD.H (seeAppendix D).

Results Interrupts are untouched.

Note This function must be called from your main() program to fetch the UserParameter Table pointer for use in the call to ajentr() to launch AMX.

AMX 86 Procedures KADAK 339

ajver ajver

Purpose Get AMX Version Number

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup unsigned long version;..

version = ajver();DX:AX

Where version is the AMX version number in the hexadecimal format0x0086rrmm whererr is the major revision number (03)mm is the minor revision number (00)

Results Interrupts are untouched.

340 KADAK AMX 86 Procedures

ajwait ajwait

Purpose Wait Unconditionally for a Wake Request

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajwait();

Results Interrupts are enabled.

The task will be suspended until some other task, ISP or Timer Procedureissues an ajwake call to wake this task.

If a task has an outstanding wake request pending when it calls ajwait,the task will continue execution immediately without waiting.

If there is any possibility that some task, ISP or Timer Procedure hasalready issued an ajwake call to wake this task, you should call ajwapr toreset any pending wake request before calling ajwait.

Note This procedure provides a simplified form of the task signal wait withouttimeout (see ajsgwat).

See Also ajwatm, ajwake, ajwapr, ajsgwat

AMX 86 Procedures KADAK 341

ajwakc ajwakc

Purpose Wake Calling Task (Acknowledge Receipt of Message)

To allow the current task to wake up the task which sent the messagewhich is being processed by the current task.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int status;..

status = ajwakc();AX

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERCNW = Task which sent the message is not waitingAERNMT = Current task is not processing a received message from

another task.

An immediate task switch will occur if the task being wakened is of higherpriority than the current task.

Note This procedure is equivalent to a call to ajwakcs to return a value ofAEROK (0) to the calling task.

See Also ajsenw, ajend, ajwakcs

342 KADAK AMX 86 Procedures

ajwakcs ajwakcs

Purpose Wake Calling Task (Acknowledge Receipt of Message with Status)

To allow the current task to wake up the task which sent the messagewhich is being processed by the current task and return completion statusto that task.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup int status;int result;..

status = ajwakcs(result);AX CX

Where result is an integer value (>=0) to be returned to the calling task.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERCNW = Task which sent the message is not waiting.AERNMT = Current task is not processing a received message from

another task.AERIRS = Invalid result status (result < 0)

The message sender was not wakened.

An immediate task switch will occur if the task being wakened is of higherpriority than the current task.

Note Calling this procedure with result = AEROK (0) is equivalent to a call toprocedure ajwakc.

See Also ajsenw, ajend, ajwakc

AMX 86 Procedures KADAK 343

ajwake ajwake

Purpose Wake a Waiting Task

To wake up a task known to be waiting because of an ajwait or ajwatmcall.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup AMXID taskid;int status;..

status = ajwake(taskid);AX DX

Where taskid is the task id of the task to be wakened.

Results Interrupts are disabled and then restored to their state at the time of thecall.

Status is returned.AEROK = Call successfulAERWKP = Warning: Task was not waiting

Wake request is now pending

AERNST = Invalid task idAERTNW = Task was not waiting and a wake request was already

pending before this ajwake call

An immediate task switch will occur if the task being wakened is of higherpriority than the current task.

Note This procedure provides a simplified form of task signalling (see ajsgnl).

See Also ajwait, ajwatm, ajwapr, ajsgnl

344 KADAK AMX 86 Procedures

ajwapr ajwapr

Purpose Reset a Pending Wake Request

This call only affects the calling task.

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup ajwapr();

Results Interrupts are untouched.

Note This procedure provides a simplified form of task signal reset (seeajsgres).

See Also ajwait, ajwatm, ajwake, ajsgres

AMX 86 Procedures KADAK 345

ajwatm ajwatm

Purpose Task Delay or Timed Wait for a Wake Request

Used by � Task � ISP � Timer Procedure � Restart Procedure � Exit Procedure

Setup long tval;int status;..

status = ajwatm(tval);AX DX:CX

Where tval is the required wait interval or delay period measured in AMXsystem ticks. Tval must be positive. If tval = 0, the caller will notwait.

Results Interrupts are enabled.

Status is returned.AEROK = Call successful

Task waited for entire intervalAERWBT = Task wakened before interval expiredAERTMV = Invalid interval (<0)

The caller is allowed to resume execution and its task timer is stopped assoon as another task, ISP or Timer Procedure issues an ajwake callspecifying this task.

If a task has an outstanding wake request pending when it calls ajwatm,the task will continue execution immediately without waiting.

If there is any possibility that some task, ISP or Timer Procedure hasalready issued an ajwake call to wake this task, you should call ajwapr toreset any pending wake request before calling ajwatm.

Note This procedure provides a simplified form of the task signal wait withtimeout (see ajsgwat).

If you want to do a task delay with no ajwake interference, use ajsgwatwith a task signal mask of 0.

See Also ajwait, ajwake, ajwapr, ajsgwat

346 KADAK AMX 86 Procedures

This page left blank intentionally.

AMX 86 Reserved Words KADAK 347

A. AMX 86 Reserved Words

ajpppppp AMX C procedure name ppppppAAPPPPPP AMX assembly language procedure name PPPPPPamxttttt AMX C structure name of type ttttt

AMXID AMX object identifier (handle)cdecl Procedures use C parameter passing conventionsAMssssss Reserved symbols defined in AMX header files

AERxxxxx AMX Error Code xxxxxAERWxxxx AMX Warning Code xxxxAERFxxxx AMX Fatal Exit Code xxxx

AA831FFF.XXX AMX 86 filenamesAM831FFF.XXXAMX831FF.XXXAJ831FFF.XXX AMX 86 C Interface filenamesAA832FFF.XXX AMX 86 PC Supervisor filenames

348 KADAK AMX 86 Reserved Words

This page left blank intentionally.

AMX 86 Error Codes KADAK 349

B. AMX 86 Error CodesAMX error codes are signed integers. Codes less than zero are error codes. Codesgreater than zero are warning codes. To assist you during testing, the hexadecimal valueof the least significant 16-bits of the error code is listed as it might appear in a register ormemory dump.

Mnemonic Value Value Meaning(dec) (hex)

AEROK * 0 0 Call successfulAERNST -1 0xFFFF No such task (invalid task id)AERNME -2 0xFFFE No free message envelopeAERNMB -3 0xFFFD No mailbox (message queue) definedAERMBF -4 0xFFFC Mailbox (message queue) fullAERWBT * -5 0xFFFB Wakened before timeoutAERTNW * -6 0xFFFA Task not waiting (after 2nd wake)AERCNW * -7 0xFFF9 Calling task not waitingAERNMT -8 0xFFF8 Message not from task AASEND call

-9 0xFFF7 reserved

-10 0xFFF6 reserved-11 0xFFF5 reserved

AERRNY -12 0xFFF4 Resource not owned by you (caller)AERNSP -13 0xFFF3 No such buffer pool (invalid buffer pool id)AERBTS -14 0xFFF2 Buffer too smallAERBNU -15 0xFFF1 Buffer not in useAERBUV -16 0xFFF0 Buffer use count overflowAERITP -17 0xFFEF Invalid task priorityAERNTC -18 0xFFEE No free Task Control BlockAERNTM -19 0xFFED No free interval timer

AERANA -20 0xFFEC Task abort (stop, kill, delete) not allowedAERIPR -21 0xFFEB Cannot read/write IVT (no IVT access provided)AERNSS -22 0xFFEA No such semaphore (invalid semaphore id)AERSIU * -23 0xFFE9 Semaphore in useAERISV -24 0xFFE8 Invalid semaphore value

-25 0xFFE7 reserved-26 0xFFE6 reserved

AERTMO * -27 0xFFE5 Timed outAERNMG * -28 0xFFE4 No message availableAERCWT * -29 0xFFE3 Calling task still waiting

* Errors so marked are not trapped to your User Error Procedure.

350 KADAK AMX 86 Error Codes

AMX 86 Error Codes (continued)

Mnemonic Value Value Meaning(dec) (hex)

AERNBF -30 0xFFE2 No buffers definedAERNFP -31 0xFFE1 No free buffer poolAERNEB -32 0xFFE0 No free event groupAEREVU -33 0xFFDF Event group in use

-34 0xFFDE reserved-35 0xFFDD reserved-36 0xFFDC reserved

AERMNA * -37 0xFFDB Memory not availableAERMIB -38 0xFFDA Invalid memory block pointerAERMNU -39 0xFFD9 Memory block not in use

AERMOV -40 0xFFD8 Memory block use count overflowAERNSX -41 0xFFD7 No such message exchange

(invalid message exchange id)AERNXB -42 0xFFD6 No free message exchangeAERXIU -43 0xFFD5 Message exchange in useAERMBZ -44 0xFFD4 Invalid mailbox (message queue) sizeAERNSB -45 0xFFD3 No free semaphoreAERNSG -46 0xFFD2 No such event group (invalid event group id)AERNSTM -47 0xFFD1 No such timer (invalid timer id)AERTMV -48 0xFFD0 Invalid timing intervalAERIRS -49 0xFFCF Invalid result status (AAWAKCS)

AERMMV -50 0xFFCE Memory fill exceeds segment limitAERSBY * -51 0xFFCD Semaphore is busyAERITT -52 0xFFCC Invalid task trap interrupt type

* Errors so marked are not trapped to your User Error Procedure.

AMX 86 Warning Codes

Mnemonic Value Value Meaning(dec) (hex)

AERWNB * 1 0x0001 No buffer availableAERWKP * 2 0x0002 Task not waiting; wake is pendingAERCWT * 3 0x0003 Calling task is still waiting

* Warnings so marked are not trapped to your User Error Procedure.

AMX 86 Error Codes KADAK 351

AMX 86 Fatal Exit Codes

Mnemonic Value Value Meaning(dec) (hex)

AERFX1 ● 1 0x0001 Not enough memory in AMX Data SegmentAERFX2 ● 2 0x0002 Divide, overflow, bound error in ISPAERFX3 ● 3 0x0003 Divide, overflow, bound error occurred:

in a Restart Procedure orin a Timer Procedure orin a task with no task trap handler

AERFX4 ● 4 0x0004 Attempt to exit from a permanent AMX systemAERFX5 ● 5 0x0005 reservedAERFX6 ● 6 0x0006 ROMed AMX kernel received a request which

it is not configured to handle or20/24-bit Memory Manager library mismatch

AERFX7 ● 7 0x0007 Invalid AMX Configuration parameters:User message size not multiple of 4 or < 12 bytesKernel Stack size < minimum of 128 bytesInterrupt Stack size < minimum of 128 bytesNumber of tasks exceeds maximum of 100

AERFX8 ● 8 0x0008 Launch cannot create predefined task or timer:Invalid task definitionMaximum number of tasks allowed is too smallInvalid timer definitionMaximum number of timers allowed is too small

AERFX9 ● 9 0x0009 Nested breakpoint encounteredAERFX10 ● 10 0x000A Cannot breakpoint on ISPAERFX11 ● 11 0x000B Breakpoint Manager cannot install vectors in IVT

Managers fail during launch:AERFXSM ● 12 0x000C Cannot create predefined semaphoreAERFXEM ● 13 0x000D Cannot create predefined event groupAERFXXM ● 14 0x000E Cannot create predefined message exchangeAERFXBM ● 15 0x000F Cannot create predefined buffer pool

● All fatal errors are trapped to your Fatal Exit Procedure.

352 KADAK AMX 86 Error Codes

This page left blank intentionally.

Generator Specifications KADAK 353

C. Configuration Generator Specifications

C.1 IntroductionIf you are not doing your software development on a PC or compatible runningMicrosoft® Windows®, then you will be unable to use the interactive ConfigurationManager for Windows to create and edit your AMX System Configuration Module. Youmay, however, still be able to use the Configuration Generator to assist you in thisprocess by porting it to your development system as described in Appendix C.4.

As described in Chapter 14.2, the Configuration Generator merges the information fromyour User Parameter File with a template of a standard System Configuration Module toproduce your module. Since the User Parameter File is a text file, you are free to use thetext editor of your choice to create and/or edit this file.

The System Configuration Template provided with the Builder has been coded usingMicrosoft's MASM Assembly Language. Some of the language syntax used by Microsoftmakes this module incompatible with Intel's ASM86 Macro Assembly Language. If youare not using an assembler from one of the toolsets supported by KADAK to assembleyour System Configuration Module, you may have to edit the template file to reflect thecapabilities of your particular assembler.

For these reasons, source code of the template file and the Configuration Generatorprogram has been provided with AMX to allow the Configuration Generator to be portedto your software development environment.

To assist you in this process, the specifications for the User Parameter File and theSystem Configuration Template are presented in this appendix.

354 KADAK Generator Specifications

C.2 User Parameter File SpecificationThe User Parameter File is a text file structured as illustrated in Figure C.2-1. The fileconsists of a sequence of keywords of the form ...XXX which begin in column one. Eachkeyword is followed by one or more parameters which you must provide.

; Constant definitions...UPT NME,UMS,CLP,CLF,NTK,NTM...STK ESS,ISS...OPT TSLICE,NSM,NEV,NMX,NBP,ROMS,CAT,BKPT;; Time/Date Manager selection...TAD UPSHED;; Your Fatal Exit Procedure and User Error Procedure...FEX UPFEX,UPERR;; Your task definitions...TDT TKPROC,TKTAG,ATTR,STACK,PRIORITY,SLICE,MB0,MB1,MB2,MB3,TKID;; Your Restart Procedures...RRX UPRRP;; Your Exit Procedures...EXX UPEXP;; Your interval timer definitions...TMR TMPROC,PERIOD,PARAM,TMTAG,TMID;; Your semaphore definitions...SEM SMVAL,SMTAG,SMID;; Your event group definitions...EVG EVAL,EVTAG,EVID;; Your message exchange definitions...MEX MBO,MB1,MB2,MB3,MXTAG,MXID;; Your buffer pool definitions...PDT BPN,BPS,BPTAG,BPID;; Memory Manager options...MAL UPMAP;; Configuration extension parameters...EXT X1,X2,DBGA,BPED,BPXD,PCSOPT

Figure C.2-1 User Parameter File

Generator Specifications KADAK 355

The example in Figure C.2-1 uses symbolic names for all of the parameters followingeach of the keywords. The symbols correspond to the screen fields described in Chapter14. You are referred to that chapter for detailed descriptions of each of the parameters.

The order of keywords in the User Parameter File is not particularly critical. Forconvenience, the keywords have been ordered to closely follow the order of thecorresponding entries in your System Configuration Module.

The file begins with a set of constant definitions.

NME Number of message envelopesUMS Size of AMX messageCLP AMX clock period (in hardware ticks)CLF Hardware clock frequency (hz)NTK Maximum number of tasksNTM Maximum number of timersESS AMX Kernel Stack sizeISS AMX Interrupt Stack sizeTSLICE Time slice option (0 = No; 1 = Yes)NSM Maximum number of semaphoresNEV Maximum number of event groupsNMX Maximum number of message exchangesNBP Maximum number of buffer poolsROMS AMX is installed in separate ROM (0 = No; 1 = Yes)CAT AMX configuration attributesBKPT AMX Breakpoint Manager used (0 = No; 1 = Yes)

The Time/Date Manager is selected as follows. If you have provided a Time/DateScheduling Procedure, include its name as illustrated. If you do not have such aprocedure, omit the name but keep the line with keyword ...TAD.

If you do not want to use the Time/Date Manager, delete the line with keyword ...TAD.

If you have a Fatal Exit Procedure, define its name in place of UPFEX. If you do nothave such a procedure, leave the name blank. Leave the comma present.

If you have a User Error Procedure, define its name in place of UPERR. If you do nothave such a procedure, leave the name blank. Leave the comma present.

356 KADAK Generator Specifications

Each of your predefined tasks must be defined using keyword ...TDT. The order ofthese definitions will determine their order of creation by AMX. If you do not wish topredefine any tasks, delete the line with keyword ...TDT.

The parameters in each task definition are as follows.

TKPROC Task procedure nameTKTAG Task tagATTR AttributesSTACK Task stack size (bytes)PRIORITY Task prioritySLICE Time slice intervalMB0 Mailbox 0 depthMB1 Mailbox 1 depthMB2 Mailbox 2 depthMB3 Mailbox 3 depthTKID Task id variable name

Note that the task tag must include exactly four displayable characters. Spaces and tabsare not allowed.

Define all of your Restart Procedures in the order in which you wish them to beexecuted. Note that you are only defining your own procedures. Restart Proceduresrequired by any of the AMX Managers will automatically be installed for you.

Define all of your Exit Procedures in the order in which you wish them to be executed.If you have no Exit Procedures, omit the line containing keyword ...EXX.

Each of your predefined interval timers must be defined using the keyword ...TMR.The order of these definitions will determine their order of creation by AMX. If you donot wish to predefine any timers, delete the line with keyword ...TMR.

The parameters in each timer definition are as follows:

TMPROC Timer Procedure namePERIOD Timer period in system ticks (0 = oneshot)PARAM Parameter variable nameTMTAG Timer tagTMID Timer id variable name

Note that the timer tag must include exactly four displayable characters. Spaces and tabsare not allowed.

Generator Specifications KADAK 357

Each of your predefined semaphores must be defined using the keyword ...SEM. Theorder of these definitions will determine their order of creation by AMX. If you do notwish to predefine any semaphores, delete the line with keyword ...SEM.

The parameters in each semaphore definition are as follows:

SMVAL Initial semaphore value- 1 for resource semaphore>=0 for counting semaphore

SMTAG Semaphore tagSMID Semaphore id variable name

Note that the semaphore tag must include exactly four displayable characters. Spaces andtabs are not allowed.

Each of your predefined event groups must be defined using the keyword ...EVG. Theorder of these definitions will determine their order of creation by AMX. If you do notwish to predefine any event groups, delete the line with keyword ...EVG.

The parameters in each event group definition are as follows:

EVAL Initial value of 16 event flags (signed decimal number)EVTAG Event group tagEVID Event group id variable name

Note that the event group tag must include exactly four displayable characters. Spacesand tabs are not allowed.

358 KADAK Generator Specifications

Each of your predefined message exchanges must be defined using the keyword ...MEX.The order of these definitions will determine their order of creation by AMX. If you donot wish to predefine any message exchanges, delete the line with keyword ...MEX.

The parameters in each message exchange definition are as follows:

MB0 Mailbox 0 depthMB1 Mailbox 1 depthMB2 Mailbox 2 depthMB3 Mailbox 3 depthMXTAG Message exchange tagMXID Message exchange id variable name

Note that the message exchange tag must include exactly four displayable characters.Spaces and tabs are not allowed.

Each of your predefined buffer pools must be defined using the keyword ...PDT. Theorder of these definitions will determine their order of creation by AMX. If you do notwish to predefine any buffer pools, delete the line with keyword ...PDT.

The parameters in each buffer pool definition are as follows:

BPN Number of buffers in the buffer poolBPS Size in bytes of each bufferBPTAG Buffer pool tagBPID Buffer pool id variable name

Note that the buffer pool tag must include exactly four displayable characters. Spacesand tabs are not allowed.

If you intend to use the Memory Manager, replace symbol UPMAP with the name of yourMemory Assignment Procedure.

If you do not wish to use the Memory Manager, omit the line containing keyword...MAL.

The configuration extensions specified by directive ...EXT are defined in the toolsetdependent chapters of the AMX 86 Tool Guide. Parameters BPED and BPXD provide thebreakpoint entry and exit delays for the Breakpoint Manager. Parameter PCSOPT providesadditional attributes for the AMX 86 PC Supervisor.

Generator Specifications KADAK 359

C.3 System Configuration TemplateThe System Configuration Template is an assembly language source file which defines aSystem Configuration Module for any system using AMX and its managers. It isrecommended that you list file AM831CG.CT and examine it carefully before trying to readthis description.

The template file consists of KADAK macro definitions for all of the various componentsof a System Configuration Module. The macro definitions are followed by codegenerating instances of these macros. Conditional assembly is used to inhibit elements inthe module which are not required if the corresponding AMX option has not beenselected.

A KADAK macro consists of a macro definition statement, a body of source languagestatements and directives and a macro end statement. The macro definition and endstatements are a special pair of directives defined by KADAK.

A simple example is shown below.

;~...MAC ...TMR PROC,PERIOD,PARAM,TAG,TMIDEXTRN ~1~:FAR ;Timer ProcedureIF ~P3~EXTRN ~3~:FAR ;Timer parameterENDIF

;~...ENDM

The macro definition statement contains a macro directive ([~...MAC), a parameterkeyword (...TMR) and an optional comment string (PROC,PERIOD,etc.). These threefields are separated by one or more space and/or tab characters.

The macro directive must start in the first column. The first character of the directivemust be the comment character used by the assembler. For Intel compatible assemblers,that character is ;.

The second character in the directive is the parameter delimiter character. This can beany printable character but is reserved exclusively for identifying parameters within thebody of the macro. It must not appear in any other context within the macro body. Forinstance, we could not have used the character : since it appears in the EXTRN directives.We have chosen the character ~ because it is not required in any of the macro definitionsin the System Configuration Template.

Immediately after the parameter delimiter character comes the macro definition keyword...MAC.

The parameter keyword (...TMR) identifies a particular keyword in the User ParameterFile which contains the parameter list needed for expansion of the macro body.

The comment string is optional and is normally used to provide a descriptive list of themacro parameters. The comment string is not used in the parameter substitution process.

360 KADAK Generator Specifications

Macro parameters appear in the macro body as parameter identifiers. A parameteridentifier is a decimal integer preceded and followed by the delimiter character defined inthe macro definition statement (~1~, ~2~, etc.). The number identifies the parameter inthe particular parameter list specified by the parameter keyword. The parameter is copiedfrom the User Parameter File into the source language macro body replacing theparticular identifier. The parameters are numbered 1 to n from left to right in theparameter list following the keyword in the User Parameter File.

A second form of macro parameter has the letter P preceding the number in the parameteridentifier, as in the IF statement in the example. This form directs the ConfigurationGenerator to replace the parameter identifier with the character 1 if the identifiedparameter is present in the parameter list. If the parameter is missing from the parameterlist, the Configuration Generator replaces the parameter identifier with the character 0.

In the above example the macro requires the first and third parameter values from a linein the User Parameter File containing the keyword ...TMR. If the third parameter ismissing from the keyword parameter list in the User Parameter File, the IF statement willbe false, inhibiting the assembler directive EXTRN which, without valid arguments, wouldproduce an assembler error.

The macro is terminated by the macro end directive containing the macro keyword...ENDM.

When the Configuration Generator encounters a macro definition in the SystemConfiguration Template File, it scans the User Parameter File for a matching parameterkeyword. The macro body is expanded and copied into the System ConfigurationModule File once for each matching parameter keyword located in the User ParameterFile.

A third type of directive is used to define an incremental integer variable. Anincremental variable is defined with an initial value and an increment which is added tothe variable each time a macro containing the variable is expanded by the ConfigurationGenerator. Note that this ;~...VAR directive begins with the assembler commentcharacter and the parameter delimiter character required by all KADAK macro directives.The variable name is a string of printable characters preceded and followed by one ormore space and/or tab characters. Although only one incremental variable is allowed, itsname, initial value and increment can be redefined and used with other macros.

The example below illustrates the use of an incremental variable.

;~...VAR &TN 1,1 ;start at task 1;~...MAC ...TDT PROC,TAG,ATTR,STACK,PR,SLICE,MB0,MB1,MB2,MB3,TKID;

DD (~4~+3)/4 DUP(?)@L@K&TN LABEL WORD ;Initial stack pointer; ;for task &TN (tag ~2~);~...ENDM

Generator Specifications KADAK 361

The first statement in this example is a directive defining an incremental variable named&TN. Both its initial value and increment are 1. Note that this directive begins with theassembler comment character (;) and the parameter delimiter character (~ in thisexample) required by all KADAK macro directives. The variable name is a string ofprintable characters preceded and followed by one or more space and/or tab characters.

Each time the Configuration Generator expands the macro, the current value of theincremental variable is substituted for the variable name wherever it appears within themacro body. For example, assume that the fifth task definition in the User Parameter Fileis listed as follows:

...TDT taskproc5,TSK5,0,2048,20,0,0,0,0,0,task5id

When the Configuration Generator encounters this task definition, the current value ofthe incremental variable &TN will be 5. Therefore the body of the macro will be expandedas follows:

;DD (2048+3)/4 DUP(?)

@L@K5 LABEL WORD ;Initial stack pointer; ;for task 5 (tag TSK5)

Note that the value of the incremental variable is not updated by its increment until afterthe macro end directive is encountered.

To gain a better insight to this whole process, run the Configuration Manager on a PCeven if you are not doing development on a PC. Use it to create a simple AMX systemwith two or three predefined tasks. Use the manager to generate the SystemConfiguration Module. Then view the User Parameter File and the System ConfigurationModule produced by the Configuration Manager. Compare the latter file with the SystemConfiguration Template to see exactly how the parameter identifiers have been replacedby parameters from your User Parameter File.

362 KADAK Generator Specifications

C.4 Porting the Configuration GeneratorThe Configuration Manager uses the Configuration Generator to generate your SystemConfiguration Module. If you are not doing your development on a PC or compatible,you may wish to port the Configuration Generator to your development system.

The Configuration Generator is a utility program provided with AMX. The program iswritten in C with portability in mind. Source file AM831CG.C is delivered with AMX.

To port the Configuration Generator to your development system, compile the moduleAM831CG.C using your C compiler. Link the resulting object module with your C Run-Time Library to produce a version of the Configuration Generator which will execute inyour environment.

The command line syntax to run the Configuration Generator is as follows.

AM831CG upfname ctfname scfname -q -w -bsss -esss

upfname User Parameter File filenamectfname System Configuration Template filenamescfname System Configuration Module filename

All three filenames must be present in the order specified. Each must include the fullpath to the file if the file is not in the current directory. Each filename must include bothname and extension.

Command line switches beginning with - are optional and must follow the filenames.

The -q (quiet) switch, if present, will inhibit the display of all informational or errormessages on the standard output device (stdout). This switch is used by theConfiguration Manager to inhibit the Configuration Generator from writing to the displayscreen when it is invoked by the manager.

The Configuration Generator will ignore a KADAK macro in the template file if the UserParameter File contains no instances of the macro keyword. By default, there is noindication in the output file that the unused macro has been stripped. If the -w switch isused, the Configuration Generator will echo the macro definition statement to the outputfile and follow it with the comment "Unused in this configuration".

Generator Specifications KADAK 363

By default, the Configuration Generator uses the macro identification character (; in ourexample) from the macro directive as a comment character to identify the commentsinserted into the output file in response to the -w switch.

This default assumption can be overridden using the -b and -e switches to definealternate comment delimiter strings. The strings sss can be up to 16 characters long.Special characters must be inserted using the character pair ^x for each special character.Special characters are:

^b blank (space) (ASCII 0x20)^t tab (ASCII 0x09)^r return (ASCII 0x0D)^n new-line (ASCII 0x0A)^^ the character ^ (ASCII 0x5E)

Since the System Configuration Module file scfname will be an assembly languagesource file, you should always use the switch -b; with the -w switch to force theConfiguration Generator's comment strings to begin with the assembler commentcharacter (;) in case a macro identification character other than ; is used in macrodirectives within the template file.

For other versions of AMX, the System Configuration Module file scfname is a C sourcefile. For these products, you would use the switches -b/* and -e*/ with the -w switch toforce the Configuration Generator's comment strings to begin and end with theC comment delimiter strings /* and */.

364 KADAK Generator Specifications

This page left blank intentionally.

Structure/Constant Definitions KADAK 365

D. AMX 86 Structure and Constant Definitions

D.1 AMX C Structures and Constants

AMX Launch Parameter (see AAENTR)

#define AMLPTMP 1 /* Temporary launch *//* Default is permanent launch*/

#define AMLPVA 2 /* Vector table is alterable *//* Default is non alterable *//* table */

#define AMLPIE 4 /* Launch with interrupts *//* enabled. Default is *//* interrupts disabled */

AMX Task Definition Structure

struct amxtdts {void (*amtdtst)(); /* task procedure pointer */char amtdtag1; /* 4 char task tag */char amtdtag2;char amtdtag3;char amtdtag4;unsigned int *amtdtsp; /* task stack pointer */unsigned int amtdtskz; /* size of task stack (bytes) */unsigned short int amtdtat; /* task attributes */short int amtdtpr; /* task priority */unsigned short int amtdtslc; /* task time slice */

/* (system ticks) */short int amtdtmb0; /* mailbox level 0 depth */short int amtdtmb1; /* mailbox level 1 depth */short int amtdtmb2; /* mailbox level 2 depth */short int amtdtmb3; /* mailbox level 3 depth */};

AMX Task Control Block Structure

struct amxtcbs {char amtcbrsv[240]; /* private */unsigned long amtcbusr[4]; /* user defined */};

366 KADAK Structure/Constant Definitions

AMX Task Status Block Structure

struct amxsbs {AMXID amsbtid; /* task id */char amsbtag1; /* task tag */char amsbtag2;char amsbtag3;char amsbtag4;unsigned long amsbst; /* task status */unsigned long amsbsig; /* pending signals */long amsbtmr; /* task timer (time remaining)*/unsigned short int amsbslc; /* time slice */unsigned short int amsbcc; /* call count */unsigned short int amsbatr; /* task attributes */AMXID amsbctid; /* caller's task id */

/* (-1=ISP; 0=AATRIG) */short int amsbcwat; /* caller waiting if <> 0 */short int amsbpry; /* task priority */unsigned short int amsbmc0; /* message count; mailbox 0 */unsigned short int amsbmc1; /* message count; mailbox 1 */unsigned short int amsbmc2; /* message count; mailbox 2 */unsigned short int amsbmc3; /* message count; mailbox 3 */};

Task Status Masks (fields amsbst, amsbsig)

#define AMSBWTMR 0x01 /* timer wait *//* (used with other bits) */

#define AMSBWTRG 0x02 /* trigger wait (i.e. idle) */#define AMSBWSEM 0x04 /* semaphore wait */#define AMSBWEVT 0x08 /* event group wait */#define AMSBWXCH 0x10 /* message exchange wait */#define AMSBWSND 0x20 /* message send wait */#define AMSBWSUS 0x40 /* suspended */

/* (waiting for resume) */#define AMSBWWAT 0x80 /* waiting for wake */#define AMSBWSIG 0x7FFF0000L /* 15 task signal waits */#define AMSBWORW 0x80000000L /* OR-wait on AMSBWSIG bits */

Critical Function Codes (passed to Task Termination Procedure)

#define AMCFE 1 /* ajtkstp() - stop (end) task*/#define AMCFK 2 /* ajtkill() - kill task */#define AMCFD 3 /* ajtkdel() - delete task */

Structure/Constant Definitions KADAK 367

AMX Extended Message Parameter Structure

(passed on stack above AMX message when starting a task)

struct amxmsgxs {AMXID amxmscid; /* calling task's id */short int amxmsfn; /* AMX function code */

/* (see definitions) */short int amxmsrsv[4]; /* reserved */};

AMX Function Codes (field amxmsfn)

#define AMXMSFNM 0 /* no message on stack */#define AMXMSFMS 1 /* message on stack */#define AMXMSFMW 2 /* message on stack; */

/* sender waiting */

368 KADAK Structure/Constant Definitions

AMX User Parameter Table Structure

struct amxupts {void (**ampbrpl)(); /* A(Restart Procedure List) */void (**ampbepl)(); /* A(Exit Procedure List) */long ampbcfga; /* Configuration attributes */short int ampbdgrp; /* user's DGROUP segment selector */short int ampbnmev; /* number of message envelopes */short int ampbums; /* user message size (bytes) */void *ampbmes; /* A(Message Envelope Segment) */void *ampbistk; /* A(top of AMX private stacks) */unsigned int ampbesz; /* AMX Kernel Stack size (bytes) */unsigned int ampbisz; /* AMX Interrupt Stack size (bytes) */unsigned int ampblen; /* size of AMX storage (bytes) */short int ampbclkp; /* AMX clock period (in hardware ticks)*/short int ampbclkf; /* hardware clock frequency (hz) */void (*ampbtds)(); /* A(Time/Date Scheduling Procedure) */void (*ampbfex)(); /* A(Fatal Exit Procedure) */void (*ampberr)(); /* A(User Error Procedure) */

short int ampbtkmx; /* maximum number of tasks */short int ampbtkpr; /* number of predefined tasks */void *ampbtkdf; /* A(Task Definition Table) */

short int ampbtmmx; /* maximum number of timers */short int ampbtmpr; /* number of predefined timers */void *ampbtmdf; /* A(Timer Definition Table) */

short int ampbsmmx; /* maximum number of semaphores */short int ampbsmpr; /* number of predefined semaphores */void *ampbsmdf; /* A(Semaphore Definition Table) */

short int ampbevmx; /* maximum number of event groups */short int ampbevpr; /* number of predefined event groups */void *ampbevdf; /* A(Event Group Definition Table) */

short int ampbmxmx; /* maximum number of message exchanges */short int ampbmxpr; /* number of predefined message exchanges*/void *ampbmxdf; /* A(Message Exchange Definition Table)*/

short int ampbbpmx; /* maximum number of buffer pools */short int ampbbppr; /* number of predefined buffer pools */void *ampbbpdf; /* A(Buffer Pool Definition Table) */

int (*ampbmap)(); /* A(Memory Assignment Procedure) */char ampbdmn[16]; /* reserved for InSight */void *ampbpcdt; /* A(PC Supervisor Definition Table) */long ampbdba; /* Debugger attributes */short int ampbped; /* Breakpoint entry delay */short int ampbpxd; /* Breakpoint exit delay */};

Structure/Constant Definitions KADAK 369

Configuration Attributes (field AMPBCFGA)

#define AMCAMTK 1 /* Some Medium tasks */#define AMCAMUP 2 /* Some Medium user procedures*/#define AMCAS24 4 /* Use 24-bit address space */

AMX Time/Date Structure

struct amxtds {unsigned char amtdsec; /* seconds (0-59) */unsigned char amtdmin; /* minutes (0-59) */unsigned char amtdhr; /* hours (0-23) */unsigned char amtddy; /* day (1-31) */unsigned char amtdmn; /* month (1-12) */unsigned char amtdyr; /* year (0-99) */unsigned char amtdow; /* day of week (Mon=1 to Sun=7)*/unsigned char amtdcen; /* 0 if time/date is incorrect*/

/* century if time/date *//* is correct */

};

AMX Timer Definition Structure

struct amxtms {void (*amtmproc)(); /* A(Timer Procedure) */long amtmper; /* timer period (system ticks)*/void *amtmparm /* user defined timeout */

/* parameter */char amtmtag1; /* timer tag */char amtmtag2;char amtmtag3;char amtmtag4;};

AMX Buffer Pool Definition Structure

struct amxbps {char *ambpbp; /* Memory pointer */unsigned int ambpnb; /* Number of buffers */unsigned int ambpbs; /* Size of buffers */char ambptag1; /* Buffer pool tag */char ambptag2;char ambptag3;char ambptag4;};

370 KADAK Structure/Constant Definitions

AMX List Header Structure (doubly linked lists)

struct amxlhs {struct amxlhs *amlhhead; /* list head */struct amxlhs *amlhtail; /* list tail */unsigned int amlhoffs; /* byte offset to object node */};

AMX List Node Structure

struct amxlns {struct amxlns *amlnnext; /* next node in list */struct amxlns *amlnprev; /* previous node in list */};

AMX Key Node Structure

struct amxlks {struct amxlks *amlknext; /* next node in list */struct amxlks *amlkprev; /* previous node in list */unsigned int amlkkey; /* node key */};

Structure/Constant Definitions KADAK 371

AMX Register Array Structure

struct amxregs {unsigned short int amxrf; /* Flags (LS byte only) */unsigned short int amxrax; /* Register AX */unsigned short int amxrbx; /* Register BX */unsigned short int amxrcx; /* Register CX */unsigned short int amxrdx; /* Register DX */unsigned short int amxrsi; /* Register SI */unsigned short int amxrdi; /* Register DI */unsigned short int amxrbp; /* Register BP */unsigned short int amxrds; /* Register DS */unsigned short int amxres; /* Register ES */};

AMX Segment Register Array Structure

struct amxsregs {unsigned short int amxsrds; /* Register DS */unsigned short int amxsres; /* Register ES */unsigned short int amxsrss; /* Register SS */unsigned short int amxsrcs; /* Register CS */};

AMX Interrupt Descriptor Structure

struct amxidts {void (*amxiptr)(); /* Interrupt procedure pointer*/unsigned short int amxigate; /* IDT gate type */short int amxirsv /* Intel reserved */};

Interrupt gate types (field amxigate)

See Intel 80286 Programmer's Reference Manual

#define AMIDTINT 0x8600 /* 80286 interrupt gate */#define AMIDTTRP 0x8700 /* 80286 trap gate */

AMX C Root ISP Structure

struct amxisps {long amxispfn[8]; /* Root ISP */};

372 KADAK Structure/Constant Definitions

AMX C Jump Buffer Structure

struct ajxjbuf {unsigned short int xjbretadr; /* ofs(return address) */unsigned short int xjbcs; /* Register CS */unsigned short int xjbsp; /* Stack pointer offset */unsigned short int xjbss; /* Stack pointer segment */unsigned short int xjbbx; /* Register BX */unsigned short int xjbcx; /* Register CX */unsigned short int xjbsi; /* Register SI */unsigned short int xjbes; /* Register ES */unsigned short int xjbdi; /* Register DI */unsigned short int xjbds; /* Register DS */unsigned short int xjbbp; /* Register BP */unsigned short int xjbrsrv; /* Reserved */};

Structure/Constant Definitions KADAK 373

D.2 AMX Assembler Structures and Constants

AMX Launch Parameter (see AAENTR)

AMLPTMP EQU 1 ;Temporary launch; ;Default is permanent launch;AMLPVA EQU 2 ;Vector table is alterable; ;Default is non alterable table;AMLPIE EQU 4 ;Launch with interrupts enabled

;Default is disabled interrupts

AMX Task Definition Structure

AMXTDTS STRUC;AMTDTST DD ? ;task procedure pointerAMTDTAG1 DB ? ;4 char task tagAMTDTAG2 DB ?AMTDTAG3 DB ?AMTDTAG4 DB ?AMTDTSP DD ? ;task stack pointerAMTDTSKZ DW ? ;size of task stack (bytes)AMTDTAT DW ? ;task attributesAMTDTPR DW ? ;task priorityAMTDTSLC DW ? ;task time slice (system ticks)AMTDTMB0 DW ? ;mailbox level 0 depthAMTDTMB1 DW ? ;mailbox level 1 depthAMTDTMB2 DW ? ;mailbox level 2 depthAMTDTMB3 DW ? ;mailbox level 3 depth;AMXTDTS ENDS

AMX Task Control Block Structure

AMXTCBS STRUC;AMTCBRSV DD 60 DUP (?) ;privateAMTCBUSR DD 4 DUP (?) ;user defined;AMXTCBS ENDS

374 KADAK Structure/Constant Definitions

AMX Task Status Block Structure

AMXSBS STRUC;AMSBTID DW ? ;task idAMSBTAG1 DB ? ;task tagAMSBTAG2 DB ?AMSBTAG3 DB ?AMSBTAG4 DB ?AMSBST DD ? ;task statusAMSBSIG DD ? ;pending signalsAMSBTMR DD ? ;task timer (time remaining)AMSBSLC DW ? ;time sliceAMSBCC DW ? ;call countAMSBATR DW ? ;task attributesAMSBIDC DW ? ;caller's task id

;(-1=ISP; 0=AATRIG)AMSBCWAT DW ? ;caller waiting if <> 0AMSBPRY DW ? ;task priorityAMSBMC0 DW ? ;message count; mailbox 0AMSBMC1 DW ? ;message count; mailbox 1AMSBMC2 DW ? ;message count; mailbox 2AMSBMC3 DW ? ;message count; mailbox 3;AMXSBS ENDS

Task Status Masks (fields AMSBST, AMSBSIG)

; low word:AMSBWTMR EQU 01H ;timer wait

;(used with other bits)AMSBWTRG EQU 02H ;trigger wait (i.e. idle)AMSBWSEM EQU 04H ;semaphore waitAMSBWEVT EQU 08H ;event group waitAMSBWXCH EQU 10H ;message exchange waitAMSBWSND EQU 20H ;message send waitAMSBWSUS EQU 40H ;suspended (waiting for resume)AMSBWWAT EQU 80H ;waiting for wake; high word:AMSBWSIG EQU 7FFFH ;15 task signal waitsAMSBWORW EQU 8000H ;OR-wait on AMSBWSIG bits

Critical Function Codes (passed to Task Termination Procedure)

AMCFE EQU 1 ;AATKSTP - stop (end) taskAMCFK EQU 2 ;AATKILL - kill taskAMCFD EQU 3 ;AATKDEL - delete task

Structure/Constant Definitions KADAK 375

AMX Extended Message Parameter Structure

(passed on stack above AMX message when starting a task)

AMXMSGXS STRUC;AMXMSCID DW ? ;calling task's idAMXMSFN DW ? ;AMX function codeAMXMSRSV DW 4 DUP(?) ;reserved;AMXMSGXS ENDS

AMX Function Codes (field AMXMSFN)

AMXMSFNM EQU 0 ;no message on stackAMXMSFMS EQU 1 ;message on stackAMXMSFMW EQU 2 ;message on stack

;sender waiting

376 KADAK Structure/Constant Definitions

AMX User Parameter Table Structure

AMXUPTS STRUC;AMPBRPL DD ? ;A(Restart Procedure List)AMPBEPL DD ? ;A(Exit Procedure List)AMPBCFGA DD ? ;Configuration attributesAMPBDGRP DW ? ;user's DGROUP segment selectorAMPBNMEV DW ? ;number of message envelopesAMPBUMS DW ? ;user message size (bytes)AMPBMES DD ? ;A(Message Envelope Segment)AMPBISTK DD ? ;A(top of AMX private stacks)AMPBESZ DW ? ;AMX Kernel Stack size (bytes)AMPBISZ DW ? ;AMX Interrupt Stack size(bytes)AMPBLEN DW ? ;size of AMX storage (bytes)AMPBCLKP DW ? ;AMX clock period (in hardware ticks)AMPBCLKF DW ? ;hardware clock frequency (hz)AMPBTDS DD ? ;A(Time/Date Scheduling Procedure)AMPBFEX DD ? ;A(Fatal Exit Procedure)AMPBERR DD ? ;A(User Error Procedure);AMPBTKMX DW ? ;maximum number of tasksAMPBTKPR DW ? ;number of predefined tasksAMPBTKDF DD ? ;A(Task Definition Table);AMPBTMMX DW ? ;maximum number of timersAMPBTMPR DW ? ;number of predefined timersAMPBTMDF DD ? ;A(Timer Definition Table)AMPBSMMX DW ? ;maximum number of semaphoresAMPBSMPR DW ? ;number of predefined semaphoresAMPBSMDF DD ? ;A(Semaphore Definition Table);AMPBEVMX DW ? ;maximum number of event groupsAMPBEVPR DW ? ;number of predefined event groupsAMPBEVDF DD ? ;A(Event Group Definition Table);AMPBMXMX DW ? ;maximum number of message exchangesAMPBMXPR DW ? ;number of predefined message exchangesAMPBMXDF DD ? ;A(Message Exchange Definition Table);AMPBBPMX DW ? ;maximum number of buffer poolsAMPBBPPR DW ? ;number of predefined buffer poolsAMPBBPDF DD ? ;A(Buffer Pool Definition Table);AMPBMAP DD ? ;A(Memory Assignment Procedure);AMPBDMN DB 16 DUP(?) ;reserved for InSightAMPBPCS DD ? ;A(PC Supervisor Definition Table)AMPBDBA DD ? ;Debugger attributesAMPBPED DW ? ;Breakpoint entry delayAMPBPXD DW ? ;Breakpoint exit delay;AMXUPTS ENDS

Structure/Constant Definitions KADAK 377

Configuration Attributes (field AMBPCFGA)

AMCAMTK EQU 1 ;Some Medium tasksAMCAMUP EQU 2 ;Some Medium user proceduresAMCAS24 EQU 4 ;Use 24-bit address space

AMX Time/Date Structure

AMXTDS STRUC;AMTDSEC DB ? ;secondsAMTDMIN DB ? ;minutesAMTDHR DB ? ;hoursAMTDDY DB ? ;dayAMTDMN DB ? ;monthAMTDYR DB ? ;yearAMTDOW DB ? ;day of weekAMTDCEN DB ? ;0 if time/date is incorrect; ;century if time/date is correct;AMXTDS ENDS

AMX Timer Definition StructureAMXTMS STRUC;AMTMPROC DD ? ;A(Timer Procedure)AMTMPER DD ? ;timer period (system ticks)AMTMPARM DD ? ;user defined timeout parameterAMTMTAG1 DB ? ;timer tagAMTMTAG2 DB ?AMTMTAG3 DB ?AMTMTAG4 DB ?;AMXTMS ENDS

AMX Buffer Pool Definition Structure

AMXBPS STRUC;AMBPBP DD ? ;Memory pointerAMBPNB DW ? ;Number of buffersAMBPBS DW ? ;Size of buffersAMBPTAG1 DB ? ;Buffer pool tagAMBPTAG2 DB ?AMBPTAG3 DB ?AMBPTAG4 DB ?;AMXBPS ENDS

378 KADAK Structure/Constant Definitions

AMX List Header Structure (doubly linked lists)

AMXLHS STRUC;AMLHHEAD DD ? ;Head of listAMLHTAIL DD ? ;Tail of listAMLHOFFS DW ? ;Byte offset to object node;AMXLHS ENDS

AMX List Node Structure

AMXLNS STRUC;AMLNNEXT DD ? ;Next node in listAMLNPREV DD ? ;Previous node in list;AMXLNS ENDS

AMX Key Node Structure

AMXLKS STRUC;AMLKNEXT DD ? ;Next node in listAMLKPREV DD ? ;Previous node in listAMLKKEY DW ? ;Node key;AMXLKS ENDS

Structure/Constant Definitions KADAK 379

AMX Register Array Structure

AMXREGS STRUC;AMXRF DW ? ;Flags (LS byte only)AMXRAX DW ? ;Register AXAMXRBX DW ? ;Register BXAMXRCX DW ? ;Register CXAMXRDX DW ? ;Register DXAMXRSI DW ? ;Register SIAMXRDI DW ? ;Register DIAMXRBP DW ? ;Register BPAMXRDS DW ? ;Register DSAMXRES DW ? ;Register ES;AMXREGS ENDS

AMX Segment Register Array Structure

AMXSREGS STRUC;AMXSRDS DW ? ;Register DSAMXSRES DW ? ;Register ESAMXSRSS DW ? ;Register SSAMXSRCS DW ? ;Register CS;AMXSREGS ENDS

AMX Interrupt Descriptor Structure

AMXIDTS STRUC;AMXIPTR DW ? ;FAR A(ISP) - offset

DW ? ; - selectorAMXIGATE DW ? ;IDT gate type

DW ? ;Intel reserved;AMXIDTS ENDS

Interrupt gate types (field AMXIGATE)

See Intel 80286 Programmer's Reference Manual

AMIDTINT EQU 8600H ;80286 interrupt gateAMIDTTRP EQU 8700H ;80286 trap gate

380 KADAK Structure/Constant Definitions

This page left blank intentionally.

AMX 86 Assembler Interface KADAK 381

E. AMX 86 Assembler InterfaceThis appendix summarizes the assembly language calling sequences for all AMXprocedures. The procedures are organized in functional groups. Within each group theprocedures are listed alphabetically.

All procedures are called as follows:

EXTRN AAxxxx:FAR ;external FAR procedure..Parameters in registers specified by column INCALL AAxxxxResults in registers specified by column OUTAX = AEROK flags = Z no errorAX = AERxx flags = NZ, S errorAX = AERWxx flags = NZ, NS warning

For some functions, AX returns a parameter and no error status is provided.In such cases, the zero and sign flags are unknown. AX is always alteredunless otherwise specified.

All registers except AX and those used to return results are preserved.Exceptions are noted.

The direction flag is always preserved. Other flags which are altered byarithmetic and logical operations are unknown upon return.

Interrupts are affected as follows:

E D R

� � � Untouched� � � Disabled upon return� � � Enabled upon return� � � Disabled and then enabled upon return� � � Disabled and then restored to the state at the time of the call� � � Disabled and enabled and then restored to the state at the time of the call

382 KADAK AMX 86 Assembler Interface

The following notes are referenced in the procedure descriptions in this appendix.

Note: 1. All registers are preserved, including AX.

2. Registers CX, DX, SI are unaltered.All other registers are undefined.

3. All registers are restored to the state they were in when AAINT was called.

4. Registers AX, BX, CX and DX are altered.All other registers are preserved.

5. A tag 'ABCD' is presented in DX:CX with 'A' in CL and 'D' in DH.

6. AX is 0 and flags = Z if ES:BX is 0:0.Otherwise AX is non-zero and flags = NZ.

AMX 86 Assembler Interface KADAK 383

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

System Control

ajentr AAENTR Enter AMX multitasking world Launch Parameters BX no � � �

Exit allowed? (0=No, 1=Yes) bit 0IVT alterable bit 1 (0=No, 1=Yes)Interrupts enabled bit 2 (0=No, 1=Yes)A(AMX User Parameter Table) DS:SIerrcode AXexitinfo DX:BX

ajexit AAEXIT Leave AMX multitasking world errcode CX no � � �

(no return) exitinfo DX:BX

ajfatl AAFATL Fatal exit Fatal Exit Code CX no � � �

(no return)

ajhook AAHOOK Install hooks to AMX Scheduler A(Block of procedure pointers) ES:BX no � � �

(0:0 to remove hooks)

ajprvl AAPRVL Lower privilege level no � � �

ajprvr AAPRVR Raise privilege level no � � �

ajver AAVER Get AMX version number Major revision rr AH no � � �

Minor revision mm ALAMX version = 0086H DX

384 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Task Control

ajend AAEND End task execution no � � �

(no return)

ajgmsg AAGMSG Get message from task mailbox A(Storage for message) ES:BX AERCWT � � �

Mailbox priority (0 to 3) CX AERNMG(4=highest priority message)

ajresum AARESUM Resume a task suspended by ajsusp Task id DX AERNST � � �

ajsend AASEND Start a task by sending it a message Task id DX AERNST � � �

ajsendp at one of 4 priorities A(message) ES:BX AERNMEajsenw Proceed = 0; Wait = 80H CH AERNMBajsenwp Priority (0 to 3) CL AERMBF

ajsgnl AASGNL Signal a task Task id DX AERNST � � �

Signal mask BX AERWATPending signals BX AERWKPSignal overruns CX AERTNW

ajsgrd AASGRD Read pending task signals signals AX no � � �

ajsgres AASGRES Reset pending task signals signal mask BX no � � �

ajsgwat AASGWAT Wait for any/all of a set of signal mask BX AERTMO � � �

task signals Wait all = 1; Wait any = 0 BX[15] AERTMVMax. wait time (system ticks) DX:CX(0:0 = forever)signals received BX

ajsusp AASUSP Suspend a task Task id DX AERNST � � �

ajtkcre AATKCRE Create a new task A(Task Definition) ES:BX AERITP � � �

Assigned task id DX AERNTCAERMBZ

ajtkdel AATKDEL Delete a task Task id DX AERNST � � �

Priority for delete CX AERANA

ajtkid AATKID Get task identifier of current task Task id AX no � � �

AMX 86 Assembler Interface KADAK 385

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Task Control(continued)

ajtkill AATKILL Kill a task Task id DX AERNST � � �

AERANA

ajtkpry AATKPRY Change task's execution priority Task id DX AERNST � � �

Task's new priority CX AERITP

ajtkstp AATKSTP Stop a task Task id DX AERNST � � �

AERANA

ajtksts AATKSTS Fetch task status Task id DX AERNST � � �

A(storage for result) ES:BX

ajtktag AATKTAG Find task id of task with a specific Task tag DX:CX AERNST � � �

task tag Task id DX Note 5

ajtktcb AATKTCB Fetch A(Task Control Block) Task id DX AERNST � � �

A(TCB for that task) ES:BX

ajtktrm AATKTRM Enable/disable abnormal task Task id DX AERNST � � �

termination A(Task Termination Procedure) ES:BX AERANA(0:0 to disable termination)

ajtrig AATRIG Start (trigger) a task with no message Task id DX AERNST � � �

ajwait AAWAIT Wait for a wake request Note 1 � � �

ajwakc AAWAKC Wake a task upon receipt of AERCNW � � �

its message AERNMT

ajwakcs AAWAKCS Wake a task upon receipt of Returned status CX AERCNW � � �

its message AERNMTReturn status to that task AERIRS

ajwake AAWAKE Wake a task Task id DX AERWKP � � �

AERNSTAERTNW

ajwapr AAWAPR Reset pending wake for current task no � � �

ajwatm AAWATM Wait for a timed interval or Number of system ticks to wait DX:CX AERWBT � � �

until a wake request occurs AERTMV

386 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Interrupt Control

ajint AAINT Begin interrupt service AMX Interrupt Stack SS:SP Note 2 � � �

DGROUP segment DS,ES

ajinx AAINX End interrupt service Note 3 � � �

ajispm AAISPM Make an ISP root A(Storage for ISP root) ES:BX no � � �

A(Interrupt Procedure) CX:DX

ajitrp AAITRP Install task trap handler Interrupt type 0,4 or 5 DX AERITT � � �

A(task trap handler) ES:BX

ajivtr AAIVTR Read entry in IVT Interrupt type (0-255) DX AERIPR � � �

A(Storage for old vector) ES:BX

ajivtw AAIVTW Write entry in IVT Interrupt type (0-255) DX AERIPR � � �

A(New ISP) ES:BX

ajivtx AAIVTX Exchange entry in IVT Interrupt type (0-255) DX AERIPR � � �

A(New ISP) ES:BXA(Storage for old ISP) DS:DI

AMX 86 Assembler Interface KADAK 387

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Timing Control

ajclk AACLK AMX Clock Handler Note 1 � � �

ajtick AATICK Read elapsed system ticks DX:AX no � � �

ajtmcnv AATMCNV Convert milliseconds to system ticks Interval (ms) DX:CX no � � �

Interval (system ticks) DX:CX

ajtmcre AATMCRE Create an interval timer A(Timer Definition) ES:BX AERNTM � � �

Timer id DX AERTMVNote 5

ajtmdel AATMDEL Delete an interval timer Timer id DX AERNSTM � � �

ajtmrd AATMRD Read an interval timer Timer id DX AERNSTM � � �

Timer value (system ticks) DX:CX

ajtmtag AATMTAG Find id of timer with specific tag Tag DX:CX AERNSTM � � �

Timer id DX Note 5

ajtmwr AATMWR Start/stop an interval timer Timer id DX AERNSTM � � �

Timer value (system ticks) BX:CX AERTMV(0:0 = stop)

ajtslv AATSLV Change a task's time slice interval Task id DX AERNST � � �

Time slice value (system ticks) CX

ajtsof AATSOF Disable time slicing no � � �

ajtson AATSON Enable time slicing no � � �

Time/Date Manager

ajtdf AATDF Format calendar time/date A(time/date structure) ES:BX no � � �

as an ASCII string A(text buffer) DS:DIFormat specification byte DLCount of chars formatted AX

ajtdg AATDG Get calendar time/date A(time/date structure) ES:BX Note 1 � � �

AATDRR Time/Date Restart Procedure Note 4 � � �

ajtds AATDS Set calendar time/date A(time/date structure) ES:BX Note 1 � � �

388 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Semaphore Manager

ajsmcre AASMCRE Create a semaphore Initial value (0 to 32767) BX AERISV � � �

(-1 for resource semaphore) AERNSBTag DX:CX Note 5Semaphore id BX

ajsmdel AASMDEL Delete a semaphore Semaphore id BX AERNSS � � �

AERSIU

ajsmfre AASMFRE Free a resource (unconditional) Resource semaphore id BX AERNSS � � �

AERRNY

ajsmget AASMGET Get use of a semaphore Semaphore id BX AERNSS � � �

(no wait) AERSBY

ajsmrls AASMRLS Release a resource (nested) Resource semaphore id BX AERNSS � � �

AERRNY

AASMRR Semaphore Manager Note 4 � � �

Restart Procedure

ajsmrsv AASMRSV Reserve a resource Resource semaphore id BX AERNSS � � �

(optional timeout) Max. wait time (system ticks) DX:CX AERTMO(0:0 = forever) AERTMVWait priority DI(0 = highest)

ajsmsig AASMSIG Signal to a semaphore Semaphore id BX AERNSS � � �

AERNME

ajsmtag AASMTAG Find id of semaphore with Tag DX:CX AERNSS � � �

specific tag Semaphore id BX Note 5

ajsmwat AASMWAT Wait on a semaphore Semaphore id BX AERNSS � � �

(optional timeout) Max. wait time (system ticks) DX:CX AERTMO(0:0 = forever) AERTMVWaiting priority DI(0 = highest)

AMX 86 Assembler Interface KADAK 389

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Event Manager

ajevcre AAEVCRE Create an event group Initial value for event group BX AERNEB � � �

Tag DX:CX Note 5Group id BX

ajevdel AAEVDEL Delete an event group Group id BX AERNSG � � �

AEREVU

ajevnt AAEVNT Get saved event state Event value AX no � � �

ajevrd AAEVRD Read current event state Group id BX AERNSG � � �

Event value CX

AAEVRR Event Manager Restart Procedure Note 4 � � �

ajevsig AAEVSIG Signal one or more events in a group PUSH <signal value> AERNSG � � �

PUSH <event mask> AERNMEPUSH <group id>CALL AAEVSIGADD SP,6

ajevtag AAEVTAG Find id of event group with Tag DX:CX AERNSG � � �

specific tag Group id BX Note 5

ajevwat AAEVWAT Wait for all/any of a set of events DX:CX=<timeout-system ticks> AERTMO � � �

(0:0 = forever) AERNSGPUSH DX AERTMVPUSH CXPUSH <0 for any; 1 for all>PUSH <match value>PUSH <event mask>PUSH <group id>CALL AAEVWATADD SP,12

390 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Message ExchangeManager

ajmxcre AAMXCRE Create a message exchange Tag DX:CX AERNXB � � �

A(Mailbox size definition) ES:BX AERMBZ DW size mailbox 0 Note 5 DW size mailbox 1 DW size mailbox 2 DW size mailbox 3Exchange id BX

ajmxdel AAMXDEL Delete an exchange Exchange id BX AERNSX � � �

AERXIU

ajmxget AAMXGET Get a message from an Exchange id BX AERNSX � � �

exchange (no wait) A(Storage for message) ES:SI AERNMG

AAMXRR Message Exchange Manager Note 4 � � �

Restart Procedure

ajmxsnd AAMXSND Send message to exchange Exchange id BX AERNSX � � �

ajmxsndp Priority (0 to 3) DX AERMBFA(Message) ES:SI AERNME

AERNMB

ajmxtag AAMXTAG Find id of exchange with Tag DX:CX AERNSX � � �

specific tag Exchange id BX Note 5

ajmxwat AAMXWAT Wait for message from exchange Exchange id BX AERNSX � � �

A(Storage for message) ES:SI AERTMOMax. wait time (system ticks) DX:CX AERTMV(0:0 = forever)Waiting priority DI(0 = highest)

AMX 86 Assembler Interface KADAK 391

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Buffer Manager

ajbau AABAU Add to buffer use count A(buffer) ES:BX AERBNU � � �

Increment for buffer use count DX AERBUVAERNSP

ajbcre AABCRE Create a buffer pool A(Buffer Pool Definition) ES:BX AERBTS � � �

Pool id DX AERNBFAERNFP

ajbdel AABDEL Delete a buffer pool Pool id DX AERNSP � � �

ajbfre AABFRE Free a buffer A(buffer) ES:BX AERBNU � � �

AERNSP

ajbget AABGET Get a buffer from a specific pool Pool id DX AERNSP � � �

A(buffer) ES:BX AERWNB

ajbgsz AABGSZ Get size of buffer A(buffer) ES:BX AERBNU � � �

Size of buffer CX AERNSP

ajbia AABIA Initialize all buffer pools AERBTS � � �

ajbip AABIP Initialize one buffer pool Pool id DX AERNSP � � �

AERBTS

AABMRR Buffer Manager Restart Procedure Note 4 � � �

ajbtag AABTAG Find id of buffer pool with Tag DX:CX AERNSP � � �

specific tag Pool id DX Note 5

392 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Memory Manager

ajmau AAMAU Add to block use count A(memory block) ES:BX AERMIB � � �

Increment for use count DX AERMNUAERMOV

ajmfre AAMFRE Free a block of memory A(memory block) ES:BX AERMIB � � �

AERMNU

ajmgeh AAMGEH Get a block of memory from Required memory size DX:CX AERMNA � � �

a private section Handle ES:BX AERMIBA(allocated memory block) ES:BXSize of block or available memory DX:CX

ajmget AAMGET Get a block of memory Required memory size DX:CX AERMNA � � �

A(allocated memory block) ES:BXSize of block or available memory DX:CX

ajmgsz AAMGSZ Get size of block of memory A(memory block) ES:BX AERMIB � � �

Size of memory block DX:CX AERMNU

ajmhan AAMHAN Create private memory section A(memory block) ES:BX AERMNA � � �

Size of memory block DX:CXHandle ES:BX

AAMMRR Memory Manager Restart Procedure Note 4 � � �

ajmset AAMSET Fill a block of memory with a pattern A(memory to be filled) ES:BX AERMMV � � �

Size of memory region DX:CXFill pattern SI

AMX 86 Assembler Interface KADAK 393

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Linked List Manager

ajlcre AALCRE Create an empty list A(List Header) DS:SI no � � �

Node offset CX

ajlhead AALHEAD Find head of list A(List Header) DS:SI Note 6 � � �

A(First object) ES:BX(0:0 if list is empty)

ajlinsc AALINSC Insert before specific object A(List Header) DS:SI no � � �

A(New object) ES:BXA(Specific object) CX:DI

ajlinsh AALINSH Insert at head of list A(List Header) DS:SI no � � �

A(Object) ES:BX

ajlinsk AALINSK Insert into keyed list A(List Header) DS:SI no � � �

A(Object) ES:BXKey CX

ajlinst AALINST Insert at tail of list A(List Header) DS:SI no � � �

A(Object) ES:BX

ajlmerg AALMERG Merge two lists no � � �PUSH SEGMENT <Source object>PUSH OFFSET <Source object>PUSH SEGMENT <Destination object>PUSH OFFSET <Destination object>PUSH SEGMENT <Source List Header>PUSH OFFSET <Source List Header>PUSH SEGMENT <Destination List Header>PUSH OFFSET <Destination List Header>CALL AALMERGADD SP,16

ajlnext AALNEXT Find next object on list A(List Header) DS:SI Note 6 � � �

A(Current object) ES:BXA(Next object) ES:BX(0:0 if list is empty)

ajlordk AALORDK Reorder object on keyed list A(List Header) DS:SI no � � �

A(Object) ES:BXKey CX

ajlprev AALPREV Find previous object on list A(List Header) DS:SI Note 6 � � �

A(Current object) ES:BXA(Previous object) ES:BX(0:0 if list is empty)

394 KADAK AMX 86 Assembler Interface

PROCEDUREC ASM PURPOSE PARAMETERS IN OUT

AX =ERRORS E D R

Linked List Manager(continued)

ajlrmvc AALRMVC Remove specific object from list A(List Header) DS:SI no � � �

A(Specific object) ES:BX

ajlrmvh AALRMVH Remove object at head of list A(List Header) DS:SI Note 6 � � �

A(Object) ES:BX(0:0 if list is empty)

ajlrmvt AALRMVT Remove object at tail of list A(List Header) DS:SI Note 6 � � �

A(Object) ES:BX(0:0 if list is empty)

ajltail AALTAIL Find tail of list A(List Header) DS:SI Note 6 � � �

A(Last object) ES:BX(0:0 if list is empty)

Circular ListManager

ajabl AAABL Add to bottom of list Address of list ES:BX 0 ok � � �

Entry to be added - byte CL 1 full - word CX -1 no - dword DX:CX

ajatl AAATL Add to top of list Address of list ES:BX 0 ok � � �

Entry to be added - byte CL 1 full - word CX -1 no - dword DX:CX

ajrbl AARBL Remove from bottom of list Address of list ES:BX 0 ok � � �

Entry removed - byte CL 1 empty - word CX -1 none - dword DX:CX

ajrstl AARSTL Reset a list Size of slot (1, 2 or 4) DX Note 1 � � �

Number of slots CXAddress of list ES:BX

ajrtl AARTL Remove from top of list Address of list ES:BX 0 ok � � �

Entry removed - byte CL 1 empty - word CX -1 none - dword DX:CX

Index KADAK Index-1

Numerals24-bit memory addressing 1, 125, 171

AAACLK 73AAENTR 22AAINT 54, 55, 56, 73AAINX 55, 56, 73

ajabl 135, 205ajatl 135, 206ajbau 52, 119, 121, 207ajbcre 119, 120, 174, 189, 208ajbdel 119, 121, 210ajbfre 52, 76, 119, 121, 211ajbget 52, 76, 119, 121, 212ajbgsz 119, 121, 213ajbia 119, 214ajbip 119, 215ajbtag 119, 120, 216ajcfjlong 217ajcfjset 217ajcfstkjmp 219ajclk 220ajdi 221ajei 221ajend 35, 61, 153, 154, 155, 222ajentr 11, 20, 21, 23, 44, 223ajevcre 104, 105, 108, 174, 185, 225ajevdel 104, 106, 226ajevnt 104, 106, 227ajevrd 104, 106, 228ajevsig 52, 58, 76, 104, 106, 229ajevtag 104, 105, 230ajevwat 28, 58, 104, 105, 231ajexit 16, 24, 44, 45, 147, 233ajfatl 147, 234ajflagrd 235ajflagrddi 235ajflagwr 235ajgmsg 236ajgofs 237ajgseg 238ajgsreg 239ajhook 152, 240ajinb 108, 241ajint 242ajinw 241ajinx 242ajispm 14, 53, 243ajitrp 60, 244ajivtr 245ajivtw 53, 68, 246ajivtx 247

ajlcre 139, 142, 144, 248ajlhead 139, 144, 249ajlinsc 139, 250ajlinsh 139, 251ajlinsk 139, 142, 144, 252ajlinst 139, 144, 253ajlmerg 139, 254ajlnext 139, 144, 256ajlordk 139, 142, 257ajlprev 139, 258ajlrmvc 139, 142, 144, 259ajlrmvh 139, 260ajlrmvt 139, 261ajltail 139, 262ajmau 126, 129, 263ajmfre 126, 128, 264ajmgeh 126, 130, 265ajmget 126, 128, 130, 266ajmgsz 126, 129, 267ajmhan 126, 130, 268ajmodl 269ajmset 126, 270ajmxcre 112, 113, 116, 174, 187, 271ajmxdel 112, 114, 272ajmxget 112, 114, 273ajmxsnd 33, 36, 40, 52, 58, 76, 112, 113, 116, 118,

274ajmxsndp 112, 113, 275ajmxtag 112, 113, 276ajmxwat 28, 33, 58, 112, 114, 117, 277ajoutb 278ajoutw 278ajproc 279ajprocq 279ajprvl 281ajprvr 282ajrbl 135, 283ajresum 158, 284ajrstl 135, 136, 285ajrtl 135, 286ajsend 26, 28, 29, 36, 40, 52, 59, 76, 122, 287ajsendp 36, 288ajsenw 26, 28, 29, 32, 36, 45, 289ajsenwp 36, 291ajsgnl 32, 52, 57, 76, 293ajsgrd 295ajsgres 296ajsgwat 28, 32, 57, 297ajsint 299ajsintq 299

Index-2 KADAK Index

ajsmcre 91, 93, 94, 95, 98, 99, 174, 183, 301ajsmdel 91, 93, 99, 302ajsmfre 91, 95, 303ajsmget 91, 94, 304ajsmrls 91, 95, 305ajsmrsv 28, 91, 95, 96, 306ajsmsig 52, 58, 76, 91, 94, 308ajsmtag 91, 93, 309ajsmwat 28, 58, 91, 94, 98, 99, 310ajsofs 311ajsseg 312ajssreg 313ajsusp 158, 314ajtdf 70, 82, 88, 315ajtdg 70, 82, 316ajtds 70, 82, 85, 317ajtick 318ajtkcre 25, 173, 178, 319ajtkdel 153, 320ajtkid 321ajtkill 153, 322ajtkpry 47, 323ajtkstp 153, 324ajtksts 325ajtktag 25, 326ajtktcb 46, 327ajtktrm 153, 154, 155, 328ajtmcnv 34, 69, 75, 76, 109, 116, 117, 329ajtmcre 34, 69, 75, 76, 116, 173, 181, 330ajtmdel 34, 69, 75, 76, 331ajtmrd 34, 52, 69, 76, 332ajtmtag 69, 75, 333ajtmwr 34, 52, 69, 75, 76, 116, 181, 334ajtrig 26, 28, 29, 52, 59, 76, 116, 118, 335ajtslv 70, 81, 179, 336ajtsof 70, 79, 81, 337ajtson 70, 79, 81, 337ajupt 338ajver 339ajwait 28, 32, 57, 103, 158, 340ajwakc 32, 341ajwakcs 342ajwake 32, 52, 57, 76, 103, 343ajwapr 344ajwatm 28, 32, 34, 57, 345

AMBKOF 161AMBKON 161AMHALT 149

AMX Library 193, 201, 202, 203, 204AMX ROM Option/Access

(Refer to AMX Tool Guides)AMX Service Procedures

Beginning on page 193Ending on page 345

AMX Tool Guide 2Arithmetic overflow 60, 61, 62, 63, 147Array bounds violations 60, 61, 62, 63, 147Assembler calls to AMX 381–94Assemblers

(Refer to AMX Tool Guides)Assembly language

programming in 203, 204

BBoolean flags

(see Event group, flags)Bounds checking 60, 61, 62, 63, 147Breakpoint Manager 27, 147, 159, 160, 161, 162, 171,

191compatible debuggers 162entry delay 191exclusion 160exit delay 191exit detection 160interrupt masking 161NMI as breakpoint 162

Buffer 119–24free 119, 121get 119, 121ownership 18, 119, 121, 122, 123, 124size 120, 121use count 120–24

Buffer Manager 18, 119–24Service Procedure Summary 197, 391

Buffer pool 3, 18, 119–24create 120definition structure 369, 377delete 121find id 120id 3, 119, 120, 190maximum number 119, 120, 174number of buffers 119, 120predefine using Builder 163, 189, 190storage allocation 120tag 120, 190wait queue 18

Building an AMX system(Refer to AMX Tool Guides)(see also Configuration Builder)

CC language interface

Service Procedure Summary 199C programming 202, 203, 204Calendar clock 70, 82–89

(see also Time/Date Manager)calloc 125Century 84, 85, 88, 89Circular list 3, 19, 135, 136, 137, 138

element 4, 135, 136, 137, 138ISP use 52slot 5, 135, 136, 137, 138storage size 136, 137, 138structure 137, 138

Circular List Manager 19, 135, 136, 137, 138Service Procedure Summary 198, 394

Index KADAK Index-3

Class of AMX servicebuffer pool, buffer 197C language interface 199circular list 198counting semaphore 196event group 196interrupt control 194linked list 198memory allocation 197message exchange 197PC Supervisor 200processor support 199resource semaphore 196system control 194task control 195task termination 195time/date 196timing control 196

Clock frequency 71, 172Clock Handler 3, 15, 34, 65, 71–74Clock installation 71–74Clock Interrupt Handler 71–74Clock ISP 15, 65, 71–74Clock ISP root 71–74Clock tick 3, 15, 69, 172

(see also System tick)Compilers

(Refer to AMX Tool Guides)Compute bound 35, 85, 157Concurrent execution 9Configuration Builder 163–91Configuration Generator 53, 164, 165, 166, 353–63

porting 164, 353–63Configuration Manager 164–91

field editing 168, 169menu selections 168

Configuration module(see System Configuration Module)

Conforming ISP(see also Clock ISP)(see Interrupt Service Procedure, conforming)

Constant definitions 365–79Constructing an AMX system

(Refer to AMX Tool Guides)(see also Configuration Builder)

Context switching 13, 14, 15Convert ms to system ticks 75Coprocessor 101, 102, 152, 162Critical code section 64, 157

DDay of week 85, 88, 89Debugger

(see Breakpoint Manager)Debugging 159, 160, 161, 162Debugging aid 46, 150, 151Delay 34Development tools

(Refer to AMX Tool Guides)Device input/output services 199DGROUP (see Groups)Disable interrupts 199Divide by zero 60, 61, 62, 63, 147Download

(Refer to AMX Tool Guides)

EEnable interrupts 199Envelope

(see Message envelope)Error

bounds 50divide 50overflow 50

Error codes 3, 150, 151, 349, 350Error Procedure 150, 151, 175Event group 3, 17, 58, 103–9

create 104, 105delete 105find id 105flags 103, 105id 3, 104–9, 186initial state 105ISP/task synchronization 58maximum number 105, 174predefine using Builder 185, 186read 105signal 17, 103, 105, 107, 108, 109state 105status 105synchronization using 17, 105–9.tag 105, 186wait for event(s) 17, 105, 107, 108, 109

Event Manager 17, 33, 58, 103–9Service Procedure Summary 196, 389

Exception traps 60, 61, 62, 63, 68(see also Task, traps)

Exit(see System, shutdown)

Exit codes(see Fatal exit codes)

Exit Procedures 3, 16, 44, 45, 176, 177interrupt state 44, 45stack size 44, 45

Index-4 KADAK Index

FFAR pointers 204Fatal error 3Fatal exit 3, 60, 147, 148, 149, 175Fatal exit codes 147, 148, 149, 351Fatal Exit Procedure 147, 148, 149, 175

interrupt state 148stack size 148

Faults (processor exceptions) 68Fences (stack) 46File names (AMX files) 7Flags

(see Event group, flags)free 125Function prototyping 201

GGroup id

(see Event group, id)Groups

DGROUP 31, 42, 44, 55, 62, 76, 86, 132, 148,151, 156, 180

Grow a memory block 129

HHalt 149Handle 3

(see also Memory pool, handle)

II/O, device input/output services 199Id variables 163

buffer pool 190event group 186message exchange 188semaphore 184task 179, 180timer 182

Installationclock 71–74ISP 53, 68

Instruction counting 34Integer size 7Interrupt

device 50disable by ajdi 199enable by ajei 199external 14, 49, 51, 53, 56, 64, 65, 68initial state 20masking by debugger 161nested 14, 51, 52, 56non-maskable (NMI) 50response 14, 31, 49, 65state 31, 42, 43, 44, 45, 51, 76, 77, 86, 87, 148,

150, 151Interrupt control

Service Procedure Summary 194, 386Interrupt controller 161, 162Interrupt Descriptor Structure 371, 379

Interrupt Handler 3, 4, 14, 51–59, 65, 66, 67, 68clock

(see Clock Interrupt Handler)shared 66, 67

Interrupt Service Procedure 4, 14, 49–68conforming 3, 14, 51–59, 65, 66, 67, 68installation 53, 68nonconforming 5, 14, 51, 64, 65, 68non-maskable (NMI) 64, 68stack size 51, 56, 65task synchronization 57, 58, 59

Interrupt Stack 14, 51, 56, 65, 171Interrupt Supervisor 14, 49–68

Service Procedure Summary 194Interrupt Vector Table 68ISP

(see Interrupt Service Procedure)ISP root 3, 4, 14, 51, 52, 53, 65, 66, 67, 68

structure definition 371, 379ISP root, clock 71–74

KKernel Stack 42, 43, 65, 76, 77, 85, 86, 87, 170Kernel Task 4, 15, 30, 31, 34, 47, 57, 58, 71, 75, 76,

77, 81, 83, 85, 158, 170priority 30, 47tag 47

Key(see Linked list, key)

Key node(see Linked list, key node)

LLaunch 20, 21, 22, 23

parameter 20–24, 20–24, 365, 373permanent 20, 21, 22temporary 20, 23

Leave(see System, shutdown)

Librarian(Refer to AMX Tool Guides)

Library, AMX 193, 201, 202, 203, 204Linked list 4, 19, 139–46

create 142, 143, 144, 145head 140header 140, 142, 143, 144, 145, 370, 378ISP use 52key 139–46key node 140, 142, 143, 144, 145, 370, 378node 140–46, 370, 378node offset 140, 142, 143, 144, 145nomenclature 140object 139–46tail 140

Linked List Manager 19, 139–46Service Procedure Summary 198, 393, 394

Linkers and Locators(Refer to AMX Tool Guides)

Index KADAK Index-5

MMailbox 4, 26

(see Message (task), mailbox)acknowledge message 35message queue 4

Make utilities(Refer to AMX Tool Guides)

malloc 125Math coprocessor 101, 102, 152Memory addressing (24-bit) 1, 125, 171Memory allocation 18, 125, 126, 128–34Memory assignment

(see Memory Assignment Procedure)Memory Assignment Procedure 131–34, 175Memory block 4, 125–34

find size 129free 18, 125, 126, 128, 130get 18, 125, 126, 128, 130header 127ownership 18, 125, 126, 127, 128, 129resize (grow or shrink) 129use count 127, 128, 129

Memory handle 4(see also Memory pool, handle)

Memory management unit 152Memory Manager 18, 125–34

24-bit memory 125assign memory to 126, 128, 131–34nomenclature 127Service Procedure Summary 197, 392

Memory paging 152Memory pool 18, 125–34

assign memory to 131handle 127, 130maximum number 125, 128memory assignment 132, 133, 134private 125, 130section 18, 125–34size 125, 128

Memory section 4(see Memory pool, section)

Message 4alignment 36, 40from ISP 58passing 16, 36–41, 58, 36–41priority 5, 16

(see Message (task), priority)(see Message exchange, message priority)

size 36, 37, 40, 113Message (task) 25, 26, 29, 31, 36–41

acknowledge message 35extension 41, 367, 375id 180mailbox 18, 29, 36–39, 180predefine using Builder 180priority 36–39queue depths 180receive 36–41send 36–38, 36–41, 59tag 180

Message envelope 3, 16, 36–41, 111, 113, 114maximum number 170size 37, 170

Message exchange 4, 16, 18, 36, 37, 38, 39, 58, 111–18create 113delete 114find id 113id 4, 112, 113, 188ISP/task synchronization 58maximum number 113, 174message priority 5, 16, 18, 36, 37, 38, 39, 111–14message queue 16, 18, 36, 37, 38, 39, 111–14, 188predefine using Builder 187, 188queue depths 113, 188send message to 58, 111–18synchronization using 18, 111–18.tag 113, 188wait for message 58, 111–18wait queue 18, 111, 112, 113, 114

Message Exchange Manager 18, 33, 58, 111–18Service Procedure Summary 197, 390

Message priority(see Message (task), priority) .(see Message exchange, message priority)

Message queue 5(see Message (task), mailbox)(see Message exchange, message queue)

Message send(see Message (task), send/receive)(see Message exchange, send to/wait for)

ModelLarge 202Medium 171, 180, 202

Multitasking 9

NNames, AMX reserved 7, 347NMI (non maskable interrupt) 162NMI (Non-maskable interrupt) 64, 68Node

(see Linked list, node)Nomenclature 7, 201, 202, 203, 204Nonconforming ISP

(see Interrupt Service Procedure, nonconforming)Non-maskable interrupt (NMI) 64, 68Numeric coprocessor 101, 102, 152, 162

OOverflow (arithmetic) 60, 61, 62, 63, 147Ownership

buffer 119, 121, 122, 123, 124memory block 125, 126, 127, 128, 129resource 95, 101, 102

Index-6 KADAK Index

PPC Supervisor

(see PC Supervisor Reference Manual)Service Procedure Summary 200

Preemption 13Priority

(see Event group, wait for event(s))(see Kernel Task, priority)(see Message exchange, message priority)(see Message exchange, wait for message)(see Semaphore, counting, wait)(see Semaphore, resource, reserve)(see Task termination, deletion priority)(see Task, priority)

Priority scheduling 30Privileged

(see Task, privileged)Procedures, AMX

Beginning on page 193Ending on page 345

Procedures, AMX (summary of) 193Processor exceptions 50Processor exceptions (traps) 60, 61, 62, 63, 68

(see also Task, traps)Processor initialization 20, 42, 43, 44, 45Processor support

Service Procedure Summary 199Programming in assembler 381–94

QQueue

(see also Circular list)(see also Linked list)(see Event group, wait queue)(see Message (task), mailbox)(see Message exchange, message queue)(see Message exchange, wait queue)(see Semaphore, wait queue)

RRAM (random access memory) 5, 7, 21, 68Real-time clock

(see Clock)Reentrant code 66, 67, 123, 125, 135, 139, 194Register array 371, 379Reserved words 7, 347Resolution

(see Timer, resolution)Resource management 17Resource ownership 95, 101, 102Resource semaphore

see Semaphore, resourceRestart Procedures 5, 11, 20, 42, 43, 176, 177

interrupt state 42, 43stack size 42, 43

Resume task 158ROM (read only memory) 5, 7, 21, 68ROM Option/Access

(Refer to AMX Tool Guides)Round robin scheduling 70

SScheduler hooks 152

(see also Time/Date Scheduling Procedure)Scheduling algorithm 13, 29, 30, 70, 79, 80, 81Section

(see Memory pool, section)Segment 5Segment register array 371, 379Segment registers 371, 379Semaphore 5, 17, 58, 91–102

binary 17, 91, 95counting 3, 17, 58, 93, 91–94, 97, 98, 99, 100,

184signal 94wait 94

create 93, 94, 95delete 93find id 93id 5, 92, 93, 95, 184ISP/task synchronization 58maximum number 93, 174mutual exclusion 94, 97, 98P and V operations 91predefine using Builder 183, 184resource 5, 17, 91, 92, 93, 95–96, 101, 102, 184

nesting 95, 101, 102release 95reserve 95, 96

synchronization using 99, 100.tag 93, 184wait queue 17, 95, 96

Semaphore Manager 17, 33, 58, 91–102Service Procedure Summary 196, 388

Send message(see Message (task), send/receive)(see Message exchange, send to/wait for)

Service Procedure Summary 193–200Service Procedures, AMX

Beginning on page 193Ending on page 345

Shrink a memory block 129Software development

(Refer to AMX Tool Guides)Stack checking 46Stack fences 46Stack overflow 46

Index KADAK Index-7

Stack sizeExit Procedures 44, 45Fatal Exit Procedure 148Interrupt Service Procedure 51, 56, 65Interrupt Stack 51, 56, 65, 171Kernel Stack 42, 43, 65, 76, 77, 85, 86, 87, 170Restart Procedures 42, 43task 44, 45, 51, 61, 65, 155, 156, 179Task Termination Procedure 155, 156Task Trap Handler 61Time/Date Scheduling Procedure 85, 86, 87Timer Procedure 76, 77User Error Procedure 150, 151User Scheduler Hooks 152

Structure definitions 365–79Suspend task 158Symbols, AMX reserved 7, 347Synchronization 32, 33

(see Event group, synchronization)(see Message (task), synchronization)(see Message exchange, synchronization)(see Semaphore, synchronization)(see Task, signals)(see Task, wait/wake synchronization)

Systemparameters 170–75ROMed 68, 171shutdown 16, 23, 44, 45, 147startup 11, 20, 21, 22, 23, 29, 42, 43

System Configuration Module 5, 11, 21, 22, 23, 163–68, 353, 163–68

System Configuration Template 164, 165, 166, 353,359–62

System controlService Procedure Summary 194, 383

System Documentation Module 164, 165, 166System Documentation Template 164, 165, 166System generation process 163–91System tick 5, 15, 69, 172

(see also Clock tick)convert ms to 75

TTag 5Task 6, 11, 25–35

breakpoint 159create 25definition structure 365, 373delay 34delete 154, 155, 156, 157deletion priority 157end 13, 35, 81, 153, 154, 155, 156execution 13, 29, 30, 31, 59find id 25halt 159id 6, 25, 154, 179interrupt state 31ISP synchronization 57, 58, 59kill 154, 155, 156, 157mailbox

(see Message (task), mailbox)maximum number 25, 173periodic execution 29predefine using Builder 163, 178, 179, 180priority 6, 30, 35, 47, 79, 80, 81, 179privileged 31resume 158signals 6, 57stack 26, 31, 35, 44, 45, 46, 51, 61, 65, 155, 156,

163, 179stack size 44, 45, 51, 61, 65, 179start 26, 29, 31, 35, 81state 11, 27, 28, 27–35, 69, 27–35

halt 27idle 27–29ready 27–29run 27, 28wait 27, 28, 37

status block 366, 374stop 153, 154, 155, 156, 157suspend 158synchronization 32, 33

(see also Synchronization)tag 25, 46, 179time slice 5, 70, 79, 80, 81, 179timed wait 34timeout 32, 34timing 15, 34, 69, 70, 71, 79, 80, 81traps 60, 61, 62, 63, 147trigger 26, 29, 35, 59, 154wait/wake synchronization 57, 103

Task controlService Procedure Summary 195, 384, 385

Task Control Block (TCB) 6, 25, 46, 152, 365, 373reserved for user 46, 152

Task Mailbox(see Message (task), mailbox)

Task Scheduler 13, 14, 29, 30, 35, 52, 56, 70, 79, 80,81, 152, 153user hooks 152

Task switching 51, 52, 56

Index-8 KADAK Index

Task termination 153, 154, 155, 156, 157delete 154, 155, 156, 157deletion priority 157enable/disable 154kill 154, 155, 156, 157Service Procedure Summary 195stop 153, 154, 155, 156, 157

Task Termination Procedure 154, 155, 156, 366, 374Task Trap Handler 60, 61, 62, 63, 147

stack size 61TCB (see Task Control Block) 6Testing 159, 160, 161, 162Tick

(see Clock tick)(see System tick)

Time slice 6, 70, 79, 80, 81enable/disable 79, 80, 81, 172interval 5, 79, 80, 81

Time/DateASCII formatting 88, 89century 84, 85, 88, 89day of week 85, 88, 89default 83get 82, 83set 82, 83, 85structure 84, 86, 87, 369, 377timer 83validity 85, 88, 89

Time/Date Manager 17, 70, 82–89, 172Service Procedure Summary 196, 387

Time/Date Scheduling Procedure 82, 83, 85, 86, 87,82–87, 172interrupt state 86, 87stack size 85, 86, 87

Timer 6, 11, 34, 69–78(see also Time/Date, timer)create 75delete 75find id 75id 6, 75, 182interval 75, 76maximum number 75, 173one-shot 75parameter 69, 75, 76, 182periodic 15, 29, 69, 71, 75, 76predefine using Builder 181, 182resolution 34start 75stop 75tag 75, 182

Timer Manager 15, 34, 69–89Service Procedure Summary 196, 387

Timer Procedure 6, 15, 34, 69, 75, 76, 77, 78, 182interrupt state 76, 77parameter 69, 75, 76, 182stack size 76, 77

Timing control(see Timer Manager)

Tools(Refer to AMX Tool Guides)

Traps(see Task, traps)

Turbo86 (VAutomation) 1, 125, 171

UUnderscore in names 100, 172User Error Procedure 150, 151, 175User Parameter File 164–69, 353–63User Parameter Table 21, 22, 23, 21–24, 21–24, 163,

368, 376User Scheduler Hooks 152

VVariables, id 163

(see also Id variables)VAutomation 1, 125, 171Vector Table 68Volatile variable access 199

WWait queue

(see Event group, wait queue)(see Message exchange, wait queue)(see Semaphore, wait queue)

Warning codes 150, 151, 350