Home

Software for the 6809 Microprocessor board - Indico

image

Contents

1. 63 3 6 Interface Functions for RInOS System Calls Continued 64 3 7 Functions available in libIO a 205 64 3 8 Denominations of logical devices 2 2 2 2 00 65 3 9 Mathematical functions callable from aC program 66 3 10 Functions available in libgec a 2 ee 68 3 11 Functions in libmath09 a for internal use only 2 68 6 Software for ihe 6809 Microprocessor board C Verkerk and A J Wetherilt 3 12 Function prototypes for libpthread a 2 2 2 69 3 13 Options defined for the Cross debugger db09 T2 3 14 Commands supported by the Cross debugger db09 74 4 1 Help Screen for the symbolic cross debugger db09 83 ACT Registe Sebi ec ace g enat ald g ea Slee wed Ses 93 A 2 Condition Code Register 0 2 ee ee 93 B 1 Error codes returned by IO calls 24 96 B 2 Error codes returned by system calls 2 2 97 Ts System calla a i te eh e aA a RaR a ted Ra ie S 98 C 1 System calls Continued 23 5 2 8 24s be eek ne 99 C 1 System calls Continued aoaaa Bp oe BAG ee A 100 C 1 System calls Continued aooaa aaa a a 101 C 1 System calls Continued aaa Ss OS ER 102 C 1 System calls Continued saaa 000082 eee 103 C 1 System calls Continued aoaaa aa a 104 C 1 System calls Continued eyo a eae i awe a 105 C 1 System calls Continued aoa a o 106 D 1 Device driver function calls ooa a0 a a a aa 107 D 1 Devi
2. Workshop on Distributed Laboratory instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 List of Figures 2 1 Schematic Drawing of the ICTP09 board 2 00 2 2 Memory Map of the M6809 under RINOS 2 2 2 3 Jumper Settings for the ICTPO9 Board Chapter 1 Introduction The 6809 Microprocessor board was developed by A J Wetherilt when at the Marmara Research Centre in Istanbul Turkey He also developed the RInOS multitasking kernel and the ICTPMon monitor program which are both resident in EPROM on the board The RInQS kernel is one of the cornerstones of the available software allowing a user to write programs to a large extent compatible with the POSIX 1003 1c standard The other cornerstone is the GNU cross compiler which was adapted by C Verkerk from an existing version for the 68HC11 microprocessor The cross assembler and the linker were also adapted from existing versions The RInOS kernel and the cross compiler chain are independent of each other RInOS docs not make any assumption about characteristics of the compiler and vice versa The bridge between the two is built from the various program libraries and the C startup routine The result is that a user can write a multi threaded application program without any knowledge of the 6809 microprocessor and its instruction set The size of a single application program is limited to just under 32 Kbytes A maximuin
3. pt2 0 pt2 primebuf Create a child thread and Set up a pipe for writing and write to the pipe pipe create_pipe width cipid create_child ciprio wr_open_pipe pipe while pt2 0 write_pipe pipe pt2 3 write_pipe pipe pt2 Don t forget the send the 0 Close the pipe and finish off wr_close_pipe pipe release_pipe pipe thread_join cipid 0 void thread_exit Child opens the pipe reads from it and outputs 15 chars at a time to the LCD display void child1 void int k char pt localbuf 15 0 pt cbuffer rd_open_pipe pipe do for k 0 k lt 15 k localbuf k 0 for k 0 k lt 15 k pt read_pipe pipe pt localbuf k pt if pt 0 break Workshop on Distributed Laboratory Instrumentation Sysiems 131 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt void printf s n localbuf mssleep 100 while pt 1 0 void printf s n localbuf rd_cliose_pipe pipe return Standard routine to create a child thread int create_child int prior int chipid tcbmain tcbmain tcbmain tcbmain chipid tprio prior sseg tcbmain sseg 0x100 tdp tcbmain tdp 1 estart child thread_create prior amp tcbmain return chipid
4. J 2 A similar program using messages File tt2b c Transposition of Jim s test2 s into C The program tests thread creation and sending and recieving of messages cv January 8 1998 include lt syscalls h gt extern int tid extern struct creation_block tcbmain int mainpid cipid c2pid msgiid msg2id Function prototypes void main void void childi void Workshop on Distributed Laboratory Instrumentation Sysiems Abdus Salam C TP Trieste November 26 December 21 2001 132 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt int create_child int void main void int ciprio char msgi Now is the char msg2 winter of our mainpid tid clprio 3 cipid create_child ciprio keep sending messages while 1 if send_message cipid msgi lt 0 printerr give time to receive print and read the message mssleep 100 if send_message clpid msg2 lt 0 printerr mssleep 100 exit 0 void childi void char mess keep receiving a message and printing it while 1 if mess get_message 0 lt 0 printerr void prntf s n mess return int create_child int prior extern struct creation_block tcbmain int chipid tcbmain tprio prior tcbmain sseg tcbmain sseg 0x100 Workshop on Distributed Laboratory Instrumentation Systems 133 Abdus Salam ICTP Tricste November
5. Table E 1 Thread Control Block TCB structure 111 Software for ihe 6809 Microprocessor board C Verkerk and A J Wetherilt Fidd Value NOTASK 0x80 SUSPEND OxC0 WAIT 0x04 SLEEPING 0x06 ADLE 0x01 READY 0x00 Description TCB not used thread suspended thread blocked thread sleeping TCB claimed but not yet running thread running or waiting to run Table E 2 Values used to define TCB fields Thread state values Value Description Detach state bit field Cancelation state bit field Cancelation type bit field Exit pending bit Cancelation pending bit DETACH STATE CANCEL_STATE CANCEL_TYPE EXIT_PENDING CANCEL_PENDING Table E 3 Values used to define TCB fields Thread attribute bit ficlds Field Value DETACH_STATE_ON OxO1fe DETACH_STATE_OFF Ox00fe CANCEL STATE_ON Ox02fd CANCEL _STATE_OFF Ox00fd CANCEL _TYPE_ASYNC 0x04fb CANCEL TYPE_DFRD OxC0fb Table E 4 User settable thread attribute values Field Off Size Description set SENDER 0 2 Message sender pid NXTMSG 2 2 Link to next message in list MSG 4 2 Pointer to message MSEMA 6 2 Message mutex MSGUSED 8 1 Message is in use Table E 5 Message structure Workshop on Distributed Laboratory Instrumentation Systems 112 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verk
6. options of a GNU C compiler For convenience the more useful options are resumed in Table 3 1 on page 55 The g option was made to work only very recently When specified it adds information for symbolic debugging to the assembly code it produces This is done in the form of assembler pseudo instructions stabs followed by the necessary information about symbols line numbers and the program structure The cross compiler will produce the usual error messages and warnings Arguments lo a function are passed as follows the first argument is passed to the function in the ZDO pseudo register and the remaining arguments are pushed onto the stack The last argument is pushed first then the last but one etc This ensures that they will be pulled off the stack in the correct order The return value of the function is passed back to the caller in the ZDO pseudo register The output of the cross compiler is a file of assembly language statements representing either PIC or absolute code For instance the function call Workshop on Distributed Laboratory Instrumentation Systems 54 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Option Effect a D name Define name for the preprocessor U name Undefine name for the preprocessor E Preprocessing only produces output file i 5 Compile only produces ass
7. After this it performs a subroutine call to the main program which in turn after some preliminaries calls a routine _main which is part again of crtQ main will clear the space occupied by the BSS area uninitialised global variables Direct Pages and the unused part of the stack area The main program may end with a return from subroutine rts in struction or it may perform an exit arg call In both eases it returns into crt0 which will exccute an OSThreadExit call after having called printerr to print an error message if needed The OSThreadExit sys tem call will delete the current process TCB If no other task is ready to run then the null task will start 3 4 Program Libraries As said previously the linker will search a number of libraries for functions to link in with the main program and its subroutines as they are defined in the source file At the present state of development it was preferred to have many small libraries rather than a few larger ones So four or five libraries are specified on the command line for the linker Different types of libraries can be distinguished i A library containing functions used on a regular basis by a user such as those performing operations on strings the family of printf functions atoi etc These are collected in libe a which can be considered as a very modest imitation of the standard C library The contents of libc a are shown in Table 3 5 page 61 in the
8. 0008 ZD2 etc etc Hexidecimal Area Addr Size Decimal Bytes Attributes _DATA 2CSB 0016 22 bytes REL CON 2C5B _tcbmain Hexidecimal Area Addr Size Decimal Bytes Attributes _BSS 2C71 000D 13 bytes REL CON 2C71 _tid 2C73 _pia_mode 2C74 _pshbttn 2076 _mainpid 2C78 _cipid 2C7A _ciprio Hexadecimal etc etc After compiling the program with cc09 tdb09 v Wall ttif c we run it with db09 The debugging session is shown here As the program goes astray we decide that we will start by setting breakpoints just before and just after the functions called from the main program one by one The first function call is to thread_create so this is where we will put breakpoints for a start From the listing we see that the load address of the main pro Workshop on Distributed Laboratory lnstrumentation Systems 148 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt gram corresponds to its entry point which simplifies the calculation of the addresses where to put breakpoints For the explanation of what is going on see the comments which start with a and which have been added later rinus katje romtest db09 v ttif invoke db09 in verbose mode abO9 gt 1 ttif log keep a log of the session db09 gt i inf get the first commands from db09 gt Clock Interrupts have been disabled input file inf db09 gt Watchpoint 0 at ad
9. Blocking Will not block Applicable All devices init 5 Device initialisation Arguments A 95 B Mode X bit mask to determine input output lines PIA mode 0 only Returns A Semaphore number PIA modes 2 and 3 only Blocking Will block Applicable All devices The system initialises all devices except ACIA1 during system initialisation This driver must explicitly be initialised before use The PIA is initialised to mode 0 by default Continued on next page Table D 1 Device driver function calls Continued Workshop on Distributed Laboratory Instrumentation Systems 108 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherili Continued from previous page Function Description and behaviour ilock 6 Lock input mutex Used to construct a safc multitasking device driver by guarding the resource Arguments A 6 Returns Nothing Blocking Will block Applicable Al devices except DAC Unlock input mutex Arguments A 7 Returns Nothing Blocking Will block Applicable All devices except DAC Lock output mutex Arguments A 8 Returns Nothing Blocking Will block Applicable All devices except ADC Unlock output mutex Arguments A 9 Returns Nothing Biocking Will block Applicable All devices except ADC Single read channel Arguments A 10 Returns B
10. Get a character cast to int from device Get character cast to int from stdin Get a string from stdin and put in buf Copy size bytes from sre to dest Print arguments to stdout using format fmt As printf above but cannot handle floating point Internal use by printf fprintf Internal use by printf fprintf Internal use by printf fprintf print a character to file i print a character on stdout Output string at address p to stdout Sleep for n seconds See also msslecp Print arguments to buf using format fmt As sprintf above but cannot handle floating point Put char c into buf Compare string at s with string at t Copy string at t to s Return length of string at str Table 3 5 Functions available in libe a Workshop on Distributed Laboratory Instrumentation Systems 61 Abdus Salam IC TP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Sm ii iii The reader should note that printf is accompanied by a function protf The difference is that the former can print fleating point numbers whereas the latter is limited to printing intcgers single char acters and strings The same holds for the functions fprntfQ and sprntf In those cases where a program does not use floating point numbers u
11. 2 1 Task Control Block structure field offsets 0 02 21 2 2 Thread state values lt 4 9 8 8 2 Ge a A a 22 2 3 Parameter structure offsets for thread creation 23 2 4 Stack layout before dispatching of thread a aaa 24 2 5 Thread attribute fields a 0a aaa a a 24 2 6 Summary of thread management system calls 30 2 7 Semaphore structure definitions 04 32 2 8 Semaphore type values 44s aie ea ee ee a 33 2 9 Summary of semaphore management system calls 36 2 10 Summary of memory management system calls 37 2 11 Message structure offsets 2 ee ee ee 39 2 12 Signal structure offsets aa eh oe Gg ee oe 39 2 13 Pipe structure offsets ao wil Se ts es BM A 2 14 Summary of interproccss communication system calls 43 2 15 Interrupt table offsets do a Ye Bo eA SS 44 2 16 Device driver function requests 2 0 2 2040 45 2 OCs usage o 2 vind oh aww ae pcs oe Le een owe tb 47 2 18 Device driver installation structure 2 0 2 0 0 AQ 2 19 Commands supported by the ICTPmon Monitor ol 3 1 Useful options to pass to the C cross compiler 59 3 2 Options for the assembler as6809 2 2 2 0404 56 3 3 Options for the linker aslink bua 4 wis By Root Ba ee ee 57 3 4 Example memory layout of a compiled program 58 3 5 Functions available in libe a 0 0 0 4 61 3 6 Interface Functions for RINOS System Calls
12. With multi threaded programs in mind a large space is reserved for stacks The same amount of space is reserved for the allocation of Direct Pages Each thread should get its own direct page to protect the pseudo and floating point registers used by the thread from being corrupted by another thread 0x2100 possibly occupied by another program 0x4100 Arguments 0x4300 main program followed by subroutines defined in the source file library functions DATA area BSS area direct pages Ox 00 0x0400 upto stacks Ox 00 0x0800 Table 3 4 Example memory layout of a compiled program The assembler and linker are fully documented in the file asmink doc with supplementary information in asmlnksup doc These files can be found in the directory usr local micros m6809 doc The recent additions to handle the symbolic debugging information are NOT described in there 3 3 The startup routine crt0 o The linker follows a strict order for collating the various modules into the code of the final program the startup routine crt0 o comes first followed Workshop on Distributed Laboratory Instrumentation Systems 38 Abdus Salam ICTP Tneste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt by the modules specified on the linker s command line usually the main program and its subroutines Finally the libraries are searched to fill in the missing re
13. second part of movhi default 0032 EC 8D 00 64 39 lda _ctprio per first part of movhi default 0036 34 06 40 pshs d second part of movhi case PRE_DEC 0038 30 8D 00 00 41 leax _tcbmain pcr address of symbol gt X 003C 1F 10 42 tfr x d 1st part of movhi for symbol or label 003E DD 00 43 std ZD0 second part of movhi REG 6040 i7 GO 00 44 lbsr _thread_create CALL R ZD0 _thread_create 2 bytes 0043 32 62 45 leas 2 5 addhi Ris Ris 2 6045 De 00 46 ldd ZD0 first part of movhi for REG 0047 DD 00 47 std ZDi second part of movhi REG 0049 DC 00 48 ldd ZDi first part of movhi for REG 9048 ED 8D 00 02 49 std _clpid per second part of movhi default Workshop on Distribuled Laboratory Instrumentation Systems 145 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt OO4F EC 8D 00 02 50 ldd clpid per tsthi H _cipid per 0053 10 20 60 03 51 lbge L2 bge long branch 0057 17 00 00 52 lbsr _printerr CALL 0IDmode _printerr pecr 0 bytes OO5A 53 L2 0054 4F 54 clra OO5B 5F 55 clrb first part of movhi for 0 GOBC 34 06 56 pshs d second part of movhi cass PRE_DEC GOSE EC 8D 00 02 57 ldd _clpid per first part of movhi default 0062 DD 00 58 std ZD0 second part of movhi REG 0064 17 00 00 59 lbsr _thread_join CALL R ZD0 _thread join 2 bytes 0087 32 62 60 leas 2 s addhi R s Ris 2 6069 1
14. 0 No timeout allowed by POSIX 1003 1 so always clear swi Wait for child thread to terminate fcb OSThreadJoin Terminate implicitely rts Child thread function This function does nothing char child void child explicit t ermination via system call ldb 1 This value is returned to any waiting thread swi fch OSThreadExit rts Return to system should not execute this thread_cre thread_creat Offsets on ate thread handle attribute attr void start attribute attr e stack 0 Return address 5 2 Thread argument address S 4 Thread starting address 5 6 Attribute address leau 0 8 Establish stack frame leas POSIZE s Place thread creation block on stack Fill in th read creation structure using attribute and function arguments ldy 6 u Point at the attribute leax 0 8 Point at the creation structure l d attr_stackaddr y Get requested address Workshop on Dis 120 tributed Laboraiory Insirumeniation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 Sofiware for the 6809 Microprocessor board Verkerk and A J Wetherilt bne cthreadl Requested stack address is null so create a new stack using memory manager pshs leau lda ldx swi fcb sta stx sty leay puls cthread1 leax ida sta 1dd std ldd std idd std ldd std ldd std lda sta ldd std lda ora ora sta lda sta Issue call to lda swi fcb u Need an extra register 0 y attr
15. 1 Thread s direct page Table 2 3 Parameter structure offsets for thread creation 2 4 2 Thread Creation The process of thread creation by an application program or the monitor are identical and similar to that of the creation of the null thread during system initialisation Whereas the null thread takes values from the system to fill its various fields these values must be supplied for other threads by the user This takes the form of supplying a table of values that the thread creation function can access to obtain the information it needs to perform its task This structure is given in Table 2 3 page 23 Under RInOS threads are created using code already loaded and in posi tion the monitor only creates the thread after it has downloaded the code This means that RInOS must be told where the code can be found This is done by the use of the PSEG and CSEG fields of the Thread Parameter Table TPT These provide the page and the start of the code used by the thread respectively and are copied directly into the PAGE and CODESEG fields of the selected TCB Similarly the start and length of the stack segment given by SSEG and SLEN are copied into STACKSEG and STACKLEN in the TCB The actual entry point of the code to be executed by the thread is specified by the CSTART field and is copied into the initial thread context set up on its stack RInOS accepts arguments to a thread in the form of a pointer to the arguments in the ARGPTR fic
16. 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and AJ Wetherilt tcbmain tdp tcbmain tdp 1 tcbmain cstart child1 if chipid thread_create prior amp tcbmain lt 0 printerr return chipid Workshop on Distributed Laboratory Instrumentation Systems 134 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix K Assembler listing of a compiled program The following is an cxample of an assembler listing produced by the cross compiler assembler linker chain The comments have also been generated by the compiler and are reproduced without having done any editing The program is the same as the second example in the preceeding Appendix 6000 6000 OOOA OO0B OO0R 0018 0019 0019 001C 001E 4E 20 a 77 72 g0 32 34 1F 6F 74 69 6F Eg 20 42 77 20 69 73 68 65 6E 74 65 72 66 20 SF 75 ES 17 18 19 26 21 22 23 24 25 26 27 28 29 Start MC6809 xgcc assembly output xgce compiler compiled on katje This is version 4 0 6 of xgce for m6809 OPTIONS mlong_branch strength reduce OPTIONS pesphole omit_frame_pointer signed char Source tt2e Destination tmp ccaQ1132 s Compiled Tus Aug 25 15 06 50 1998 3 CMETA compiled by GNU C version 2 7 2 module tt2c c area _BSS area _CODE Leo ascii Now is the byte 0x0 Lei ascii winter of our byte 0
17. EC 8D OO 02 86 ldd _clpid per first part of movhi default 0044 DD 00 87 std ZD0 second part of movhi REG 0046 17 00 00 88 lbsr _send_message CALL R ZD _send_message 2 bytes OOAS 32 62 89 leas 2 s addhi Ris Ris 2 OOAB DC 00 90 ldd ZD0 first part of movhi for REG OOAD DD 00 91 std ZD1 second part of movhi REG Workshop on Distributed Laboratory Instrumentation Systems 136 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt OOAF DC 00 92 ldd ZD1 tathi R ZD1 OOB1 10 2C 00 03 93 lbge L bge long branch OOBS 17 00 00 94 lbsr _printerr CALL VOIDmode _printerr per 0 bytes OOBS8 95 LS OOB8 1F 20 96 tir y d OOBA C3 00 OF 97 addd 15 GOBD DD 06 98 std ZD1 addhi3 y by 15 gt ZD1 OOBF DC 00 99 ldd ZDi first part of movhi for REG 00C1 34 06 100 pshs d second part of movhi case PRE_DEC 0003 E 8D 00 62 101 ldd cipid per first part of movhi default oac DD 00 102 std ZD0 second part of movhi REG o0c9 17 00 00 103 lbsr _send_message CALL R ZDO _send_ message 2 bytes goce 32 62 104 leas 2 s addhi R s Ris 2 QOCE DC 00 105 ldd ZD0 first part of movhi fer REG OODO DD 00 106 std ZDi second part of movhi REG o0D2 DC Oo 107 ldd ZD tsthi R ZD1 00D4 10 2C 00 03 108 lbge L6 Chge long branch OODS 17 00 00 109 Ibsr _printerr CALL VOIDmode _printerr per 0 bytes 00
18. Input byte PIA D Input word ADC Blocking Will not block Applicable ADC PIA only Continued on next page iunlock 7 olock ounlock bread2 10 Table D 1 Device driver function calls Continued Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste Noyember 26 December 21 2001 109 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Function Description and behaviour bwrite2 11 Arguments Returns Blocking Applicable sread2 12 Arguments Returns Blocking Applicable Single write channel2 Multiple read channel2 A ll B Byte to write PIA D Word to write DAC Nothing Will not block DAC PIA only A 12 X Address of ata holding buffer Y Number of conversions to make ADC Nothing Will block ADC PIA modei only Table JD 1 Device driver function calls Continued Description Hardware device driver identifiers acial 0 Serial port 1 driver acia2 1 Serial port 2 driver pia 2 Parallel port driver ade 3 ADC driver dac 4 DAC driver timer 5 Timer 3 driver pia device driver modes used when opening the device pia_std 0 PIA standard mode pia_ hndshk 0x10 PIA handshaking mode pia_led 0x20 PLA LCD board mode pia_colombo 0x30 PLA C
19. MC6809 MC6809E Microprocessor Programming Manual Motorola Inc 1983 90 Chapter 6 Credits e The ICTP monitor was adapted from Motorola s Assist09 by Jim Wetherilt The multitasking kernel running from EPROM on the 6809 board was developed by Jim Wetherilt Inspired by Motorola s MCX11 Real Time Executive it was practically rewritten from scratch and many important features added The GNU C cross compilers for the 6809 and 6811 processors have a rather long story The original machine description and macro files for the 6809 were developed by Th E Jones University of Wisconsin jones sal wisc edu and then adapted to the 6811 processor by Otto Lind otto coactive com Carlos Kavka used the latter with only a minor modification to build a cross compiler for the 6811 We config ured the 6809 cross compiler from this 6811 version as we felt it to be superior to the original 6809 compiler During the autumn of 1997 the 6809 cross compiler was upgraded to ac cept floating point The floating point library was built from a package written in 1986 for the 6811 by Gordon Doughman Motorola Semicon ductor Dayton Ohio revised in 1988 by Scott Wagner Rochester In strument Systems Rochester New York and further revised in 1993 by P D Hiscocks University of Alberta Canada The Perl script elvn2nin was used to transpose from 6811 code to 6809 assembly code During Spring and Summer 1998 the cross compiler
20. Microprocessor board C Verkerk and A J Wetherilt translate from the more familiar formats to the directives of as6809 For an obvious reason it is called jim2rinus and it can be found in the directory usr local micros m6809 src tools perl The assembler will produce output files according to the options specified when it was invoked As the compiler does not specify an origin for the code the program will be assembled assuming O zero as origin The linker aslink will link object files produced by the assembler with a startup routine crt0 o and will search the libraries specified on its command line for routines referenced This process is recursive so that a library routine may reference in turn other functions In the course of linking memory references are relocated and the various CODE areas pasted together The same is done for the pieces of the other arcas _DATA and BSS The linker also accepts a few options the essential ones are cnumerated in Table 3 3 page 57 The linker will produce three output files two with extensions map 1819 and a third without any extension The first gives a complete memory map for all global symbols in each defined area The addresses shown in the map file are determined by the origin passed as an option to the linker 0x0000 for Position Independent Code The second file is there for historical reasons and is at present not used It is a file in Motor
21. Most of them have an unconventional calling sequence making them unusable from a C program vi Recently a new library was added implementing the major part of the POSIX standard concerning multi threaded programs the so called pthreads This library lippthread a is entirely written in C and makes use of the functions in libcreal a The prototypes of the functions it contains are shown in Table 3 12 page 69 For morc details sec Annex III of Chapter 1 Volume I of the Lecture Notes Workshop on Distribuied Laboratory Instrumentation Systems 67 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for Lhe 6809 Microprocessor board C Verkerk and A J Wetherill f Function Purpose divhi3 Divide two signed 16 bit integers divxbd Divide contents of X register by those of D register unsigned imul Do a 16 bit by 16 bit multiply unsigned modhi3 Modulo of two signed 16 bit integers mulhi3 Signed multiply of two 16 bit integers udivhi3 Unsigned divide of two 16 bit integers umodhi3 Unsigned modulo of two 16 bit integers Table 3 10 Functions available in libgcc a Purpose Function Prototype asc2fit char num float loc flt2asc float sre char dest flt2int fltadd float dest float src1 float src2 fitdiv float dest float srcl float src2 fitmul fioat dest float srel float src2 fitround fltsub float dest float srel float s
22. Note that the assembly leve debugging commands are also available in both cases but the user should be aware that there are considerable differ ences between low level db09 and ICTPmon on the board 4 5 Symbolic Debugging Commands The symbolic debugging commands use a single capital letter for the command itself in contrast to the low level commands which use a single lower case letter To sce the help screen you should type the letter H followed by a carriage return Typing a will show the low level command set In the help screen the commands are given in alphabetical order In what follows we will follow a more didactical approach 4 5 1 Creating a log of your debugging session It is highly recommended to keep a log of your debugging session to avoid that something escapes your attention when it is scrolled off the screen Also the instructors will be grateful if you can show them precisely what you did To create a log file simply type L mylog or something similar when the db09 gt gt prompt appears on your screen The L command without a filename will close a previously opened log file 4 5 2 Setting and using breakpoints You can specify either a line number or a symbol name to indicate where you wish to place a breakpoint You may have compiled a set of files and as the same line number may appear in more than one file the name of the source file where the breakpoint should be placed must also be specifie
23. Semaphore number On cerror A ERR SEMCREATE Blocking Will not block OSFreeSem 2 Release existing system semaphore Arguments A Semaphore number Returns Nothing On error A ERR BADSEMA Blocking Will not block OSDownSem 3 Perform a down on a given system semaphore Arguments A Semaphore number Returns Nothing On error A ERR_BADSEMA Blocking Will block Continucd on next page Table C 1 System calls 98 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSUpSem 4 Perform an up on a given system scmaphore Arguments A Semaphore number B 1 if all waiting threads are to be released Returns Nothing On crror A ERR BADSEMA Blocking Will not block OSResetESem 5 Reset an event system semaphore Arguments A Semaphore number Returns Nothing On error A ERR BADSEMA Blocking Will not block OSFrecUserSem Release existing user semaphore Arguments X Address of semaphore Returns Nothing On error Nothing Blocking Will not block OSDownUserSem Perform a down on a given user semaphore Arguments X Address of semaphore Returns Nothing On crror Nothing Blocking Will block OSUpUserSem Perform an up on a given user semaphore Arguments X Address of semaphore Returns Nothing Onerror Nothing Blo
24. _cipid blkb 2 103 glebl _cipric 0004 104 _ ciprio blkb 2 105 END We will also need to consult the file ttifmap We reproduce here only those parts that are of interest for our debugging example Hexidecimal Workshop on Distributed Laboratory Instrumentation Systems 146 Abdus Salam ICTP Trieste Novernber 26 December 21 2001 Software for the 6809 Microprocessor board CG Verkerk and A J Wetherilt Size 0000 0000 DIRECT_start 000D _BSS_length 0016 _DATA_length OO3F DIRECT_length OBSB _CODE_length 1000 PAGES_length 1000 STACK length 2100 _CODE_start 2C5B _DATA_start 2C71i _BSS_start 2CTE PAGES_start 3C7E STACK_start Size OB5B 2100 _arge 2104 _argstr 2180 _argv 2200 _start 22CC __ main 22EA exit 2300 _main 2382 _childl 2394 _prntf 23CA _printerr 259E _putc 268C __dprnt 294C _thread_join 296F _thread_create 2992 _thread_exit 29C0 __prtio 2A8F __prtl6 2B38 _ICTP_I0O_write 2B6E ___modhi3 2BA1 divhi3 2BD6 _divxbd Decimal Bytes Attributes 0 bytes ABS OVR Decimal Bytes Attributes 2907 bytes REL CON Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste Novernber 26 December 21 2001 147 Software for the 6809 Microprocessor board Verkerk and A J Weitherilt Hexidecimal Area Addr Size Decimal Bytes Attributes DIRECT 0000 QOO3F 63 bytes ABS OVR PAG Value Global 0000 ZzDO 0004 ZD1
25. a modhi3 o appl micros m6809 1lib libgec a divhi3 o appl micros m6809 lib libgec a divxbd o User Base Address Definitions _ CODE 0x2100 Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 143 Appendix M A debugging session with db09 The program ttlf c which is buried somewhere in the directory tree of usr local micros m6809 use find to find it is faulty It is a super Hello World program and it should create a child thread which then prints those famous words It disappears into blue sky instead Here is the program include lt syscalls h gt extern int tid extern struct creation_block tcbmain int mainpid cipid clprio Function prototypes void main void void childi void void main void 4 Set up tcbmain and create a child thread Then wait for it to finish before exiting tcbmain sseg tcbmain sseg 0x0100 tcbmain tdp tcbmain tdp 1 tcbmain cstart childl clprio 3 clpid thread_create amp tcbmain cliprio thread_join cipid 0 vyoid thread_exit 144 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt void childi void printf Hello World n return In order to debug this program we will need to consult the assembler listing reproduced below bine ee tee ee tee e a ee eee ees 2 33 Start MC6809 xgcc asse
26. address is in RAM at Ox012e so that breakpoints can be set on the null thread for debugging ii The STATUS field is cleared indicating that the null thread is capable of being run when scheduled to do so The STATUS field is used to indicate the thread state a non zero value indicates some condition preventing the thread from being run Possible values for this field are given in Table 2 2 page 22 The null thread can only take the value zero since it is always runnable Other threads however can have any values depending on the current state Prior to creation and when totally dead a TCB will show the value NOTASK 0x80 indicating that this TCB is eligible for use A zombie thread is one which has finished its activity but has the possibility that other threads will wait for its demise and therefore cannot release its TCB entirely Such a thread will have the value SUSPEND Oxc0 A thread put to sleep will show the value SLEEPING 0x06 and a blocked thread will indicate WAIT 0x04 The final legal value IDLE 0x02 is used by the system to indicate that a TCB has been reserved for use but is not yet runnable State Value Description _NOTASK 0x80 TCB not used SUSPEND 0xC0O Thread suspended WAIT 0x04 Thread blocked SLEEPING 0x06 Thread sleeping IDLE 0x01 TCB claimed but not yet running READY 0x00 Thread running or waiting to run Table 2 2 Thread state values iii The priority va
27. and A J Wetherilt 4 2 New features added in 1999 With the aim of implementing a symbolic debugging capability a number of modifications were made to the cross development software for the ICTP m6809 board These changes resulted in a more unified approach to the software for the m6809 which in turn led to considerable simplification for the user of the cross software Untill recently debugging a program written for the m6809 board was rather difficult and required consultation of assembly listings and load maps needing a basic knowledge of the m6809 instruction set and also the ability to do mental calculations in hexadecimal Both skills are not necessarily available to a C programmer Symbolic debugging uses line numbers of the C program and the names of symbols variables constants function names etc in the interface to the user The programmer can thus track bugs in his code with greater casc with the need to consult only the listing of the C program The modifications made to the software chain are in summary i The compiler was made to accept the g option It now adds to its output file of assembly code the necessary information to make sym bolic debugging possible the stabs pseudo instructions which convey information about the type of symbols line numbers of the C source code and the block structure of the program ii The assembler was upgraded to accept these pseudo instructions and to associate a mem
28. board C Verkerk and A J Wetherilt Function Prototype struct tcb get_thread int handle int pthread_attr_destroy pthread attrt attr int pthread_attr_getdetachstate pthread_attr_t attr int detachstate int pthread_attr_getschedparam pthread_atir_t attr struct sched_param param int pthread_attr_getstackaddr pthread_attr_t attr void stackaddr int pthread_attr_getstacksize pthread_attr t attr size_t stacksize int pthread_attr_init pthread_attr_t attr int pthread_attr_setdetachstate pthread_attr_t attr int detachstate int pthread_attr_setschedparam pthread_attr t attr const struct sched_param param int pthread_attr_setstackaddr pthread_attrt attr void stackaddr int pthread _attr_setstacksize pthread_attr_t attr size_t stacksize int pthread_cond_broadcast pthread_cond_t cond int pthread_cond_destroy pthread_cond_t cond int pthread_cond_init pthread_condt cond const pthread_condattr_t attr int pthread_cond_signal pthread_cond t cond int pthread_cond_timedwait pthread_cond_t cond pthread mutex_t mutex const struct timespec int pthread_cond_wait pthread_cond_t cond pthread mutext mutex int pthread_condattr destroy pthread _condattr_t attr int pthread _condattr init pthread condattrt attr int pthread_create pihread t thread const pthread_attrt attr void startfunc void void ar int pthread_detach pthread_t thread int pthread cqual pthread_t thread1
29. file syscalls inc Call the function with swi2 byte device_identifier Function bread Description and behaviour Single read channell Arguments A 0 Returns B Input byte byte devices D Input word word devices Blocking Will block ACIA1 ACIA2 PIA mode 1 Applicable AlL devices bwrite Single write channel Arguments A 1 B byte to write byte devices X Word to write word devices Returns Nothing Blocking Will block in most modes Applicable Al devices Continued on next page Table D 1 Device driver function calls Software for the 6809 Microprocessar board C Verkerk and A J Wetherilt Continued from previous page Function Description and behaviour sread 2 Multiple read channell Arguments A 2 X Address of holding buffer Y Number of conversions ADC only Returns Nothing Blocking Will block ACIAL ACTA2 PIA mode 1 Applicable All devices except DAC ACIA1 ACIA2 PIA mode 2 will have null terminated buffers swrite 3 Multiple write channell Arguments A 3 X Address of buller to write Returns Nothing Blocking Will block Applicable All devices except DAC ADC ACIA1 ACIA2 PIA mode 3 will have null terminated buffers IOCTL Arguments A 4 B Byte to write to register Write mode high X Read Write 1 0 low X Offset from base register Returns B Byte read from register Read mode
30. line 4 5 5 Investigating the values of variables 2 0 4 5 6 Show the contents of the stack 2 00 2202 4 5 7 Using an input file containing debugging commands 4 5 8 Repeating a command 246 9 5 02 be ee 4 5 9 Starting and exiting 3 oo 5 0 bbls fal bw oe es 5 Bibliography 6 Credits A m6809 Registers and programming model B Returned error codes Workshop on Distributed Laboratory Instrumentation Sysiems Abdus Salam ICTP Trieste November 26 December 21 2001 49 49 49 50 52 53 53 56 58 60 69 71 71 74 TT ST S7 88 88 89 90 91 93 96 Sofiware for the 6809 Microprocessor board C Verkerk and A J Wetherilt C System calls 98 D Device driver function calls 107 E Structure and definitions reference 111 F Linked lists used by RInOS 116 G Programming examples assembly language 118 G 1 Create a thread using POSIX 1003 1 compatible method 118 H A debugging example 122 System calls from C 127 J Programming examples in C 129 J 1 A sample program using pipes 22 129 J 2 A similar program using messages 0 08 132 K Assembler listing of a compiled program 135 Example of a map file 140 M A debugging session with db09 144 N An example on board symbolic debugging session 152 Workshop on Distributed Laboratory Instrumentation Systems 3 Abdus Salam ICTP Tricsic November 26 December 21 2001 List of Tables
31. memory in short IEEE format occupying 32 bits Three floating point pseudo accumulators are defined in the direct page in a format more convenient for arithmetic operations than the format used to store floating point numbers in memory The other pseudo registers are also 32 bits wide so that they can contain floating point numbers The floating point operations are emulated by a package of floating point routines The compiler inserts a call to the appropriate function for every floating point operation The same is actually also true for a number of arithmetic oper ations on integers and bytes for which no equivalent machine instructions exist Floating point numbers can be part of a structure or union The earlier versions of ccf the latest of those versions is 3 4 6 could only generate absolute code which must be loaded into memory at a fixed address During spring and summer of 1998 a new version at present version 4 0 7 of ecf was prepared which produces Position Independent Code PIC that will execute correctly at any address in memory Version 4 0 7 is installed on the system as the standard cross compiler The PIC code produced by the standard version makes it possible to make full use of the facilities of the RInOS kernel Loading of a user program and starting its execution is different for PIC and absolute code At the present state of development absolute code is very rarcly used The cross compiler accepts the usual and useful
32. of the interruption If so the entries in the interrupt vector table correspond ing to the device are loaded and a jump is performed to the device interrupt function defined in the table Since the table is in RAM a user can change the default behaviour by inserting new values into the table The vector table itself is initialised during system initialisation At the top 256 bytes of shared RAM the monitor maintains its own work area Immediately below this RInOS creates first the stack for the null task and secondly the system stack The remainder of the shared memory is available for use by both the system and applications as required A map of shared RAM is given in Figure 2 2 on page 14 Use of the ROM is divided into three areas The first of these starting at Oxc030 contains the RInOS code The monitor resides at Oxf000 The third area is a table of jump vectors at Oxfff2 that is used by the 6809 processor to vector resets and hardware and software interrupts On initial booting the processor reads the value located at Oxfffe and jumps to that value This is the start of the monitor After performing its initialisation the monitor calls the RInOS initialisation manager at Oxc030 and waits for keyboard input User applications are downloaded to the paged RAM area by the mon itor Two methods of loading are possible depending on whether the code is relocatable or not If the code is relocatable it has an assumed origin of 0 and must be
33. pointers argv and puts the pointers in the same reserved space where the main program can pick them up iii It reserves space in the DATA area for a structure needed by the function thread_create For the convenience of the user this structure is filled with initial values ready to be used for generating child threads see a later chapter for more details The structure is described in Chapter 2 Table 2 3 page 23 iv It reserves space for a few global variables in the BSS area tid pia_mode and pshbttn Workshop on Distributed Laboratory Instrumentation Systems a9 Abdus Salam ICTP Tricste Novernber 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt v It also reserves space for a number of Direct Pages one for cach thread upto a number of MAXTHREADS defined in syscalls h and for an assembly program in syscalls inc Space is also reserved for the same mimber of stacks This reserved space is useful for multithreaded programs If a user feels that they occupy too much space he may increase the value of MAXTHREADS which is normally set to 4 During execution it sets the value for the Direct Page register and the U register for the main thread The PIA is opened for writing to the LCD display In case the program is running under db09 with the simulator of the m6809 instructions a call is made to initialize the kernel followed by a call to OSThreadInstall
34. reach line 15 x x x gt LCD Display s 007 d 7 lt LCD display now shows this db09 gt Repeat the N command Function Call _mssleep Breakpoint reached Line 16 file pt4 c To reach line 16 xxae gt LCD Display s 007 d 7 lt k With the same display db09 gt Repeat N once more Function Call _exit To get into _exit in crt0 Now nothing Line 17 file pt4 c more happens We pushed the on board reset xx x gt LCD Display ERROR NONE Soke And obtained this db09 gt exit At the prompt we type exit Besides the use of the B N and G commands this example has shown how one can inspect the value of a variable D command and the values of function arguments and its return value A command In addition the L and T commands were illustrated We also demonstrated that low level commands of ICTPmon are accessible from within db09 in fact all commands which are defined by a single letter can be used Workshop on Distributed Laboratory Instrumentation Sysiems 156 Abdus Salam ICTP Trieste November 26 December 21 2001
35. requests 2 8 1 Interrupt handling within the device driver All hardware interrupts are processed by the hardware interrupt handler in the RInOS kernel Each hardware device is polled to ascertain whether it was the cause of the interruption and if so a jump is made to the address of the device interrupt handler contained in the ISR_ADDR field of the device entry in the interrupt service table This Handler routine is an integral part of the driver for each device that can raise interrupts The first function of any handler must be to remove the cause of the interrupt by performing whatever action is required for the interrupted device This usually takes the form of reading a status register somewhere on the device If such an action is not performed when the handler returns or unmasks the interrupt the interrupt will again occur and will probably lead to system failure The interrupt handler should keep the interrupts masked only as long as strictly necessary to prevent any potential interrupts from other sources going astray The interrupt handler can and often does perform actions that result in a context switch when the interrupt is finished A typical example of such an event is the unblocking of a thread waiting for device input The interrupt handler should take care not to change any register in the stacked context of the interrupted thread as a hardware interrupt is asynchronous and the registers contain potentially vital information
36. roundf float x float ceilf float x float floorf float x float fabsf float x float fmodf float z float y float frexpf float x int exp_ptr float Idexpf float x int e float modff float x float int_ptr float fractint float 2 float int_p r Exponentials Logarithms and Powers Returns the sine of the angle s in degrees Returns the cosine of the angle x in degrees Returns the tangent of the angle x in degrees Returns the arctangent in degrees of z Not yet implemented Not yet implemented With z in degrees returns value in radians With x in radians returns value in degrees Returns the natural logarithm of x Returns the logarithm base 10 of z Returns e to the power 2 Returns 10 to the power s Returns to the power y Returns the square root of x Polynom is basis of many functions above coeff is pointer to first element of array of fit pt coefficients ending with byte Oxf Returns the value of the constant 7 Returns the value of the constant e Returns the integer nearest to the value of z NOTE casting float to integer will truncate Returns as a float the smallest integer not less than 7 Returns as a float the largest integer not greater than T Returns the absolute value of z Computes the remainder of z y Returns xz n y where n is the quotient z y rounded toward zero to the nearest integer Free exponent Returns float stores
37. the flow of control So the N for Next linc command may also go backward in your program and follow loops faithfully More on the N command later You should use the G command to proceed from a breakpoint at a function entry db09 will put automatically a breakpoint at the return point of the function and it will show the return value when it hits this return point For a library function the type of the return value will again be a guess unless you used the A command before You may also use the B command without an argument it will show you a list of the breakpoints set in your program 4 5 3 Removing a breakpoint It is easy to remove a breakpoint Simply use the K command with the same argument that was used before to set it Examples K ttlilel c 39 K printf K without any argument will kill all breakpoints 4 5 4 Executing your program line by line The N command allows you to step through your program line by line You should first set a breakpoint at the first line or further down in your program if you are confident about the first part and then launch the execution with the X command Once you stopped at a breakpoint you may continue line by line by typing N Note that N 1 is equivalent to N N 7 or any other positive number is also allowed It will step through a number of lines without stopping but you should be aware that the results shown may be slightly different in particular for multi threaded programs The
38. the PIPE_REAR pointer is loaded with the address of the buffer start contained in the PIPE_MEM field Otherwise the pointer is incremented by the width of the pipe After both reading and writing the mutex lock is released When the reading or writing operations have finished the pipe should be closed by calling either OSWClosePipe or OSRClosePipe These fuctions perform UPs on either the PIPE_RMTX or the PIPE_WMTX and allow other threads reading or writing access to the thread A pipe can be released if desired using the OSReleasePipe call All semaphores arc returned to the pool and the buffer memory released back to the system Finally the PIPE_USED flag is incremented to indicate that the structure is free Workshop on Distributed Laboratory Instrumentation Systems 42 Abdus Salam ICTP Trieste Noyernber 26 December 21 2001 Sofware for the 6809 Microprocessor board G Verkerk and A J Wetherilt Function Value Category Description OSSend Message 6 OSWait Message 7 OSGetMessage 8 Message Message Message Send a message to a thread Send a message and wait for response Receive a message OSSignal 9 OSWaitSignal 10 OSResctsignal 30 Signal Signal Signal Send a numbered signal 0 31 Wait for a numbered signal Reset a numbered signal OSCreatePipe 3l Pipe Create a pipe OSReleasePipe 32 Pipe Release a pipe OSWOpenPipe 33 Pipe Open a pipe for writing OSWClosePi
39. to terminate OSThreadKill 16 Kill a specified thread OSSetPriority 17 Set the priority of the current thread OSSleep 18 Put the current thread to sleep for specified clock ticks OSWake 19 Wake a specified thread OSAtExit 25 Set an exit function for the current thread OSGet TaskInfo 26 Get a pointer to the TCB of the current thread OSSet Thread Attr 27 Set the attribute of the current thread OSCancelPoint 28 Cancel the current thread if cancellation pending OSGetLastError 29 Get last error code of the current thread Table 2 6 Summary of thread management system calls 2 4 6 Summary of thread management system calls A complete list of system calls used in thread management is given in Ta ble 2 6 page 30 2 5 Semaphore management Semaphores are perhaps the most important ingredient in a real time sys tem after the mechanisms for process management in that they allow the full use of the system facilities in a secure manner Without the invention of semaphores real time programming in particular and all multitasking ac tivity would be radically different Semaphores provide a means of sharing system resources in such a way as to prevent simultaneous access to critical regions Although several other constructs can provide protection for these critical regions semaphores are perhaps better suited and more general in nature A semaphore is basically a lock that can be applied to a region of code that needs to be protected from m
40. together with various switches and push buttons for simulating events The LCD display consists of 16 alphanumeric characters and can be accessed using function 1 of the device driver Null terminated strings of up to 16 characters can be written to the display using function 3 The state of a dip switch can be read using function 0 and an 8 strip LED on the board can be written to using function 11 It is possible to wait for a pushbutton on the board to be pressed During initialisation of the driver in LCD mode an event semaphore is created and its number returned to the user When the pushbutton is pressed the handler for the resulting interrupt makes an UP on the semaphore thus waking any threads waiting on the sernaphore Since multiple presses of the button can be expected this Workshop on Distributed Laboratory Instrumentation Systems 48 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt semaphore is resettable No debouncing is handied at this time in software as the delay necessary of the order of 5 ms is unacceptable in an interrupt handler in a real time system The Colombo board mode is similar to the LCD except that instead of the liquid crystal display the board has four 8 segment light emitting diodes It reads switch settings with function 0 and writes hexadecimal values to the LEDs using function 1 An interrupt is raised by the pressi
41. use flag 1 if free PIPE WDTH 1 Pipe width in bytes PIPE MEM 2 Pointer to allocated memory PIPE FRNT 2 Pointer to front of buffer PIPE_ REAR 2 Pointer to rear of buffer PIPE_FPOSN l Index of front PIPE RPOSN 1 Index of rear PIPE_FULLS 1 Full semaphore PIPE EMTYS 1 Empty semaphore PIPE_WMTX 1 Write semaphore lack PIPE RMTX 1 Read semaphore lock PIPE_LMTX 1 Pipe resource lock Table E 10 Pipe structure ISR ADDR DRIVER ADDR DATA ADDR HARDWARE _ADDR Description Off Size alee 0 Interrupt service handler Device driver address Hardware base address Device scratch data area C Verkerk and A J Wetherilt DD_INSTALLED 2 4 6 9 WM Nh NM Is driver installed Table E 11 Interrupt table structure Symbol Address size Description ctskinst 0x100 1 Current thread instance ciskpid 0x101 1 Current thread ctskptr 0x102 2 Address of current task s TCB intlvl 0x107 1 Depth of nested interrupts 0 when in a task gt 0 when interrupts are nested or in the kernel prioptr 0x108 2 Head of linked list of threads in order of priority elktsk 0x10e 2 Head of linked list of threads waiting on timer pagereg Ox10f 1 Page register copy defstack 0x111 2 Default stack size Table E 12 System variables 114 Workshop on Distributed Laboratory Instrumentation Sysiems Abdus Salam ICTP Trieste November 26 December 21 2001 Softwar
42. vi The context switch finishes with the new context being pulled from the stack and execution resuming or starting in the case of a newly created thread at the appropriate point Interrupts are unmasked as the new CCR register is pulled from the stack Hardware interrupts use the same route to return back to the point of interruption Since context switches can also occur as a result of the asyn chronous action of a hardware interrupt it is important that all code be written defensively so that any sections that are sensitive to context switch ing are guarded The kernel makes use of the masking of interrupts at ap propriate points to perform this function and safeguard itself Outside the kerncl mutexes and other synchronisation mechanisms must be employed Hardware interrupts do not affect the context of the current thread 2 4 4 Thread termination A thread can terminate in one of several ways Firstly some threads are expected to terminate in the same way that a function in C is expected to return either explicitely or implicitely issuing a return statement Under RInOS a thread can issue a rts return from subroutine statement which causes the processor to pull the address at the top of its stack into the pro gram counter registcr and jump to the address All threads have the address of the RInOS thread termination handler pushed onto the stack during thread Workshop on Distributed Laboratory Instrumentation Systems 2T Abdus
43. 001 Contents 1 Introduction 2 User Manual for RInOS 2 1 2 2 2 3 2 4 2 6 2 6 2 8 Introduction fe ac ww wn BS Bat dy See age Se a a The ICTPO9 Gari iig aia coe Bae beat eee e rads hat An overview of RInOS 2 2 2 Thread Process management 0 2 4 1 The Task Control Block 0 2 2 4 2 Thread Creation aud Se ee a Qos Tea Ww na 2 4 3 Context switching between threads 2 44 Thread termination 2 4 5 Sleeping and waking threads 0 2 4 6 Summary of thread management system calls Semaphore management 0 02 002 2 5 1 Semaphore creation 2 00 2 5 2 UP and DOWN operations a ae Gok ie ee eas we 2 5 3 Other semaphore operations 0 00 2 5 4 Summary of semaphore management system calls Memory management 2 0 2 0 0 00048 2 6 1 The common memory manager 2 6 2 The paged memory manager 0 000 2 6 3 Summary of memory management system calls Interprocess communication manager 2 0 2000 Qituky AVIGSBH ROS ei ah See ae Be he Sete dae 2 7 2 Numbered signals coke bogie Fe tS we he al Diet A PIPES voa he a oe OF wg Apa ies ae Bites he ae wea tn 2 7 4 Summary of interprocess communication system calls Device DPV CES foie sece ae emcee SS Gee ee satan Aah a ee a ae Be he 2 8 1 Interrupt handling within the device driver 2 8 2 The
44. 01 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 2 7 Interprocess communication manager Threads and processes need to communicate with each other in order to pass data and other information The life of a thread in this respect is much easier than that of a process in most systems as threads being part of the same process have the ability to share common data and code Nonetheless most systems implement a number of mechanisms for sharing data and passing data to other threads or processes The simplest of these is perhaps the use of shared memory Data can be stored by one thread and read by another with the minimum of overhead Care must be exercised however to ensure that both accesses are synchronised to prevent the occurrence of race conditions The easiest way to achieve this is to use a mutex lock to guard the shared memory resource Correctly applicd a mutex can prevent totally any race condititions developing in the system Messages are another common method of passing data One thread dispatches a message to the mailbox of another thread to indicate the occurrence of some event When the receiver gets the message appropriate action can be taken Messages are generally intended for a single recipient In some cases it is necessary to notify many or all threads of the occurrence of some event In this case a second type of message or signal must be sent Finally pipes are frequently used for communica
45. 09 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Semaphore waiting list List function To maintain a list of all threads wishing to own the resource guarded by the semaphore Iead of list NXTSEM in the semaphore body Link SEMALNK in the TCB body Semaphore owners list List function A list of all semaphores currently owned by a given thread This is required in order to release these semaphores during termination Head of list SEMAOWND in the TCB body Link SEMOLNK in the semaphore body Thread waiting list List function A list of all threads waiting for the termination of a given thread Head of list ESEMALNK in the TCB of the thread being waited for Link ESEMALNK in the TCB of the threads waiting for termination Mailbox message list List function A list of messages waiting in the mailbox of a given thread Head of list MAILBOX in the TCB body Link NXTMSG in the message body Table F 2 Linked lists in RInOS Continued Workshop on Distributed Laboratory Instrumentation Systems 117 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix G Programming examples assembly language A basic example is presented in assembler language that illustrate various aspects of the use of RInOS The assembler example uses the standard Mo torola syntax and statements and can be assembled by a user who has access to this assembler An origi
46. 2587 in the main thread If the timer is correctly jumpered issuing the command gt g PC 2587 A O1 B 02 X 005D Y 002D U 2900 S 2B7C CC 80 DP 29 gt will bring us immediately back to the same instruction This is a peculiar ity of the monitor and to proceed we must first pass through the breakpoint by removing it gt b 2587 00 012E gt g PC 012E A 00 B 00 X 0100 Y 00CO U 0000 S 1EFC CC 80 DP 20 gt The next stop is in the null thread This will only occur when no other thread is able to run either because of blocking or as a result of thread termination It is easy to determine which by examining the RInOS work area again gt d 100 80 0O 1 2 3 4 5 6 7 89 ABC OD CE FE 0100 00 01 01 30 01 01 30 00 01 30 00 FF 00 00 01 00 0 0 0 0110 00 03 00 00 00 40 00 EC 00 82 00 05 00 8C 00 D1 0 0120 00 96 00 FB 00 FF 00 FF 00 FB 00 FF 00 FY 20 FE 0130 00 00 00 01 00 00 00 EC 00 00 00 05 1E FO 00 00 0140 00 96 00 00 00 FF 00 00 00 00 00 00 00 00 00 0O 0150 00 00 00 00 00 00 00 00 01 30 01 02 04 CO 22 00 Ds csers 0160 28 80 03 00 2B 72 00 01 00 00 00 C6 AF 77 00 00 r 0170 00 00 00 23 5A 00 00 00 00 00 00 00 00 O01 00 80 Z gt Workshop on Distributed Laboratory Instrumentation Systems 125 Abdus Salam ICTP Tricsie November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Here we see that the priority list pointe
47. 28 bytes of paged RAM and thus the smallest amount of memory that can be dispensed by the paged memory manager is 128 bytes When a request for paged memory is made the size requested is again passed to the allocation call OSPAllocMem Additionally the page number 0 3 of the requested memory is passed If any page will do then the value Oxff will indicate this The selected page is searched and if a sufficiently large block of memory is found it is allocated to the calling process otherwise the ERR PALLOC error value is returned Sufficient memory to hold the requested size is always allocated if the search is successful This means that the allocated memory is often slightly larger than requested The actual size allocated is returned together with a pointer to the memory which is null on an error and the page number The allocated size should always be recorded to enable the correct size to be freed later If the memory will not be freed later then this can be avoided 2 6 3 Summary of memory management system calls Function Value Description OSCAllocMem 20 Allocate blocks of common memory OSCFreeMem 21 Free blocks of common memory OSPAllocMem 22 Allocate blocks of paged memory OSPFreeMem 23 Free blocks of paged memory Table 2 10 Summary of memory management system calls Workshop on Distributed Laboratory Instrumentation Systems 37 Abdus Salam ICTP Triesic November 26 December 21 20
48. 62 210 leas 2 s addhi Ais Ris 2 O17F DC 00 241 ldd ZDO first part of movhi for REG 0181 DD 00 212 std ZDi second part of movhi REG 0183 Be 00 213 ldd ZD1 first part of movhi for REG 0185 ED 24 214 std 4 y second part of movhi case PLUS register 1 0187 EC 24 215 ldd 4 y tsthi R 4 y Workshop on Distributed Laboratory lustrumentation Systems 138 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 0189 10 2 60 03 216 lbge L13 bge long branch 018D 17 G6 OO 217 lbsr _printerr CALL VOIDmode _printerr pcr bytes 0190 218 L13 0190 EC 24 219 ldd 4 y first part of movhi case PLUS register 1 0192 DD 00 220 std ZDQ second part of movhi REG 0194 16 00 00 221 lbra L12 0197 222 L12 223 EPILOGUE 0197 35 10 224 puls x Pulling register ZD1 0199 9F O00 225 stx ZD1 019B 35 20 226 puls y Restore stack frame 019D 32 64 227 leas 4 8 deallocate 4 bytes auto variables C19F 39 228 rts return from function 220 4p RSaea lt a ee cosa Se r SSSeeessssss5 230 END EPILOGUE for create_child 231 pj peer rrr rn rn nnn cen nnn ne e 232 area BSS 233 glebl _mainpid 0000 234 _mainpid blkb 2 235 giobl _clpid 0002 236 _cipid blkb 2 237 globl _c2pid 0004 238 c2pid blkb 2 239 globl _msglid 6006 240 _msglid blkb 2 241 globl wmsg2id 6008 242 _msg2id blkb 2 243 END Workshop o
49. 7 00 06 61 ilbsr _thread_exit CALL R ZDO0 _thread_exit 0 bytes 006C 62 Li 63 EPILOGUE 0060 35 10 64 puls x Pulling register ZD1 OO6E OF 00 65 stx ZD1 0070 35 20 66 puls y Restors stack frame 0072 32 60 67 leas 0 8 deallocate 0 bytes auto variables 0074 39 68 rts return from function 69 pg frre rrr rrr rn ern rrr rn ener nn cn eneneacen 70 33 END EPILOGUE for main TL gre rrr rt cn ccc oct cerns 0075 72 L Q 0075 48 65 6C 6C 6F 20 73 ascii Hello World 57 6F 72 6C 64 0080 OA 74 byte OxA 0081 00 75 byte 0x0 76 globl _childi 0082 77 childi MRT aaa aaa a a a 79 i PROLOGUE for childi BO gp prt tt rr rt rn se enn ee eenennn 6082 32 60 81 leas 0 s allocate 0 bytes auto variables 0084 34 20 82 pshs y Save stack frame 6086 1F 42 83 tfr s y Set current stack frame 84 END PROLOGUE 0088 30 8C EA 85 leaz LCO per address of symbol gt X OO8B iF 10 86 tfr x d 1st part of movhi for symbol or label 008D DD 00 87 std ZD0 second part of movhi REG QO8F 17 00 00 88 lbsr _prntf CALL R ZD0 _prntf 0 bytes 06092 16 00 00 89 lbra L3 0095 90 L3 91 EPILOGUE 0095 35 20 92 puls y Restore stack frame 0097 32 60 93 leas 0 s deallocate 0 bytes auto variables 0099 39 94 rts return from function Q5 py pt rr rt rrr cnc ese ecccccce 96 3 END EPILOGUE for childl Bie aos at SSS Seg Satara er renS 98 area _BSS 99 globl _mainpid 0000 100 _mainpid blkb 2 101 globl _cipid 0002 102
50. 7 Mantsgn2 0038 Fpacc3ex 0039 Fpacc3mn 003C Mantsgn3 Hexidecimal Area Addr Size Decimal Bytes Attributes DATA 2E75 0016 22 bytes REL CON 2E75 _tecbmain Hexidecimal Area Addr Size Decimal Bytes Attributes BSS 2E8B 0011 17 bytes REL C N 2E8D _pia_mode 2E8E _pshbttn 2E90 _mainpid 2E92 _cipid 2E94 _c2pid 2E96 _msglid 2E98 _msg2id Hexidecimal Area Addr Size Decimal Bytes Attributes PAGES 2F8 1000 4096 bytes REL CON Hexidecimal Area Addr Size Decimal Bytes Attributes STACK 3E9C 1100 4352 bytes REL CON Workshop on Distributed Laboratory Instrumentation Systems 142 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Files Linked module s asr lib gec lib m6809 local 2 7 2 2 crt0 o startup f tmp ecadi1321 0 tt2c c Libraries Linked object file appl micros m6809 lib libc a prntf o appl micros m6809 lib libcreal a send_message o appl micros m6809 1lib libcreal a printerr o appl micros m6809 1lib libc a putc o appl micros m6809 1ib libcreal a get_message o appl micros m6809 1ib libc a dprnt o fapp1 micros m6809 1lib libc a memcpy o app1 micros m6809 lib libcreal a 142 app1 micros m6809 1lib libc a prt10 o app1 micros m6809 1lib libc a prti6 o Jj appl micros m6809 lib libIOreal a IOwrite o appl micros m6809 lib libgec
51. Blocking Will block OSRClosePipe 36 Close a pipe for reading Arguments B Pipe handle Returns Nothing On error A ERR PUNINIT Blocking Will block OSWritcPipe 37 Write to an open pipe Arguments B Pipe handle X Address of data buffer to send down the pipe Returns Nothing On error A ERR_ PUNINIT Blocking Will block OSReadPipe 38 Read from a pipe Arguments B Pipe handle X Address of buffer in which to place data Returns Nothing On error A ERR_ PUNINIT Blocking Will block Continued on next page Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Sysiems Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSInstallDriver 24 Install Replace a device driver Arguments A Device driver number to replace acial ACIA1 acia2 ACIA2 dac DAC adc ADC pia PIA timer PTM3 B 0 1 substitute new Replace with the default X Address of device structure Returns Nothing On crror Nothing Blocking Will not block Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 106 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix D Device driver function calls Usage Include the
52. Common RAM 0x0000 Ox1 fff and Paged RAM 4x 0x2000 0x9fff All hardware devices occupy the 8k between Oxa000 Oxbfff The first 0x100 bytes of each area of RAM are used by the memory manager to indicate whether or not a block of memory is in use RInOS uses the low portion of shared RAM starting at 0x100 to store information such as pointers to various lists maintained by the system and flags to indicate system status A number of structures are defined that hold information needed by the system Examples of such structures are the thread control block TCB that defines the state of all threads loaded by the system blocks for semaphores signals messages and so on Those structures that are predefined by the system reside in the low RAM area in the following order Task control blocks 32 System semaphores 256 Message blocks 32 Signal blocks 32 Pipe blocks 16 Workshop on Distributed Laboratory Instrumentation Systems 16 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Here the bracketed quantities refer to the default number of the struc tures created during system initialisation Another important structure that resides in this area is the interrupt vector table This table consists of an entry for each hardware device in the system When a hardware interrupt is received cach device is interrogated to determine whether it was the cause
53. DE 119 L6 OODB 16 FF B1 111 lbra L2 OODE 112 L3 OODE 4F 113 elre OODF 5F 114 clrb first part of movhi for 0 GEO DD 00 115 std ZD0 second part of movhi REG 00E2 17 00 00 116 lbsr _exit CALL R ZD0 _exit 40 bytes O0ES 117 Li 118 EPILOGUE OOES 35 10 119 puls x Pulling register ZD2 OOE7 9F 00 120 stx ZD2 00E9 35 10 121 puls x Pulling register ZD1 GOEB 9F 00 122 stx ZD1 QQED 35 20 123 puls y Restore stack frame OQEF 32 E8 1B 124 leas 27 s deallacate 27 bytes auto variables OOF2 39 125 rts return from function 126 Stet ec ee ne er a RS 127 END EPILOGUE for main 128 py prt rrr rrr ene scenes sens sscsrssss OOF3 129 LC2 OOF3 25 73 130 ascii 4s 00F5 OA i131 byte OxA O0F6 00 132 byte 0x0 133 globl _childi OOF 134 _child1 188 33 o oo errr nnn 136 PROLOGUE for childi AST Spores aa eee ase sees e sess QOF 32 7E 138 leas 2 s allocate 2 bytes auto variables OOFS 34 20 139 pshs y Save stack frame OOFB 1F 42 140 tfr s y Set current stack frame OOFD SE 00 141 ldx ZD1 OOFF 34 10 142 pshs x pushed register ZD1 143 END PROLOGUE 0101 12 144 nop 0102 145 L8 0102 16 00 03 146 Ibra L10 0105 16 00 28 147 Ibra L9 0108 148 L10 0108 4F 149 c lra 0109 SF 180 clrb first part of movhi for 0 0104 DD 00 151 std Z2D0 second part of movhi REG 010C 17 00 00 152 lbsr _get_message CALL R ZDO _get_message 0 bytes G10F DC 00 153 ldd 2D0 first part of movhi for REG Wo
54. ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt commands given in Table 2 19 page 51 arc supported by the extended ver sion All commands are lower case and must end with a carriage return These commands allow the user to download code to the ICTP09 board and to set various parameters Full tracing and breakpoint facilities arc provided so that code can be debugged in situ rather than by the use of a simulator 2 9 2 The code downloader Three separate commands are provided for the downloading of cade to the board the 1 1 size and the la size Each of these downloads the code in slightly different ways to accommodate the various possible ways in which the code can be prepared The first of these commands l is intended to place code into the memory of the ICTP09 board that has been assernbled or compiled with a definite origin and is not position independent This last condition means that the memory manager in the kernel cannot be used to find a suitable free location for the code This command also does not call the kernel to register the presence of the code in memory In order to run code downloaded with this command the user should issue the g address command If kernel calls are to be made from the user program the OSThreadInstall system call must be issued prior to any other call The other two downloader commands are provided so that a thread do
55. J Wetherilt Command Description l Load at absolute address without starting kernel la size priority arg arg2 Load to address 0x2200 a module of length size priority priority aud with argument list argi arg2 l size priority arg arg2 Load relocatable module of length size priority priortty and with argument list ergi arg2 g p address Go from current address or specified address x Start kernel execution c addr Call a subroutine at address addr Control will return to monitor following the rts instruction b Display breakpoint list b p addr Add address p addr to breakpoint list b p addr Remove address p addr from breakpoint list Trace a single instruction r Display modify registers d addr size Display size bytes of memory starting at addr m addr Modify memory location addr dd Toggle the wait status on or off This is used as an aid to debugging the LCD device driver which requires a wait normally supplied by the system timer Use of the system timer is not recommended during debugging ss length Set size of defanlt stack to length length smp p Set memory page to p rmp Get memory current memory page pid Get pid of current task sp p pid Set priority of task with pid pid to p rp pid Get priority of task pid or current task if no argument is given tn Trace n instructions ctrl x Cancel current instruction Note
56. N command traces the execution machine Workshop on Distributed Laboratory Instrumentation Systems 86 Abdus Salam CTP Trieste November 26 December 21 2001 Software for ihe 6809 Microprocessor board C Verkerk and A J Wetherilt instruction after machine instruction which is extremely slow of the order of 5 instructions per second due to the need to transmit many characters between the board and the PC It stops when the new memory address corresponds to the beginning of a line in the C program To speed up the execution of the N command it will not trace instruction by instruction inside a function called from the program being debugged or a system call It will warn you about this happening When executing the N command the LCD display on the board cannot function in its usual way It is therefore foreseen to redirect the output intended for the LCD display to the PC s screen but going through all calls to library functions as usual What the LCD display shows stands out on the screen and truly represents what it would show at this particular point in the execution of the program 4 5 5 Investigating the values of variables Use the D for Display command followed by the name of the variable to see its valuc for instance D mutex Global variables do not cause problems in general Local variables may For instance you might be tempted to ask for the valuc of a local variable outside its scope You will then be war
57. N on a semaphore differs slightly de pending in the semaphore type but can be summiarised as follows i If the semaphore is a Mutex or an Event the value is decremented using a rotate right accumulator instruction This both decrements the value and allows a test as to whether the semaphore was previously zero or not If not zero the semaphore is claimed for the calling process by firstly writing the address of the caller in the SEMOWNER field and secondly by linking the semaphore into a list of semaphores owned by the caller This list has its head in the SEMAOWND field of the current thread s TCB The SEMOLNK field of the semaphores form the remainder of the list Each time a new semaphore becomes owned by a thread the SEMOLNK field of the last semaphore is updated to point at the new semaphore The purpose of this list is to enable all semaphores owned by a thread to be released should that thread terminate for some reason It is good practice to ensure that in the event of ter mination all semaphores should have been released previously so that this mechanism is superfluous The system now issues a return to the Workshop on Distributed Laboratory Instrumentation Systems 33 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt caller In the case of Counting semaphores the value is also decre mented and tested If previcusly non zero a
58. OSFreeSem 2 int free_user_sem struct user_sem OSFreeUserSem 39 int get last error void OSGetLastError 29 char get _message int pid OSReceive 8 char get_task_info void OSGctTaskInfo 26 int install_driver int device num int new OSInstallDriver 24 void params int mssleep int nticks OSSleep 18 char palloc_mem int tid int sizc int page OSPAllocMem 22 int pfree_mem int size void addr int page OSPFreeMem 23 void printerr void None Continued on next page Table I 1 C functions resulting in a system call 127 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Function Prototype From libereal a int read_pipe int pipeid void data int rd_close_pipe int pipe_id int rd_open_pipe int pipc_id int release_pipe int piped int reset_esem int sem_num int reset_signal int signal num int reset_user_esem struct uscr_scm int send_message int pid char message int set_priority int priority int pid int set_thread_attr int attrs int signal int sig num int type void params void start void int thread_create int priority void create_block int thread_exit void int thread install void create_block int thread _join int pid int time out int thread_kill int pid int up sem int sem_num int up_user_sem struct uscr_scm int wait_message int pid char message void wait_signal int sig num int wake int pid
59. OSFreeUserSem 39 int get_last_error void OSGetLastError 29 char get_message int pid OSReceive 8 char get_task_info void OSGet TaskInfo 26 int install_driver int device_num int new OSInstallDriver 24 void paramis int mssleep int nticks OSSleep 18 char palloc_mem int tid int size int page OSPAllocMem 22 int pfree_mem int size void addr int page OSPFreeMem 23 void printerr void None int read_pipe int pipeid void data OSReadPipe 38 int rd_close_pipe int pipe id OSRClosePipe 36 int rd_open_pipe int pipe id OSROpenPipe 35 int release_pipe int pipe id OSReleasePipe 32 int reset_esem int sem num OSResetESem 5 int reset_signal int signal num OSResctSignal 30 int reset_user_esem struct user_scm OSResetUserESem 42 int send_message int pid char message OSSend Message 6 int set_priority int priority int pid OSSet Priority 17 int set_thread_attr int attrs OSSetThreadAttr 27 int signal int sig num int type void params OSSignal 9 void start void OSStart 11 int thread_create int priority void create block OSThreadCreate 13 int thread _exit void OSThreadExit 14 Table 3 6 Interface Functions for RInOS System Calls Workshop on Distributed Laboratory Instrumentation Systems 63 Software for the 6809 Microprocessor board Function Prototype From libereal a int thread_install void create_block int thread_join int pid int time out int thread_kill int pid int up_sem int sem_num int
60. Push and Pull instructions which put the contents of a list of registers on the stack or take them off pshs d x y cc or pulu y d dp The order of pulling and pushing is fixed and not according to the order of the list e Software Interrupt instructions swi swi2 and swi3 They behave as if a hardware intcrrupt had occurred all registers are pushed on the stack and then the PC register is set to a fixed value between Oxfff2 and Oxffff Miscellaneous instructions such as nop sex cwai etc For more details the reader should consult Motorola s MC6809 MC6809E Microprocessor Programming Manual Workshop on Distributed Laboratory Instrumentation Systems 95 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix B Returned error codes Here is a list of the error numbers that can be returned The table has been split into two The first gives the crror codes returned by the interface routines for the IO calls Not all of them are uscd at present The table on the next page shows the errors which can be returned by a system call The error message printed by printerr is also indicated the messages shown in the last column are always preceded by ERROR when printed ICTPIO EGF 13 EOF found EOF ICTPIOJILLEGAL_DEVICE 12 illegal device number ILL DEV ICTP_IO_OUT_OF_RANGE 11 data out of range TOO LARGE ICTP_IO_HW_ERR 10 hardware error HARDWARE ICTP_IO_ MSG_WR_ERR 9 could not write messa
61. Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt creation to allow this action Alternatively a thread can terminate by call ing the OSThreadExit function explicitely which just calls the same thread termination function Threads can also be terminated as the result of receiving the OSThreadKil1l system call from another thread The course of action resulting from one of these commands to terminate is ultimately similar in each case with minor differences arising only for kill condition The common sequence of events is i ii iii iv A thread can return a value This value is placed in the B register prior to issuing the system call RInOS places this value in the EXITCODE field of the TCB and subsequently into the B register of any thread waiting for the thread to exit RInOS allows a terminating thread the opportunity of executing an exit function which was previously installed using the OSAtExit system call The exit function fakes as a parameter a pointer to an optional argument list The addresses of the function and its arguinent pointer are stored in the TCB fields EXITFUNC and EFARG respectively The default value of the EXITFUNC field is the address of a function in the RInO S kernel that simply performs an immediate return The exit function is called before any other termination activity RInOS now initiates a number of checks to
62. Software for the 6809 Microprocessor board Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 C Verkerk 01710 Thoiry France A J Wetherilt Arcelik A S Tuzla Istanbul Abstract This preliminary document describes the software available for the ICTP 6809 board the RInOS multitasking kernel and the monitor ICTPmon both resident on the board together with the tools for cross development The RInOS kernel implements an environment for multithreaded application programs with a well furnished set of inter process and interthread communication mechanisms The tools for cross development running under Linux on a PC comprise the cross compiler cross assembler and linker chain the associated libraries and additional tools such as a symbolic cross debugger Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Old Rinus and Jim Wetherilt were walking through some code They wept like anything to see obscure assembly modc It would be grand they said if C could make some road If seven firms with seven staff would code for half a year Do you suppose old Rinus said that they could make it clear I doubt it said Jim Wetherilt and shed a bitter tear With apologies to Lewis Carroll the Walrus and the Carpenter Workshop on Distributed Laboratory Instrumentation Systems 2 Abdus Salam ICTP Trieste November 26 December 21 2
63. System calls involving the DOWN operation on semaphores will not block inside the interrupt handler Workshop on Distributed Laboratory Instrumentation Systems 45 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt but will cause a context switch when the handler finishes In any case a blocked interrupt handler is something that should be avoided at all costs 2 8 2 The serial driver ACIA1 and ACIA2 The serial comunications driver is an interrupt driven driver for input and output In order for it to function the appropriate interrupts must be jumpered to the 6809 IRQ line on the ICTP09 board Since the 6850 ACIA device has only a single input and output channel the functions for a second channel are ignored Prior to use all drivers must be initialised This is done by default during system initialisation for all drivers except ACIA1 This is not initialised as ACIAI is the default channel of communication for the mon itor which uses a simple polling mechanism for its driver To initialise the RInOS driver for ACIA1 would therefore cut all the facilitics offered by the monitor for downloading and system debugging Therefore ACIA1 has to be initialised by the user if it is to be made use of During initialisation the ACIA driver creates a number of fields in its scratch data area This is an area of at least 25 bytes in which the device driver can stor
64. TALLED 8 Is driver installed Table 2 15 Interrupt table offsets Since the interrupt service table is located in RAM it can be changed by the user so that user supplied device drivers can be implemented RInOQS supplies the OSInstallDriver system call for this purpose The first step of the device driver is usually to determine the driver request number This is obtained from the A register in the current stack frame A jump to the requested function is then made The possible function requests are shown in Table 2 16 page 45 Workshop on Distributed Laboratory Instrumentation Systems 44 Abdus Salam LCOTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Request Val Description Applicable devices bread 0 Single read channell All except DAC bwrite 1 Single write channell All except ADC sread 2 Multiple read channell All except DAC swrite 3 Multiple write channell All except DAC ADC ioctl 4 IOCTL All init 5 Device initialisation All ilock 6 Lock input mutex All except DAC iunlock 7 Unlock input mutex All except DAC olock 8 Lock output mutex All except ADC ounlock 9 Unlock output mutex All except ADC bread2 10 Single read channel2 ADC PIA bwrite2 11 Single write channel2 DAC PIA sread2 12 Multiple read channel ADC PIA swrite2 13 Multiple write channel2 None Table 2 16 Device driver function
65. Wait for a numbered signal Arguments A Signal number Returns X Address of optional data On error A ERR BADSIG Blocking Will block OSResctSignal 30 Reset a numbered signal Arguments A Signal number Returns Nothing On error A ERR BADSIG Blocking Will not block OSCreatePipe Create a pipe Arguments B Pipe width in bytes Returns B Pipe handle On error A ERR_PCREATE ERR_PWDTH ERR SMCREATE Blocking Will not block OSReleasePipe 32 Release a pipe Arguments B Pipe handle Returus Nothing On error A ERR PUNINIT Blocking Will block Continued on next page Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Sysiems 104 Abdus Salam iCTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSWOpenPipe 33 Open a pipe for writing Arguments B Pipe handle Returns Nothing On error lt A ERR_ PUNINIT Blocking Will block OSWClosePipe 34 Glose a pipe lor writing Arguments B Pipe handle Returns Nothing On error A ERR_PUNINIT Blocking Will block OSROpenPipe 35 Open a pipe for reading Arguments B Pipe handle Returns Nothing On error A ERR PUNINIT
66. _page Get requested memory page attr_stacksize y Get requested stacksize Call memory allocation function USPAllocMem attr_page u attr_stackaddr u attr_stacksize u 0 u Reset y to point at attribute u Reset u to point at stack frame O s Point at thread creation structure on stack attr_page y Set page PSEG x start pcr Set strt of code segment C5EG x attr_stackaddr y Set stack address SSEG x attr_stacksize y Set stack length SLEN x 4 u Set thread entry point CSTART x 2 u Set thread argument ARGPTR X attr_priority y Set thread starting priority TPRIO x 0 No extra memory is needed TMEM x attr_detachstate y Set thread attributes attr_cancelstata y attr_canceltype y TATTR x attr_directpage y Set data direct page TDP x kernel function attr_priority y Set priority OSThreadCreate Return thread handle in d rts Workshop on Distributed Laboratory Instrumentation Systems 121 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix H A debugging example In this section it is assumed that a terminal emulator programme is available and running and that the ICTP09 board is connected via the first serial port to the host and to a suitable power supply Since the commands used to transmit code across the link depend on the particular terminal emulator used all such commands will be in italics as pseudo commands Thus send code would cause the code to be transmitted to the board B
67. action inside nested interrupt An illegal message has been received Semaphore was released by timeout Sema was released by a release call Sema released by a terminating thread Thread was terminated by a timeout Thread was terminated by a kill signal Illegal semaphore number requested Thread could not be killed An error occurred in the flt pt package NONE BAD CALL BAD TASK TH INSTAL TH CREATE NO SLEEP BAD EX FC SM CREATE PIPE WDTH PIPE CREA P NO INIT CALLOC PALLOC BAD SGNL INT LEVEL BAD MSG SM TIMOUT SM RELEAS SM TH END TH TIMOUT TH KILLED BAD SEMA BAD KILL FLOAT PT Table B 2 Error codes returned by system calls The FLOAT_PT error will be accompanied by another error message e Either EDOM if the argument to a function is not in the required domain For instance a negative argument to log x e Or ERANGE if the result of the function lies outside the range of floating point numbers that can be represented in 32 bits Either the largest possible number or zero is returned in that case Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 97 Appendix C System calls Usage Include the file syscalls inc Call the function with swi byte Function Symbolic name Description and behaviour OSCreateSem 1 Create new system semaphore Arguments A Type MUTEX COUNTING EVENT etc B Initial valuc Returns A
68. ame is the name you gave in the o option without any extension If you don t give a name with the o option the output file will be called a out lFor convenience of the developpers the assembly listing and the map file are still available Workshop on Distributed Laboratory Instrumentation Systems amp 1 Abdus Salam ICTP Trieste November 25 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt 4 3 Downloading and running your program When the hardware board has been connected to a serial port of your PC this serial port should be known to the system as dev modem and powered up the only thing you have to do to download your program is to type inside a normal X Term window db09 name arguments where name is again the name of your program and of its ELF file and arguments are optional Then follow the instructions Downloading is a rather slow business so you should have some patience When the message Task 02 loaded at address 2200 appears the downloading was succes fully completed and the db09 gt gt prompt will show Now type x and your program will run hopefully without errors If it does not run at the first attempt you should read the next section Otherwise you may ask an instructor to congratulate you 4 4 Debugging your program To debug your program you have the choice between two possibilities Use the real hardware board or th
69. ce driver function calls Continued 108 D 1 Device driver function calls Continued 22 109 D 1 Device driver function calls Continued o a000 110 D 2 Device driver definitions aooaa aaa 110 E i Thread Control Block TCB structure 111 E 2 Values used to define TCB fields Thread state values 112 E 3 Values used to define TCB fields Thread attribute bit fields 112 E 4 User settable thread attribute values 2 0 200022 112 E 5 Message structure 26 b dew ale we acd a oy eer Bo eo oe 112 E 6 Thread creation structure 2 2 0 0 0 a eee 113 E 7 Semaphore structure 2 2 aa a es 113 E 8 Semaphore types used by semaphore system calls 2 113 E 9 Signal structure 4 6 itd id ie Gas Se le ang ae eG Oe 113 Os Pipe structure cee a Sea ieee pce ait Tooke ae ee 114 E 11 Interrupt table structure a Sn Oo a eh oe ol ee 114 E 12 System variables 2 0 ee ee 114 E 13 Global maximum values 2 2 02 0000 e eee 115 E 14 Hardware addresses 22 ele 115 Workshop on Distributed Laboratory Instrumentation Systems T Abdus Salam ICTP Tricste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt F 1 Linked lists in RInOS F 2 Linked lists in RInOS Gontimed I 1 C functions resulting in a system call I1 C functions resulting in a system call Conid 116 117 127 128
70. cking Will not block OSReset UserESem Reset an event user semaphore Arguments X Address of semaphore Returns Nothing On error Nothing Blocking Will not block OSDownHybrid 43 Perform down on semaphore and up on mutex combination Arguments X Address of resource semaphore Y Address of mutex lock Returns Nothing Onerror Nothing Blocking Will block Continued on next page Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 99 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page 3 Symbolic name Description and behaviour OSStart 11 Start RIMOS This function never returns Arguments None OSThreadInstall 12 Install thread loaded at absolute address This function does not return Arguments X Address of thread creation structure OSThreadCreate 13 Create new thread Arguments A Thread priority X Address of thread creation structure Returns D Thread identifier handle of new task X Address of new task On error A ERR_TCREATE Blocking Will not block OSThreadExit 14 Terminate a thread This function is called implicitely or explicitely by a terminating thread and never returns If an exit function has been installed this is called first All semaphores owned by the thread are released and the thread is removed from the wait
71. combined into a single one libIO a Also two other library functions mssleep and pute were changed The IO functions and the other two now detect auto matically if the program is running on the simulator or on the real hardware and they act accordingly The result for the user is that he now has to deal with two programs only to compile execute and if necessary debug his program ccO9 and db09 As db09 maintains a dialog with the hardware board there is no need anymore to run a terminal emulator program such as seyon The user compiles his program once only and not twice as before once for the real m6809 and once for its simulator There is only one single set of libraries and one single output file A listing of the user compiled programs is also produced with numbered lines to serve as an aid in debugging To compile a program the user now proceeds as follows ccO9 oname name c where name is the name you gave to the file containing your C program If you want more information from cc09 and the compiler type cc09 v Wall oname name c If necessary you can specify all regular options of gce the g option is added automatically and does not need to be specified If you have a long program extending over more than one file you can compile and link everything in a single go as the following example shows ccO9 v ottilee ttilet c ttiie2 c The compiler will produce an ELF output file its n
72. cross compiler for the 6809 microprocessor is an adaptation of the GNU C compiler which has been obtained by writing or modifying four configuration files a machine description file m6809 md two include files local h and xm local h and an auxillary file m6809 c These files only influence the building of cct sgec and cpp remain unchanged when one of these files is modified The assembler and linker used in the cross compilation chain for the m6809 microprocessor are not adaptations of GNU software but are the so called Baldwin assembler linker The 6809 has a limited number of registers which causes difficulties for a GNU compiler The cross compiler is therefore made to believe that it has many more registers at its disposal for storing intermediate results These pseudo registers are simply memory locations in the so called Direct Page of the 6809 Because of other restrictions imposed by the 6809 microprocessor the cross compiler originally recognized only three data types char int and 53 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt pointers These data types are 8 16 and 16 bits wide respectively Structures and unions of the various data types are correctly recognized During the autumn of 1997 the cross compiler was enhanced with floating point facilities so now also the data type float is recognized Floating point numbers are stored in
73. cted as the semaphore s next owner and the appropriate actions taken For Event semaphores all threads are woken A Mutex can also be induced to behave as an Event by placing the value Oxff in the B register prior to issuing a call to cither OSUpSem or OSUpUserSem This is to ensure compatibility with certain features of the POSIX 1003 1c standard iii A context switch is now performed 2 5 3 Other semaphore operations A number of other operations are provided under RInOS to facilitate the use of semaphores A semaphore can be releascd if it is no longer required This is simple with user semaphores which the same as memory can be reused However calls Workshop on Distributed Laboratory Instrumentation Systems 34 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt are provided for both user and system semaphores These calls will ensure that the correct tidying up is performed by the system and no loose pointers remain Sometimes it becomes necessary to reset an Event semaphore and OSResetESem is provided for this purpose The user should bear in mind that the manual resetting of any semaphore can be a dangerous act In some situations it is desirable to have two semaphores acting in tandem together Using the standard system calls it is obviously not possible to perform atomically a DOWN on one semaphore followed by an UP on a second Such a r
74. ction of the system call or a new thread may even be created This new thread should then be the one that resumes execution when control is returned from the system When one of these happen the following sequence of actions occurs Workshop on Distributed Laboratory Instrumentation Systems 26 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Webherilt i If an error is indicated the error number is stored in the ERRORSTS field of the current TCB and the carry bit set in the CCR byte of the current context for return to the caller ii Interrupts are masked to prevent spurious interruptions that could de stroy system information iii The intlvl system variable is decremented and its new value compared with zero If it is not zero then the current context is obtained from the current TCB and pulled from the stack This ensures that a context switch cannot occur when a system call is itself interrupted iv The priority list pointed to by the prioptr system variable is scanned for the first runnable thread Since the list is maintained in strict order of priority the first suitable thread will also have the highest priority v The address of the TCB of this thread is stored in the system variable ctskptr to indicate that this is now the current thread and the address of the context for the new thread loaded from the STACKPTR field of its TCB
75. d On error A ERR PALLOC Blocking Will not block Free paged memory Arguments A Page number of memory block to be freed X Address of start of memory block Y Size of memory block Returns Nothing Onerror Nothing Blocking Will not block OSSendMessage 6 Send a message to a thread Arguments D Receiving thread id X Address of message Returns Nothing On crror A ERR BADINST ERR SMCREATE Blocking Will not block OSWaitMessage 7 Send a message and wait for response Arguments D Receiving thread id X Address of message Returns Nothing Onerror A ERR BADINST ERR_SMCREATE Blocking Will block Continued on next page Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 103 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSGetMessage 8 Receive a message Function will block if none available Arguments Nothing Returns X Address of message On error A Nothing Blocking Will block OSSignal 9 Send a numbered signal 0 31 Arguments A Signal number B Signal type 0 Auto reset 1 no reset on send X Address of optional data Returns Nothing On error A ERR BADSIG Blocking Will not block OSWaitSignal 10
76. d in case you want to use a line number B ttlieil c 39 will place a breakpoint at the beginning of line 39 in file tillel c To see the numbered lines consult the file t1Jel cn cnl for C with Numbered Lines In case you want to place many breakpoints in the same file you can save some typing by first specifying the file name 7On the hardware db09 makes available to the user ONLY the single lower case letter commands Workshop on Distributed Laboratory Instrumentation Systems 84 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt F ttile2 c You can now limit yourself to typing B 39 B 45 B 46 etc You may change to another file by using the F command again Without an argument the F command will show the name of the current file If you choose to sct a breakpoint at the entry point of a function cither a library function or one you have compiled yourself type B printf or any other name of a function When you reach a breakpoint at the entry of a function db09 will tell you so and show you the value s of the argument s to the function if any In casc you compiled the function yourself db09 knows the number of arguments and the type of each and it will show correct results except at present for floating point numbers For a library function this information is not yct available and db09 can only guess If you ha
77. d on it This signifies that the initialisation of the pipe is complete and any threads waiting to use it can proceed The pipe creation system call OSCreatePipe returns the pipe identifier for use in all subsequent operations on the pipe Reading and writing proceed as follows i iii The pipe is opened for reading or writing This consists of passing the pipe identifier to OSROpenPipe or OSWOpenPipe for reading or writing respectively These functions first perform a DOWN on the pipe lock mutex as do all pipe operations before attempting any other action The function will block if the lock is already in use and resume only when the lock is made available again A DOWN is performed on the appropriate reading or writing semaphore and the lock mutex released Data are read from or written to the pipe For writing after claiming the lock mutex a DOWN is made on the FULL semaphore When access is gained to this semaphore the data are written to the address pointed to by the PIPE_FRNT pipe field The PIPE_FPOSN value is decremented If this value is zero the PIPE_FRNT valuc is set to the address in the PIPE_MEM field otherwise it is incremented by the width of the queue Reading proceeds in a similar manner After claiming the lock mutex a DOWN is made on the EMPTY semaphore After gaining access data is read from the address contained in the PIPE_REAR field The PIPE_RPOSN value is decremented and if zero at the end of the buffer
78. ddress Oxfffa within the hard ware interrupt table in ROM This value points to a location in the monitor which in turn points to the system dispatcher Once RInOS receives the request a number of actions occur prior to jumping to the desired system call Firstly RInOS saves the current stack in the Task Control Block TCB for the current thread and switches to the system stack It also increments a system flag the intlvl variable to indicate that it is running in system space and that any subsequent interrupts should not reset the stack again The return address is changed to the first valid instruction at the second byte following the swi instruction This is achieved simply by adjusting the value of the return address on the stacked register scet Throughout the system call it is assumed that the U register points at the base of the stacked registers and acts as a stack frame pointer for the interrupted thread In this way the register values can be accessed as desired At this stage the interrupt mask bit in the 6809 processor is set so that interrupts are disabled If this Workshop on Distributed Laboratory Instrumentation Systems 18 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt situation were to continue no hardware interrupts could occur and the system would not respond in the desired manner to external events Accordingly the interrupt
79. download09 This program can be run from a termina emulator to download a pregram into the hardware board as its name implies Normally there should be no need to use this program Its job is also entirely done by db09 ii postlog When followed by the name of a log file from a debugging session this little shell script is useful to get rid of a series of unprintable characters which however cause the log file to have an ugly appearance on the screen iii s19tobin This utility translates an s19 filc inte a binary file which is an image of how the program would appear in memory on the m6809 board The user types the following command line si9tobin prog si9 and obtains a new file prog which contains the binary image iv s19todb09 This program is similar to s19tobin but it uses as input two files prog s19 and a template file containing a binary image of the RInOS kernel The command line is s19todb09 prog si9 rinos offset rinos is the template located in the subdirectory src RIn0S The optional argument offset which must be a decimal number is added to the load addresses in the s19 file This shifts the position of the program in memory and allows to check that the program is indeed in Position Independent Code The result of the above command is a binary file of 64 Kbytes containing the program prog and the RIn0S kernel v check_pic This is a program to check if an object module or an entire library is writ
80. dress A030 modified from D101 inf puts here a PC DP A B X Y U S DP EFHINZVC CC watchpoint D103 8601 03 OA A030 115D 1EBO 1EBO 00 11010000 DO all this is kernel Watchpoint 0 at address A030 modified from D10F initialisation PC OP A B X Y U 5 DP EFHINZVC CC D111 6DA8 91 OA A030 115D 1EBO 1EBO 00 11011000 D8 BreakPoint Reached end of kernel Pc OP A B X Y U 5 DP EFHINZVC CC initialisation C006 1322 01 00 11DA 1144 10E0 1ECO 00 01000000 46 db09 gt Clock Interrupts have been enabled inf enables the clock dbO9 gt N Address Stop and lists watchpoints O A030 0 db09 gt N Address Skip Hit and lists breakpoints set 000 C006 000001 000000 db09 gt b 2340 db09 gt b 2343 db0g gt g was interrupted from 22e7 newpc cf94 was interrupted from 22e5 newpc cf94 was interrupted from 22e3 newpc cf94 was interrupted from 22e1 newpc cf94 was interrupted from 22e7 newpc cf94 was interrupted from 22e5 newpc cf94 was interrupted from 22e3 newpc cf94 Now we enter into action set breakpts around thread_create start the program running Here we are in a very long loop in crtQ we set to zero the direct pages unused stack and the _BSS area The time between two messages is equivalent to 10 ms on the real hardware se Ft Fe Fk OH FH Ht OH OH was interrupted from 22e1 newpc cf94 was interrupted from 22e7 newpc cf94 was interrupted from 22e5
81. e attr_canceltype equ 7 Offset of cancel type attribute attr_priority equ 8 Offset of scheduling priority attribute attr_directpage equ 9 Offset of data direct page attr_schedpolicy equ 10 Offset of scheduling policy not implemented Entry point of start std parent thread parentid x Save parent handle which is returned by RInDS Fill in attributes leax attribute pcr Point at the attribute structure ldd DETACH_STATE_ON Set detachstate sta attr_detachstate x ldd CANCEL_STATE_ON Set cancel state sta attr_cancelstate x ldd CANCEL_TYPE_DFRD Set cancel type sta attr_canceltype x ldd 1000 Set stack size std attr_stacksize x ldd 0 Indicate no preference for stack address std attr_stacksddr ata attr_page Set page to don t care lda 4 Set scheduling priority sta attr_priority x Workshop on Distributed Laboratory Instrumentation Systems 119 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherili Call thread create function thread_create thread handle attribute attr void start attribute tattr First push arguments on to stack ldd 0 Null argument pointer pshs d ldd child pcr Addressof child function pshs d pshs x Address of attribute Now issue ca ll to function bsr thread_create leas 6 8 Remove stacked function parameters std childid per Save returned child handle x Just wait for thread to finish ldx
82. e 3 14 Both debuggers work at the level of machine instructions or in other terms at the level of assembly language coding Breakpoints must be set at absolute locations in memory In order to set a breakpoint at a spot in say one of the library functions which are part of the program the user must consult the map file prog map and the listing of the function where the breakpoint should be placed To obtain the absolute address some calcula tions in general an addition and sometimes also a subtraction must be performed in hexadecimal These were added during the 1998 College by a team of participants as their project work Workshop on Distribuled Laboratory Instrumentation Systems 73 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt l Command or help x or exit r r reg value d low high g location m lt low gt lt high gt lt byte gt S c n bora b lt addr gt skip k lt addr gt k all i filename l filename t filename t e w lt addr gt w kill w lt addr gt kill u addr fn RETURN m lt addr gt lt byte gt byte2 Description Prints this message Exits from the debugger Show the register contents Set one register to the HEX value reg can be a b d x y 1 s CCR p direct page program counter Dump memory bet
83. e compiler itself the interested reader can find details in the GNU C compiler manual As said before the compiler chain consists of five programs The super visory program zgec will need to access cpp ect as and ld and search for include files and program libraries There may be other programs with the 1The comments have been added by the authors Workshop on Distributed Laboratory Instrumentation Systems 55 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt same name present in the system and in fact there are In order to direct xgec to look for these entities in the correct place a symbolic link must be sct up from the file usr lib gcc lib m6809 local 2 7 2 to the direc tory from where the downward search should start In our case this is the directory usr local micros m6809 3 2 Assembler and Linker The assembler and linker were not adapted from GNU as and ld and thus do not accept the usual options Options are therefore passed by using the Wa and W1 mechanism defined by the GNU C compilers The op tions which can be passed to the assembler in this way or specified directly if the assembler is invoked in its own right a practice that we don t recommend see below are shown in Table 3 2 on page 56 Option Effect Produce a listing with numbers in decimal Produce a listing with n
84. e declared extern if you intend to use them struct creation_block tcbmain and int tid The only data types you can use are char int float and pointers You may combine then into arrays structures unions and what have you You may use floating point numbers and operations including calcu lating sines tangents exponentials etc See Table 3 9 page 66 You may print floating point numbers using the 4f format The curious may dump a floating point number in hexadecimal using the 41 format For a program that does not use floating point you may wish to call prntf instead of printf The program size will be reduced by approximately 2000 0x800 bytes The main program may have arguments Pointers to the arguments are set up by the startup routine crt0 The values of the arguments must be specified when downloading the program They are all stored as ASCII strings including the numerical ones The conversion must be done in the main program using atoi or atoh A total of 8 Kbytes of space is reserved for direct pages and stacks 16 each of 256 bytes Each child thread needs its own direct page All space not occupied by direct pages is available for stacks for the child threads For instance a program with six threads 1 parent and 5 children needs 1 5 Kbyte for direct pages leaving an average stack space of 1 Kbyte for cach of the six threads Enough to use lots and lots of local variables If on the contrary you are g
85. e eerean ase henian e A O13C 32 7C 185 leas 4 s allocate 4 bytes auto variables O13E 34 20 186 pshs y Save stack frame 0140 1F 42 187 tfirs y Set current stack frame 6142 9E 00 188 ldx ZD1 0144 34 10 189 pshs x pushed register ZD1 190 END PROLOGUE 0146 DC 00 191 1dd ZDO first part of movhi for REG 6148 ED 22 192 std 2 y second part of movhi case PLUS register 1 014A EG 23 193 ldb 3 y first part of movqi case PLUS register 1 0140 E7 8D 00 OB 194 stb tcbmaintil per second part of movgi default 0150 EC 8D 00 03 195 ldd _tcbmaint3 per 6154 C3 FF 00 196 addd 256 0157 ED 8D 00 03 197 std _tebmaint3 per addhi3 _tcbmaint3 per by 256 gt tchmain 3 per 015B E6 8D OO 11 198 ldb _tcbmaint17 per O15F B 01 199 addb 1 0161 E7 8D 00 11 200 stb _tcbmainti7 pcr addqi3 _tcbmain 7 per by 1 gt _tcbmainti7 pcr 0165 30 aC oF 201 leax childi per address of symbol gt X 0168 1F 10 202 tir x d 1st part of movhi for symbol or label 016A ED 8D 00 07 203 std _tcbmaint7 per second part of movhi default 016E 30 8D 00 00 204 leax _tchmain per address of symbol gt 0172 1F 10 205 tfr x d 1st part of movhi for symbol or label 0174 34 06 206 pshs d second part of movhi case PRE_DEC 0176 EC 22 207 ldd 2 y first part of movhi case PLUS register 1 0178 DD 00 208 std ZDO second part of movhi REG Q17a 17 00 00 209 lbsr thread create CALL R ZD0 _thread create 2 bytes OL7D 32
86. e for the 6809 Microprocessor board C Verkerk and A J Wetherilt Symbol Value Description MAXTASKS 32 Maximum number of tasks for system MAXSEMAS 255 Maximum number of semaphores for system MAXMSGS 32 Maximum number of messages MAXSIGS Maximum number of signals MAXPIPES Maximum number of pipes Symbol Address Description priatch Oxa040 Physical page register PIABASE Oxa000 PIA TIMR Oxa010 PTM ACTAI 0xa020 ACTAI ACTA2 O0xa030 ASCIA2 ADCBASE Oxa040 ADC DACBASE 0xa044 DAC Table E 13 Global maximum values Table E 14 Hardware addresses Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 115 Appendix F Linked lists used by RInOS RInOS uses a number of linked lists to perform some of its functions Thread priority list List function The maintainance of a list of all threads created by the system in order of decreasing priority This list always contains at least the null thread Head of list prioptr at address 0x108 in the RInOS work area Link PPTR in the TCB Active timer list List function A list of all threads waiting for the completion of an active timer Head of list clktsk at address 0x10c in the RInOS work area Link TMRLNK in the TCB Continued on next page Table F 1 Linked lists in RInOS 116 Software for the 68
87. e information it needs Each driver is assigned its own area The initialisation function for the ACIA creates four mutexes two each for the input and output channels One of each set of mutexes is to protect a stream from other threads whilst a thread is using it A very garbled strcam would result if two or more threads were able to transmit together and by locking the mutex a thread can pre vent this abuse The second mutex acts to regulate the activity of the thread owning the device stream When a byte is transmitted the ACIA device takes a finite time before the transmission register is emptied If the thread were to send a second byte during this time the first would be overwritten A mutex is therefore employed to block further writing until the holding reg ister is emptied Conversely when a thread wishes to receive a byte and a byte is not yet available the input mutex blocks until released by the arrival of a new byte This interplay with the mutexes occurs within the ACIA interrupt handler When a byte is transmitted an interrupt is issued when the byte leaves the holding register and the interrupt handler performs an UP on the mutex Similarly when a byte is received by the ACLA handling the interrupt it raises allows an UP to be performed on the input mutex waking any thread waiting for input Similar principles are employed in the other device drivers The multiple read function takes a string of bytes from the input stream and
88. e register in the initial context RInOS itself does not use direct addressing and therefore can accept any value for this register The requested priority is set in the A register and passed to the TCB An important feature for POSIX 1003 1e compatibility is the ability to set attributes for threads cither dynamically or statically Under RInOS those attributcs that can be represented using a bit field are stored in the ATTRIBUTE field of the TCB and set during thread creation using the TATTR field of the TPT Table 2 5 page 24 lists the bits of the attribute and their usage A full description of the properties of the various attributes is deferred until better POSIX 1003 1 compatibility will be achieved The two byte pid of the thread consisting of the INSTANCE and the ID fields of the TCB is returned in the D register to both the parent thread Workshop on Distributed Laboratory Instrumentation Systems 24 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt and its new child The ID field refers to the number of the TCB in the TCB table created during initialisation Each time a TCB is reused by the system the value of the INSTANCE field is incremented by one The combination of INSTANCE and ID lowers the risk of false identification of a thread Two different functions are available for thread creation The first of these OSThreadCreate allow
89. e simulator built in with db09 The first choice is the default and you should type exactly as above db09 name arguments For instance db09 pt4 Hello 007 When the prompt db 9 gt gt shows on the sereen db09 accepts input from the keyboard A help facility is available to sce the commands you may give to db09 The help screen is reproduced in Table 4 1 page 83 The commands will be described in more detail below Before doing anything else you should set a breakpoint somewhere in your program otherwise you will not gain control over its execution once you have Jaunched the program with the X command as above An example debugging session is shown in Appendix N If you choose to debug your program using the simulator which is much faster as it climinates the slow transmission over the scrial line you should type db09 s name arguments Workshop on Distributed Laboratory Instrumentation Systems 82 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocesser board C Verkerk and A J Wetherilt Command Meaning db09 HELP for commands for Symbolic Debugging To see the assembly level and expert commands type X Start the RInOS kernel A bedfsux When stopped at entry point of function show the arguments in the format indicated one char per arg preceeded by format for return value b byte c char d decimal f float s string u unsigned v void x hex indicates a point
90. eached at line pt4 c 9 We reached line 9 db09 gt K pt4 c 9 Ereakpoint is no longer needed Kill it db09 gt I This ends reading the input file Regrettably at the time when this Appendix was prepared we had in the input file to do a few things behind the scenes Hopefully this will not be necessary anymore today The comments were added by the authors at the time this Appendix was prepared of course Workshop on Distributed Laboratory Instrumentation Systems 153 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt We now want to place two breakpoints one at line 13 after exiting the loop and one at the entry point of the library function atoi We then check that the breakpoints have in fact been placed correctly After that we start executing the N command to step line by line through our program The result is db09 gt B pt4 c 13 Set a breakpoint at line 13 db09 gt B atoi And one at a function entry db09 gt B Check where the breakpoints are N Address Skip Hit 000 2373 000000 000000 line pt4 c 13 001 23F5 000000 000000 atoi All OK db09 gt N Now the first N command Line 10 file pt4 c brings us to line 10 db09 gt Hitting Enter repeats the last command Function Call ___mulhi3 This is used by cci internally Breakpoint reached Here we are at the entry to ___mulhi3 Function Call _prntf Now _pr
91. ecember 21 2001 Appendix A m6809 Registers and programming model The Motorola m6809 microprocessor appeared on the market in 1981 or 1982 It is a member of the m6800 family of 8 bit microprocessors but it has 16 bit 2 s complement arithmetic It distinguishes itself from other microprocessors of the same period by its very neat and symmetric instruction set and a large range of addressing modes As all Motorola processors it is a big endian It has the following sct of registers accessible by the programmer A 8 Accumulator for byte arithmetic B 8 Accumulator for byte arithmetic D 16 Accumulator Consists of A and B register side by side A being the most significant X 16 Index Register Y 16 Index Register U 16 User stack pointer usable as Index Register S 16 Stack Pointer Register CC 8 Condition Code Register DP 8 Direct Page Register PG 16 Program Counter Table A 1 Register Set EJE A I N z v c Table A 2 Condition Code Register 93 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt The bits in the Condition Code Register have the following meaning The N negative Z zero V overflow and C carry bits are used alone or in certain logical combinations by the branch instructions F fast interrupt and I interrupt are the interrupt mask bits E entire and H half carry are flag bits The m6809 p
92. ecessary UP to wake the sender 2 7 2 Numbered signals Numbered signals are similar in many respects to messages except that they are sent to all threads in the system Their structure is given in Table 2 12 page 39 Signals under RInOS are synchronous in that a signal handler is not invoked to intercept and process them Rather a thread can wait for a particular signal to arrive by calling the OSWaitSignal system call specifying Workshop on Distributed Laboratory Instrumentation Systems 39 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt which signal as an argument The thread will wait on the event semaphore given in the SIGSEM field of the signal structure When released the receiver can optionally obtain a pointer to data from the signal SIGPTR ficld RInOS does not define the meaning of any of the 32 available signals but leaves this up to the user Of course all threads must agree on the meaning of each signal As with all constructs using event semaphores the decision as to whether once used the semaphore is to be reset or always remain set has to be made Logically once a signal has been sent it should always be available to threads that wish to check for that signal In practical terms within a small system such as the ICTP09 RInOS combination it is easy to exhaust the number of available signals and hence be unable to send further on
93. ed from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 Signal 2 we hit esc to stop this db09 gt r show regs to see where we are PC OP A B kK Y U 5 DP EFHINZVC CC 0000 0100 EC 03 DOOD DOOC 0000 FFAS 00 00100001 21 THIS IS WRONG we are in hyperspace db09 gt x we stop here rinus katje romtest We never reached the second breakpoint so we conclude that we do not return from thread create The first argument to thread create is in the pseudo register ZDO and the second is on the stack as things should be Presumably thread_create has been tested before and can be trusted so the mistake must be ours Inspection of the function prototypes in Appendix I page 127 reveals that we swapped the two arguments priority should be the first and be passed in ZD0 Maybe thread_create has created a monster as the behaviour of the program would indicate but the fault is easily repaired After a short editing session and recompilation of the program we try again Workshop on Distributed Laboratory Instrumentation Systems 150 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt rinus katje romtest db09 ttig invoke db09 without any option db09 gt 1 ttig log the first steps are as before db09 g
94. efore any session is begun when the terminal is running the RESET button on the ICTP09 board should always be pressed This both resets the board to a known state and gives the user an indication that the board is responding correctly by returning a sign on message Currently this message is RInOS followed by the version number Connections baud rate settings etc should be checked if this message does not appear The prompt sign gt always appears when the monitor is ready to receive input TP5 19 is an absolute code file with an origin at 0x2200 and length 0x618 bytes It is to be downloaded with a stack size of 0x300 bytes priority 4 and the arguments Mary had a little lamb Firstly we set the default stack size to 0x300 gt ss 300 This can be checked by looking at the memory The RInOS work area starts at 0x100 and the default stack size occurs at 0x111 The command gt d 110 will reveal the following memory dump O 1i 2 3 4 5 6 7 8 9 A BCDEF 0110 00 03 00 00 00 40 00 EC 00 82 00 45 00 8C 00 DI er gt 122 Software for ihe 6809 Microprocessor board Verkerk and A Wetheriit At addresses 0x111 and 0x112 is the value 0x0300 indicating that the stack size is now set to 0x300 The file can now be sent using the following instruction sequence gt la 618 4 Mary had a little lamb followed by the emulator command send code The monitor will now send the code to the board When transmission is c
95. em call which is implicitly called during the downloading process requires that the X register points at a structure containing such items as the start of the process code segment stack segment and length etc In addition the A register contains the priority of the process to be created The value following the byte state ment is a byte sized function number for the system call A complete list of the system calls available under RInOS is given in Table C 1 on page 98 On return from the system call RInOS uses the carry bit in the 6809 condition code register to indicate whether the call was completed satisfactorily If the carry bit is sct following a system call an error has occurred and the A register contains the error code number as given in Table B 1 page 96 Oth erwise when the carry bit is clear the system call has completed normally and the A register does not contain a valid error code but may contain in some cases a value returned by the system A bricf description of the 6809 registers and programming model can be found in Appendix A The process of issuing a system call from C is simplified by the provision of a library of functions that load the registers with the required values and issue the appropriate software interrupt During a system call the processor as an integral part of the software interrupt call first stacks the entire 6809 register sct together with the return address and jumps to the location found at a
96. embly language output file s C Compile and assemble do not link output file lst and file o I dir Add directory dir to search path for include files L dir Add directory dir to search path for libraries l file Add library libfile a to search for referenced functions g Produce information for symbolic debugging 0 name Give name to the output file Wa opt Pass the string opt as an option to the assembler Wl opt Pass the string opt as an option to the linker Wall The compiler will issue a warning for every irregularity Table 3 1 Useful options to pass to the C cross compiler void write int fd char buf int len could produce the following piece of code where the Y register contains a stack frame pointer useful for locating the local variables ldx 2 y pick up the last argument len pshs x push it onto the stack ldx 4 y pick up the second argument buf pshs x and push it onto the stack ldd 6 y pick up the first argument fd std 2D0 and store it in pseudo register ZD0 lbsr _write branch to the function _write leas 4 8 after returning clean up the stack where the memory locations referenced by 2 y 4 v and 6 y would contain the number of type int of bytes to write the address of the buffer where the bytes are stored and the file descriptor respectively Other outputs can be obtained for the purpose of debugging th
97. emoved A watchpoint defines a memory location that Option Description S Makes db09 run with the simulator Default is to run on the real hardware lt loadaddr gt Sets loadaddress Default 0 r lt runaddr gt Sets runaddress Avoid this option e escchar Sets escape character Default Esc V Turn on verbose mode a message will be printed for every simulated clock interrupt Table 3 13 Options defined for the Cross debugger db09 will be watched e g the user will be warned when the contents of that memory location are changed and if required execution will stop Another feature of db09 is its ability of simulating clock interrupts A clock interrupt occurs every 10000 clock ticks but only if interrupts are 3the most useful is s Workshop on Distributed Laboratory Instrumentation Systems 72 Abdus Salam ICTP lrieste November 26 December 21 2001 Software for ihe 6809 Microprocessor board C Verkerk and A J Wetherill cnabled exactly as on the hardware The clock interrupts can be easily turned off and on during a debugging session so single stepping is pos sible The interrupt facility makes it possible to debug multithreaded or similar programs which rely on clock interrupts e g those programs containing calls to sleep or mssleep Also RINOS commands are ex ccuted as normal since the kernel is part of the binary image loaded into the PC
98. ensure that the terminating thread owns no resources when it finally exits Firstly the thread is unlinked from the priority list This ensures that the thread cannot be run when the termination call finishes Secondly the thread is removed from the list of active timers This act should only be necessary for a thread receiving an OSThreadKill system call Next any semaphores owned by the terminating thread are released and the thread is removed from the waiting lists of all other semaphores Any threads which were waiting for this thread to end are woken and the EXIT_PENDING bit in the ATTRIBUTE ficld set The ESEMALNK field in the TCB is the head of the list of threads waiting on the cur rent thread A thread is placed in this list by calling OSThreadJoin The value in the EXITSTS field is returned in the B register of such a thread The ERR_THRDKILL error is returned by any thread killed by the OSThreadKill call Whether or not the TCB used by the thread is returned to the pool of available TCBs depends on the status of the DETACK STATE bit of the ATTRIBUTE field If this bit is set either dynamically using the OSSetThreadAttr system call or statically when the thread is created the TCB will be released and the STATUS field will be set to _NOTASK Workshop on Distributed Laboratory Instrumentation Systems 28 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wether
99. equirement exists however in the POSIX 1003 1le standard concerning the implementation of structures known as condition variables The OSDownHybrid system call is provided to enable condition variables to be constructed It takes two arguments of pointers to semaphores and performs a DOWN on the first followed by an UP on the second assumed to be a Mutex Practically it allows a Mutex defined as a lock guarding a semaphore resource to be released by an application after blocking on the resource semaphore 2 5 4 Summary of semaphore management system calls Table 2 9 page 36 gives a summary of the system calls for semaphore man agement 2 6 Memory management RInOS implements a memory manager for several reasons Firstly to allow multiple processes to be downloaded to the ICTP0O9 board without the user having to worry about the location of each process Secondly to handle system requests for memory allocation and deallocation in a consistent and safe manner and lastly to form a bridge between the hardware page register and the system The memory manager does not rely on hardware and does not therefore swap regions of memory or detect or prevent the illegal use of memory not owned by a process In asmall embedded system there is no need for such a mechanism RInOS actually implements two memory managers one for each of the two regions of memory They are both similar in operation and differ principally in the size of memory managed Ini
100. er B Show all breakpoints B lt name gt skip Set breakpoint at symbol name usually a function entry stop after skip passages B lt number gt skip Set breakpoint at line number stop after skip passages C number Continue execution until next breakpoint or for number of lines D lt name gt cfis Display value of variable name in given format F file Set current file to file or if no argument print the name of current file H Shows this help screen I filename Open input file without filename close K name line Kill breakpoint at name or line Without argument kills all breakpoints L filename Open log file without name close the file N number Continue execution until NEXT line or for number of lines R command Repeat command just before prompt appears Without argument clear what previous R set up S Show contents of stack exit Exit from db09 To see the assembly level commands type Table 4 1 Help Screen for the symbolic cross debugger db09 s option for simulator From then onward you can proceed exactly as for the other case The db09 commands are the same in both cases their behaviour inside db09 changes however Workshop on Distributed Laboratory Instrumentation Systems a3 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board CG Verkerk and A J Wetherill
101. er PRIORITY 4j 1 System Priority value BASE PRIORITY 5j 1 System Base Priority STATUS 6 1 System Thread s status CODESEG T 2 System Start of thread s code segment STACKSEG G 2 System Pointer to stack segment STACKSIZE 11 2 System Size of stack segment STACKPTR 13 2 System Thread s stack pointer PAGE 1a 1 System Page number of thread PARENT 16 2 User Parent of thread EXITSTS 17 1 User Exit status of thread EXITCODE 18 1 User Return code of thread EXITFUNC 19 2 User Pointer to thread s exit function EFARG 21 2 User Pointer to exil function s argument MAILBOX 23 2 IPC Pointer to mailbox SEMALNK 25 2 Semaph Link to chain of semaphores TIMRCNT 27 2 System Sleeping time TIMRLNK 29 2 System Link to timer list ESEMALNK 31 2 Semaph Link to threads waiting for termination SEMAOWND 33 2 Semaph Link to list of semaphores owned by thread SEMAWAIT 30 2 Semaph Pointer to semaphore thread is waiting to own MSGSEMA 37 1 IPG Message queue counting semaphore ERRORSTS 38 1 User Last error status ATTRIBUTE 39 1 User Sys Thread s set of attributes Table 2 1 Task Control Block structure ficld offsets Workshop on Distributed Laboratory Instrumentation Systems 21 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt that performs a tight loop forcing the processor continually to jump to itself This
102. erk and A J Wetherilt Field Of Size Description PSEG 0 1 Page register value for the thread CSEG 1 2 Start of Code segment Module SSEG 3 2 Stack segment SLEN 5 2 Stack length CSTART 7 2 Entry point of code ARGPTR 9 2 Pointer to thread Argument Environment block TPRIO 11 1 Requested priority TPID 12 2 Thread pid OSBackAlloc only TMEM 14 2 Memory size requested OSBackAlloc only TATTR 16 1 Initial thread attributes TDP 17 1 Thread direct page Table E 6 Thread creation structure Field Description set SEMTYP 0 Semaphore type 1 SEMVAL i 1 Semaphore value NXTSEM 2 2 Link to list of threads waiting on this semaphore SEMOWNER 4 2 Current semaphore owner SEMOLNK 6 2 Link Lo list of owners semaphores Table E 7 Semaphore structure Field MUTEX 1 Mutex semaphore COUNT 2 Counting semaphore EVENT 4 Event counter REVENT Oxe Single event reset after use REVNT Ox8 Test for REVENT SEVENT 0x84 Single event freed after use Field jize Description SIGPTR Optional pointer to signal parameters SIGSEM Pointer to EVENT semaphore Table E 9 Signal structure Workshop on Distributed Laboratory Instrumentation Systems 113 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Field Off Size Description PIPE_USED 1 Pipe in
103. ern call This call takes as an argument the time in system clock ticks of period 0 01 s for which the thread will be suspended A duration of zero ensures that the thread will sleep forever or until woken by another thread When this function is called the STATUS field is set to _SLEEPING For non zero valucs of the duration the thread is placed in the active timer list pointed to by the system variable clktsk The next link and the duration are placed in the TIMRLNK and TIMRCNT fields of the TCB respectively On each clock interrupt the TIMRCNT field of each thread in the list is decremented and any threads with timers reaching zero are removed from the list and woken by setting the STATUS field to READY Another thread can wake a sleeping thread by the usc of the OSWake system cal This call checks that the specified thread is in fact asleep and sets its STATUS field to READY ifit is The ERR_NOSLEEP error value is returned if the thread was not asleep Workshop on Distributed Laboratory Instrumentation Systems 29 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Function Number Description OSYield 0 Voluntarily yield to another thread OSThreadInstall 12 Install a thread loaded at an absolute address OSThreadCreate 13 Create new thread OSThread Exit 14 Terminate the current thread OSThreadJoin 15 Wait for a specified thread
104. es For this reason RInOS allows the sender to select whether a signal is to be persistent or will be reset In addition if a persistent signal is to be reused it can be reset using the OSResetSignal system call When making the decision as to whether persistent or non persistent signals are to be used it should be remembered that all threads both extant and to be created in the future can receive persistent signals but only those waiting for the signal when the signal actually arrives will be able to receive non persistent signal 2 7 3 Pipes A pipe is basically a queue or fifo for holding data with suitable protection for the queue in the form of counting semaphores to indicate full and empty states and a mutex lock to guard access to all the resources of the pipe The pipe structure is given in Table 2 13 page 41 A total of 16 blank pipe structures are created during system initialisation with the PIPE_USED field set to 1 To be used by an application a pipe must first be created This consists of the following steps i The list of pipes is scanned until a free one is found When found it is marked as in use by clearing the PIPE_USED field The error value ERR_PCREATE is returned if no free pipe can be found ii At this stage the interrupts are masked off so the initialisation process can be protected to interruption It is critical during the creation of a pipe to prevent another thread from attempting to use the pipe before i
105. exponent z frexpf value amp e will cause value x 2 to hold z in interval 1 2 1 load the exponent Returns the value g 2 Breaks x into integer and fraction as floats Thus z modf f value amp i returns float f and stores float i such that value i f This function is identical to modff above Table 3 9 Mathematical functions callable from a C program iv The user callable mathematical functions which use floating point num bers are collected in libmath09 a page 66 They are shown in Table 3 9 Workshop on Distributed Laboratory Instrumentation Systems 66 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt The ANSI standard requires that these mathematical functions use the type double for their arguments and return value The GNU cross compiler gives the possibility of using type float for both arguments and return values provided that the function names have the letter f appended to their usual name In order to avoid compiler warnings this convention has been followed for the functions in libmath09 a Some of the functions above require that the argument lics within a certain domain For instance the argument for the logarithm must be positive When such a function is called with an argument outside its domain the error EDOM is returned and the program exits For certain arguments the re
106. ferences Execution of a compiled program will always start at the first instruction of the startup routine crtO which performs a number of important functions providing an interface between a program written in the C language and the RInOS kernel A C program requires that i arge and argv be made accessible to the main program ii a function main exists which is called by the main program at the beginning of its execution iii uninitialized global variables be set to zero before their use iv a main program ending with a return statement should not go astray Untill recently different versions of the crtO o were needed to handle different situations PIC or absolute code Thanks to the recent developments this is no longer required and the overall situation has become much cleaner and easier to use crtO can do a few more things for the convenience of the programmer such as initializing a few things and setting up a global structure which can be used repeatedly for creating new threads The following run down of the code in ert0 s outlines the operations that are performed i It defines where in the Direct Page the pseudo registers and floating point accumulators are located ii It reserves space at execution address 020100 for argc and argv for use by the main program When the task is created the kernel puts here the number of arguments and strings representing them crt0 extracts from here the array of
107. form of function prototypes Workshop on Distribuied Laboratory Lastrumentation Systems 60 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Function prototype Purpose int atoh char p int atoi char p void bzero char b1 int length int doprnt char fgets char buf int size int dev int fprintf int fd char fmt int fprntf int fd char fmt int fputs char p int f int getc int device int getchar void char gets char buf void memepy char dest char sre int size int printf char fmt int prntf char fmt int prt10 int val char buf int prt16 int val char buf int prt32 int val char buf int putc int c int i int putchar char c int puts char p void sleep int n int sprintf char buf char fmt int argl int sprntf char buf char fmt s int spute int c char buf int stremp char s char t char strepy char s char t size_t strlen char str Convert ASCII hex string to integer Convert ASCII decimal into integer Zero length bytes of memory from address bl For internal use by printf fprintf Get string of size bytes from dev into buf Print arguments to file fd using format fmt As fprintf above but cannot handle floating point Put string at address p to file with id f
108. g system initialisation and are identified by a unique number whereas user semaphores are created by the application and are identified by their address During semaphore creation for both system and user types the fields of the semaphore structure are filled in with appropriate values The sys tem call OSCreateSem performs this task for system semaphores and returns the semaphore identification number For user semaphores the application program must perform this task The type of the semaphore is defined by placing the desired value from Table 2 8 page 33 into the SEMTYP field of the semaphore It can be seen in this table that several options are available for Event semaphores The simple Event behaves in an identical manner to a Mutex except that it wakes all processes waiting on it and sets its value to 1 This is somctimes not the desired action In some cascs it is neces sary to wake only those processes that are waiting on the semaphore when the particular event occurs If a process docs a DOWN on a simple Event semaphore after the event has taken place it will not be blocked but will continuc In repetitive events this type of semaphore after its first trigger will always indicate the occurrence of the event when what is required is the occurrence of each individual trigger To circumvent such problems RInOS also uses the Resettable Event semaphore which instead of incrementing its value to one following the event trigger always keep
109. ge MSG WRITE ICTP_IO_MSG_RD_ERR 8 could not read message MSG READ ICTPIO_MSG_DELETE_ERR 7 Could not delete message queue MSG DEL ICTPIO_MSG_CREATE ERR 6 Could not create message queue MSG CREAT ICTP IO ILLEGAL_DEV 5 no such device ILL DEVIC ICTPIO _WRONLY 4 trying read on a writeonly dev WR ONLY ICTPIO_RDONLY 3 trying write to a readonly dev RD ONLY ICTP_IO_BAD CONFIG 2 writing to LCD when in LEDmode BAD CONF ICTPIO BUSY 1 only a single board may be opened IO BUSY ICTPIO SUCCESS 0 operation succesful NONE Table B 1 Error codes returned by IO calls 96 Software for the 6809 Microprocessor board Verkerk and A J Wetherill ERR_ NONE ERR_BADCALL ERR_BADTASK ERR BADINST ERR TCREATE ERR_NOSLEIEP ERR BADXTFN ERR_SMCREATE ERR_PWDTH ERR PCREATE ERR_PUNINIT ERR_CALLOC ERR_PALLOG ERR_BADSIG ERR_INTLVL ERR_BADMSG ERR SMTMR ERR SMREL ERR SMTRM ERR THRDTMR ERR THRDKILL ERR_BADSEMA ERR BADKILL ERR FLOAT_PT He Symbolic name Meaning WaT Och wr Error message No error has occurred Illegal system call Non existent thread Incorrect thread id Thread creation error Thread is not sleeping Ilegal null exit function Semaphore creation error A pipe of zero width has been requested Pipe creation error Attempt to use an uninitialised pipe Common memory allocation error Paged memory allocation error Ilegal signal number Illegal
110. gement In most multitasking systems the concepts of process and thread refer to quite different entities the overhcads necessary to create a process being consid erably larger than those needed to create a thread Threads are generally created within a single process and allow cencurrency within that process Communication and synchronisation between threads within the process is encouraged Conversely communication between threads created by differ ent processes is only possible under strictly defined conditions RInOS does not distinguish between thread and process creation the two are identical However the concept of threads being created by a parent process is still a valid one under RInQS It will be assumed that any code downloaded using the ASSISTO9 monitor will be a process and any children it subsequently creates will be threads If one process can learn the identity of another it will be possible for the two sets of child threads to communicate Conse quently some of the terms used in the text will differ depending whether a thread or process is being refered to For instance the previously mentioned Workshop on Distributed Laboratory Instrumentation Systems 19 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt identity could be refered to as a process identity pid or a thread identity tid depending on the context In fact they refer t
111. ging will be shown The listing of the program pt4 c with line numbers is as follows 1 include lt syscalls h gt 2 include lt pthread h gt 3 include lt ICTP_IO h gt 4 5 void main int argc char argv 6 7 int k 8 9 for k 0 k lt arge k 10 pratf s n argv k 11 mssleep 50 12 13 k atoi argv 2 14 prntf s 4s d 4x n argv 2 k 15 mssleep 50 16 exit 0 17 18 After having compiled the program using the command Sofiware for the 6809 Microprocessor board C Verkerk and A J Wetherilt ccO9 opt4 pt4 c we type db09 pt4 Hello 007 The prompt db09 gt gt will now appear We then typed as our first command I inn2 The contents of this input file are as follows log2 pt4 c 9 22fe O1 Safe 00 3aff 00 pt4 c 9 HAR eS BBB oT The first line of inn2 will create a file log2 with a log of our symbolic debug ging session We have used this log to prepare the present Appendix The first lines of this log arc db09 gt B pt4 c 9 We set a breakpoint at line 9 db09 gt m 22fe 01 Behind the scenes we set up for redirection 01 of output from LCD display to the screen gt db09 gt m 3afe 00 Note the use of low level monitor commands 00 We set a flag and clear two bytes These gt db09 gt m 3aff 00 last two commands are tricky the address to 00 change differs from program to program gt db09 gt X Now we start the RInOS kernel and pt4 Breakpoint r
112. he PLA on channel 1 for the A port and channel 2 for the B port Multiple strings are not supported In many cases high speed parallel data transmission is required between two boards In such circumstances the technique of handshaking is generally used to ensure that data are transmitted safely at the highest possible speeds The MC6921 peripheral interface adaptor PIA provides this facility in the following manner During the transmision of a sequence a byte of data is written to port B of the PIA This action causes the CB2 signal to strobe low for a few microseconds indicating to the receiver that the data put on the bus is valid and should be taken On receipt of this strobe signal the receiver reads the byte and when ready strobes the CB1 line momentarily low in acknowledgement The PIA is configured to raise an interrupt when the ackowledgement is received and if another byte is available it will cause the sequence to continue The advantage of such handshaking during data transmission is that both transmitter and receiver can proceed at a rate suitable to both i e that of the slower device and cnsure that no data are lost during the process The PIA is configured to receive data in the A port in a similar manner using the CA1 and CA2 lines for handshaking The final two modes are used to interface with specificic I O devices that can be attached to the ICTP09 parallel port connector The LCD hoard consists of a liquid crystal display
113. home userl src prog c Things have become casier with the use of cc09 Instead of calling di rectly xgec the user can make use of a shell script that will set up the long command line for him cc09 In principle the user can type a line as short as ccO9 prog c The user may add options if he wishes and he is in fact encouraged to do so The more useful are v for verbose and Wall which will induce the compiler to complain about nearly everything in your program Asking for verbose output to the screen gives an insight into what happens behind the scenes and may help in finding oul that something went wrong Under particular circumstances other options may be needed such as E S c to stop the compilation process at certain stages or I L 1 to specify directories or files to use when searching for include files or libraries All options the user adds are passed by cc09 to the program that needs them including the arguments of the options Note that there is no need to specify the g option cc09 automatically adds it for you As said ccO09 can instruct the compiler to stop at a certain point in the chain but it can also make the compiler start at a given point Where actually to start is simply derived from the extension of the submitted file A C program will be compiled assembled and linked a program written in assembly language extension s will be assembled and linked whereas an object module extension o will be lin
114. i segmented memory addresses refer to paged memory If a page is not specified it defaults to the current page ii The g and x commands only return control to the monitor if a breakpoint is encountered Other wise the monitor effectively is killed as a process iii Breakpoints are allowed only in RAM It is an error to place a breakpoint on a swi instruction and will result in erratic behaviour iv The monitor accepts values only in hexadecimal form Table 2 19 Commands supported by the ICTPmon Monitor code segment The first byte of this segment contains the number of argu ments passed on the command line and the arguments themselves appear at offset 4 The final argument is terminated with a null character The address Workshop on Distributed Laboratory Instrumentation Systems 51 Abdus Salam ICTF Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt of the argument string is placed in the creation structure for passing to the OSThreadCreate system call of the kernel The code is then downloaded into memory on the board Finally the starting address of the code is obtained from the Motorola 519 format code file and a TCB is created for the process Code downloaded using either the 1 size orthela size com mands must always be started using the x command This is because instead of starting the individual threads RInOS itself must be started which in tur
115. ield Offset Description SENDER 0 Message sender s pid NXTMSG 2 Link to next message in list MSG 4 Pointer to message MSEMA 6 Message mutex MSGUSED 8 Message is in use Table 2 11 Message structure offsets Field Offset Size SIGPTR 0 2 Optional pointer to signal parameters SIGSEM 2 2 Pointer to EVENT semaphore Table 2 12 Signal structure offsets receiver s mailbox This is a linked list with its head in the MAILBOX field of the receiver s TCB and linked by the NXTMSG field of the message structure A thread may cxamine its message queue at any time by performing the OSGetMessage system call This call examines the message queue and returns the address of the data field of the first message block it finds If no message is present the thread blocks and waits on the counting semaphore given in the MSGSEMA field of its TCB An UP will be performed on this semaphore whenever a message is sent to the thread and the semaphore value indicates the number of messages in the queue awaiting processing A message sender may also desire to wait until the message is read by the receiver This can be arranged using the OSWaitMessage system call This creates a system semaphore and places a pointer to it in the message block at the MSEMA field This mutex is initialised to zero so that the sender will block when a DOWN is performed on it The receiver always checks this field and if a semaphore is found performs the n
116. ilt Otherwisc the TCB will not be reused and the thread will become a zombie In this case the value SUSPEND will be placed in the STATUS field vi Finally the stack segment used by the thread is released back to the pool of available memory and a context switch performed If an attempt is made to kill a thread using the OSThreadKill call several additional actions are possible depending on the CANCEL_STATE and CANCEL_TYPE bits of the ATTRIBUTE field If the CANCEL_STATE bit is cleared no cancellation is allowed and the system call returns the ERR_BADKILL error to the caller Otherwise the kill will succeed in one of two ways depending on the value of the CANCEL_TYPE bit If this bit is set to CANCEL_TYPE_ASYNC the thread will immediately be terminated otherwise the bit will have the valuc CANCEL_TYPE_DFRD for deferred and will be killed only at a time when it is safe to do so To indicate this state the CANCEL_PENDING bit is set in the attribute The POSIX 1003 1c standard defines certain points within a program where cancellation can safely occur and these are discussed in a later section The OSCancelPoint system call allows the thread to specify that it is safe to cancel and to perform that action if the CANCEL_PENDING bit is set In this way a thread can prepare itself for cancellation 2 4 5 Sleeping and waking threads A thread can temporarily suspend itself from the list of runnable threads by issuing the OSSleep syst
117. in Table 2 19 page 51 The user should be aware that breakpoints should be set after the pro gram has been loaded with the 1 command but before the x command Workshop on Distributed Laboratory Instrumentation Systems 71 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherile ii is issued Once a breakpoint is reached it should be removed before giving a g command The user is also strongly advised before single stepping through the program instructions to remove the jumper PTM see Figure 2 3 page 15 from the board so that clock interrupts are disabled Otherwise he will single step through the interrupt routines and never be able to gct out of them The second is the cross debugger db09 which runs under Linux and has no need for the actual hardware It accepts a few command line options see Table 3 13 page 72 but generally it is cnough to invoke it with db09 s prog The commands supported by db09 are very similar to those of ICTPmon and are shown in Table 3 14 page 74 db09 has several features that are not available in the debugger of ICTPmon It allows to input data or commands from a file to write a log of the session to a file or to write to another file the trace of a program Besides breakpoints which by the way can be skipped a specified number of times before they become active watchpoints can be set and r
118. ing lists of any semaphores Any counters are purged Arguments B Thread return code Blocking Will not block OSThread Join 15 Wait for a thread to terminate Arguments D Thread handle X Timeout in clock ticks zero an indefinite wait Note For POSIX 1003 1 compatibility this should always be zero Returns B Return code of terminating thread A Status code of terminating thread On ertor A ERR BADTASK Blocking Will block Continued on next page Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 100 Abdus Salam ICTP Trieste Novernmber 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSThreadKill 16 Kill a thread according to the state of the cancellation attribute i CANCEL_STATE OFF The thread is not cancelled and an error is indicated ii CANCEL_TYPE DFRD The thread is marked as CANCEL PENDING Gi CANCEL_TYPE ASYNC The thread is terminated Arguments D Thread identifier Returns Nothing On error A ERR_BADTASK ERR_ BADKILL Blocking Will not block Set an exit function Arguments X Address of exit function Y Address of function argument Returns Nothing On error A ERR BADXTFN Blocking Will not block Reset a thread s
119. int wr_close_pipe int pipe_id int wr_open_pipe int pipe_id int write_pipe int pipeid char data int yield void Table I 1 C functions resulting in a system call Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 Corresponding System Call OSReadPipe 38 OSRClosePipe 36 OSROpenPipe 35 OSReleasePipe 32 OSResetESem 5 OSResetSignal 30 OSResetUserESem 42 OSSendMessage 6 OSSetPriority 17 OSSetThreadAttr 27 OSSignal 9 OSStart 11 OSThreadCreate 13 OSThreadExit 14 OSThreadInstall 12 OSThreadJoin 15 OSThreadKill 16 OSUpSem 4 OSUpUserSem Al OS Wait Mcssage cf OS WaitSignal 10 OS Wake 19 OSWClosePipe 34 OSWOpenPipe 33 OSWyritePipe 37 OSYield 0 Continued 128 Appendix J Programming examples in C J 1 A sample program using pipes File tt4ce c Transposition of Jim s tp4 s into C The program tests the usage of pipes The main thread sets up a pipe and sends strings to the child which prints them on the lcd display Defining a very long string turned out to be difficult The string is defined in pieces which are glued together in primebuf E amp FF FF FR He He H cv January 19 1998 include lt syscalls h gt include lt ICTP_IO h gt extern int tid extern struct creation_block tcbmain char primebuf 512 char cbuffer 512 char localbuf 16 int mainpid c
120. is available to a user and has both gate and output on the on board standard ICTP 26 pin strip connector To ensure these and other interrupt signals are processed the jumpers must be set correctly on jumper JP Under RInO S all interrupts except the Workshop on Distributed Laboratory Instrumentation Systems 12 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt ie ae ied Figure 2 1 Schematic Drawing of the ICTP09 board Workshop on Distributed Laboratory Instrumentation Systems 13 Abdus Salam ICTP Trieste November 26 December 21 2001 Verkerk and A J Wetherilt Software for the 6809 Microprocessor board A addaa HOLNO LWN 4 ooa SHAAINGA apinaa Hossa qgaNwNa aH M 0o02 pay F ova oroyvy Z VWIDYv ocov SaDradma LWIDY ozov YMAAINIL oLow IWwHoaHodinsad Vid oocov PTERA ooov i SWwVHDOoOUd uya aaovd NOIL DNI ddwy wae SGE wares DOLE metered are oocoor y VWAHY HHOAA HOLINOIN Mae tee ae Oost HMHOvVLS WSL __ gt sas y ne 5 esie MIO pure DViqQqet SLUuEe sues I UITI SH eae oo LO As1GOWISeU UOLUIT ae o000 Y dV AHORN LN 14 Figure 2 2 Memory Map of the M6809 under RInOS Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 Soft
121. k with the same priority level viii The thread has its STATUS field cleared in its TCB ix The highest priority thread in a runnable state now runs If this is the new child its initial context is pulled from the stack and execution starts at the address indicated in the TPT 2 4 3 Context switching between threads A context switch occurs when a running process becomes preempted blocked or is put to sleep Whenever this occurs the kernel must save sufficient infor Workshop on Distributed Laboratory Instrumentation Systems 25 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt mation about the running process to enable it to start again at a later time at the position it stopped The information that must be saved consists of the contents of the machine registers together with the stack pointer and the address of the next instruction that would normally be executed Together this information constitutes the context RInOS saves this information by requiring that all access to the system is via either a software or hardware interrupt In both cases the entire registcr sct is pushed onto the current stack and automatically saved In addition the particular software interrupt selected for system usage also switches off interrupts which allows the con cept of atomic or indivisible system calls which can be interrupted only at the discretio
122. ked only In all cases where the process is brought to a succesful end the entire downloadable and executable program will be found in an ELF file prog where prog is the name the user gave to the program Options which are not recognised by cc09 are passed on unchanged This makes it possible for instance to obtain output useful for debugging the compiler itself In conclusion when compiling for downloading to the board the recom mended command is ccO9 v Wall oprog prog c The reader should note that multiple files can also be compiled assem bled and linked by cc09 with a single command line In that case it is Workshop on Distributed Laboratory Instrumentation Systems 70 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocesser board Verkerk and A J Wetherilt recommended to specify the name of the final output file with the o op tion Otherwise the final file will carry the name of the last file in the list Similarly if it is desired to have an assembly listing of all compiled and or assembled files the option save temps should be used otherwise only a listing of the last file in the list will be produced In the list of filenames files with extensions c s and o may be mixed in any order Thus the following will work ccO9 v save temps omyprog main c subl o sub2 s 3 6 Downloading the program The prog file can be downloaded onto the hardware via a seria
123. l line driven on the Linux side from one of the serial ports and on the side of the m6809 board by ACIA1 The debugger db09 will take care of the downloading and running of the program In addition you may also use it to debug your program The procedure to follow is described in the next chapter In principle it is also possible to use a terminal emulator running on the PC to download the program The terminal emulator will then communicate with ICTPmon on the board so low level debugging will be possible but the procedure becomes much more complicated and worse the symbolic debugging facilities will be lost The preferred terminal emulator is seyon 3 7 Debuggers Two low level debuggers have been available since a number of years both assembly language level debuggers Very recently the one running under Linux db09 has been upgraded to do symbolic debugging as well db09 can run in two modes using its built in simulator of the m6809 instructions or by maintaining a dialog with ICTPmon on the real hardware board using ICTPmon s low level debugging facilities More on this and the procedure to follow to use db09 in the next chapter The two low level debugging facilities available are i The first is part of ICTPmon and runs directly on the hardware It allows to inspect and modify memory and register contents and to set break points besides loading programs The set of debugging commands implemented for debugging are given
124. ld of the TPT This address is pushed onto the stack prior to the register set In addition the address of the function that is called when the thread terminates is also pushed onto the stack after the argument pointer but before the context The complete initial stack then appears as in Table 2 4 page 24 When the thread is dispatched the context Workshop on Distributed Laboratory Instrumentation Systems 23 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Position Contents 14 Arg Pointer S 12 Return Addr S 10 Thread s PC 5 8 U Reg 5 6 Y Reg S 4 X Reg 543 DP Reg S 2 B Reg S 1 A Reg S CC Reg Table 2 4 Stack layout before dispatching of thread Attribute DETACH_STATE CANCEL_STATE CANCEL_TYPE EXIT_PENDING CANCEL PENDING 0x40 Description Detach state bit Cancelation state bit Cancellation type bit Exit pending bit Cancellation pending bit Table 2 5 Thread attribute fields is removed and the stack ressembles the stack of a simple function call with the return address in this case a function in the RInOS kernel being pointed at by the stack pointer register and a single argument on the stack above the return address Certain compilers use the 6809 direct page register for various purposes and in such cases the TDP field can be used to set the initial value of the direct pag
125. level language Various cross compiler tools developed or adapted for use with the ICTP09 board under RInOS are available The RinOs kernel and library interface have been designed so as to follow closely the POSIX 1003 1 standard for threads PThreads Although not yet compliant fully with the standard many of its features have been imple mented It is hoped that both the ICTP09 board and RInOS will find use not only as an aid to the teaching of real time principles and methodology but also as research and development tools in laboratory instrumentation To this end the RInOS kernel is romable and relatively easily adaptable to other 6809 boards and configurations A C version is planned for the future that will be portable to other microprocessors 2 2 The ICTP0O9 board The 6809 board implements a large number of functions at the price of some complexity 24 integrated circuits are used in its construction see Figure 2 1 It comprises 11 Soltware for the 6809 Microprocessor board C Verkerk and A J Wetherilt 2 serial communications ports 1 parallel port 3 timer channels 2 channels of 12 bit ADC input 2 channels of 12 bit DAC output 16k EPROM 8k base RAM 128k RAM arranged in 4 pages each of 32k The memory map of the system is shown in Figure 2 2 The board is based around a MC6809 processor running at a clock speed of 1 MHz Although the 6809 is now an old microprocessor its use in a piece of hardwa
126. lpid int pipe width clprio Function prototypes 129 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt void main void void childi void int create _child int void main void int i char pt char pt2 char msgi 10 Define anumber of short strings char p0 The Walrus and the Carpenter were walking char pi close at hand char p2 They wept like anything to seesuch quantities char p3 of sand If this were only cleared char p4 away they said it would be grand a3 char p5 If seven maids with seven mops swept it for char p6 half a year Do you suppose the Walrus said char p7 that they couldsweep it clear char p8 I doubt it said the Carpenter and shed a Ws char p9 bitter tear k Define an array of pointers msg1 0 po msg1 i pi msg1 2 p2 msg1 3 p3 msgi 4 p4 msgi 5 p5 msgi 6 p6 msg1 7 p7 msgi 8 ps msgi 9 p9 mainpid tid width 1 ciprio 3 pt2 primebuf Glue the strings together leaving out the O characters pt msgi 0 Workshop on Distributed Laboratory Instrumentation Systems 130 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt for i 0 i lt 10 i pt msgif il while pt 0 pt2t pt pt2 7 0
127. lue is set in the PRIORITY ficld and the TCB is linked into the system priority list RInOS maintains a linked list of TCBs starting with the system variable prioptr and linked using the TCB PPTR field Thus prioptr points at the highest priority thread in the system that is the thread having the largest value in the PRIORITY field In turn the PPTR field of this TCB points at the next highest priority thread and so on The final TCB in the chain is that of the null thread which having the lowest priority of any thread has its PPTR field set to zero or null During initialisation the null thread is the only thread in the linked list and prioptr points directly at the null thread Subsequently as other threads are created they are inserted at appropriate points in the list Workshop on Distributed Laboratory Instrumentation Systems 22 Abdus Salam ICTP Triesie November 26 December 21 2001 Software for ihe 6809 Microprocessor board Verkerk and A J Wetherilt Field Offset Size Description PSEG 0 1 Page register value for the thread CSEG 1 2 Start of Code segment Module SSEG 3 2 Stack segment SLEN 5 2 Stack length CSTART 7 2 Entry point of code ARGPTR 9 2 Pointer to thread s Argument Environment block TPRIO 11 1 Requested priority TPID 12 2 Thread s pid OSThreadInstall only TMEM 14 2 Memory size requested OSThreadInstall only TATTR 16 1 Initial thread attributes TDP 17
128. mask is cleared at the first safe opportunity Throughout the kernel interrupts arc cnabled when possible and disabled only when it would be dangerous to allow more than a single thread simultaneous access to the same block of code Such code blocks are known as critical sections and must be carefully guarded The next step is to clear the carry bit in the stacked copy of the condition code register to indicate that no error ocurred by default A subsequent error will cause this bit to be set otherwise it will remain cleared Finally the system call number is obtained which acts as an offset into the dispatch jump table The address of the required function is loaded from the dispatch table and a jump is made to that location Return from a system call is basically the reverse process The 6809 stack pointer register is loaded with the saved stack value in the TCB of the highest priority task that can run and the registers popped making control continue following the software interrupt The highest priority task is not always the same task that issued the original interrupt as during processing of the system call the calling thread can sometimes block that is become temporarily suspended until some action is complete or else another higher priority task can be woken which will take precedence over the first task A discussion of such context switching is deferred until threads are discussed in detail in the next section 2 4 Thread Process mana
129. mbly output 3 33 3 xgcc compiler compiled on katje 4 This is version 4 0 6 of xgec for m6809 5 33 OPTIONS mlong_branch strength_reduce 6 OPTIONS peephole omit_frame pointer signed char 7 33 Source ttif c 8 Destination tmp cca00349 s 9 Compiled Tue Aug 25 15 58 54 1998 10 META compiled by GNU C version 2 7 2 IL ha pte srr se re es Se a 12 module ttlf c 13 14 area _BSS 15 area _CODE 16 globl main 0000 17 _main A a a ie 19 33 PROLOGUE for main 0 isaac ae een ene ass Sea esessasessses 6000 32 60 21 leas 0 s allocate 0 bytes auto variables 0002 34 20 22 pshs y Save stack frame 6004 1F 42 23 tfr s y Set current stack frame 0006 GE OO 24 ldx ZD1 6608 34 16 25 pshs x pushed register ZD1 26 END PROLOGUE 000A 17 00 00 27 lbsr _ main CALL VOIDmode ___main pcr bytes 000D EC 8D 00 03 28 ldd _tcbmain 3 per 0011 C3 FF 60 29 addd 256 0014 ED 8D 00 03 30 std _tcbmaint3 pcr addhi3 _tcbmaint3 per by 256 gt _tcbmain 3 pcr 0018 E6 8D 00 11 31 ldb _tebmainti7 pcr 001C CE 01 32 addb 1 OO1E EY 8D 00 11 33 stb _tcbmain 17 pcr addqi3 _tebmain 17 per by 1 gt _tcbmaint17 pcr 0022 30 8C 5D 34 leax _childi pcr address of symbol gt X 0025 1F 10 35 tfr x d ist part of movhi for symbol or label 0027 ED 8D 00 07 36 std _tcbmaint 7 per second part of movhi default 002B CC 00 03 37 ldd 3 first part of movhi for const 002E ED 8D 00 64 38 std _clprio pcr
130. n will start the thread with the highest priority Although RInOS can run up to 32 different position independent threads only a single absolute thread can be loaded at a given time and an error will be generated in the case of the la size command if an attempt is made to load more than this number To circumvent this restriction the single thread should create all other threads required by the user as child threads and gracefully kill itself when no longer needed 2 9 3 Debugging with the modified ASSISTO9 monitor A fully commented example of a debugging session using the modified AS SISTO9 monitor is given in Appendix H page 122 Workshop on Distributed Laboratory Instrumentation Systems 52 Abdus Salam ICTP Trieste November 26 December 21 2001 Chapter 3 The Cross compilation Chain 3 1 The Cross compiler A GNU C compiler or cross compiler chain consists of a sequence of five programs executed in sequence a supervisory program gec or xgec for a compiler or a cross compiler respectively the preprocessor cpp the compiler proper cc1 the assembler as and the linker loader Id The entire chain is usually invoked by entering on the command line either gcc or xgcc For reasons that will become clear later we do NOT recommend to invoke gcc directly but to use a shell script ccO9 instead The steering script cc09 is adapted to the local situation and is infinitely more convenient to use than zgce The
131. n Distributed Laboratory Instrumentation Systems 139 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix L Example of a map file Below is the map file of the program shown in the second example of Ap pendix J Hexidecimal Addr Size ABS 90000 0000 DIRECT_start _BSS_length _DATA_length DIRECT_length _CODE_length PAGES_length STACK length _CODE_start _DATA_start _BSS_start PAGES_start STACK_start Addr Size 2100 8 OD75 140 Decimal Bytes Attributes wee eee ee ee se 0 bytes ABS OVR Decimal Bytes Attributes 3445 bytes REL CON Software for the 6809 Microprocessor board C Verkerk and A J Weilerilt 2104 _argv 2180 _Empty 2200 _start 226C ___main 228A _exit 22B9 _main 2397 _childi 23DC _create_child 2440 _prntf 2470 _send 2470 _send_message 2491 _printerr 2665 _putec 274B _receive 274B _get_message 2772 __dprnt 2432 _memcpy 2483 _thread_ create 2AB7 __prti0d 2586 __prti6 2C2F _ICTP_I0_write 2D88 ___modhi3 2DBB ___divhi3 2DFQ _divxbd Hexidecimal Area Addr Size Decimal Bytes Attributes DIRECT 0000 003D 61 bytes ABS 0VR PAG Workshop on Distributed Laboratory Instrumentation Systems 141 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 002C errno 002E Fpacclex 002F Fpaccimn 0032 Mantsgni 0033 Fpacc2ex 0034 Fpacc2mn 003
132. n immediate return to the caller is made Counting semaphores are not linked into the callers list of semaphores ii In the case when the semaphore value was previously zero the semaphore manager now links the thread into the list of tasks waiting on the semaphore with its head in the NXTSEM field of the semaphore and linked using the SEMALNK field of the TCB structure In the case of a Mutex the order of insertion into the list depends on the current pri ority of the blocked thread the higher its priority the nearer the front of the list For Event and Counting types the thread is inserted at the rear of the list iii Finally the thread is put to sleep by marking the STATUS field of its TCB with the value _WAIT and a context switch performed The UP operation proceeds in the reverse order It too guarantees atom icity and can not be interrupted during its critical sections i The list of processes waiting on the semaphore is first examined If the NXTSEM field is NULL the value of the semaphore can be incremented if currently below its maximum value simple Event semaphores are always changed to one If the semaphore is a Mutex or an Event the owner of the semaphore is set to NULL and the semaphore removed from the thread s list of owned semaphores A return to the caller is then performed ii If the list of waiting threads is not empty the first thread in the list in the case of Counting and Mutex semaphores is sele
133. n of the kernel itself at dangerous or inconvenient times the system can be protected from undesirable events The steps taken during each system call to save the context are as follows i The 6809 registers are loaded by the application with the desired values and the system call issued This causes the register set to be pushed onto the current stack and execution to transfer indirectly to the RinOS software interrupt handler ii The system variable intlvi is incremented to indicate the depth of nested interrupts both hardware and software If it is found to be zero prior to being incremented the current stack pointer is saved in the STACKPTR field of the TCB and the system stack loaded Otherwise the system itself has been interrupted and the system stack is already in use Resetting the system stack would be an error in this case and lead to system failure iii The return address is incremented to the address following the function number and the function number loaded iv The stacked context is made accessible by pointing at it with the 6809 U register v Interrupts are unmasked to allow the rapid processing of hardware events vi A jump to the desired system call is made using the dispatch jump table and the call is executed During the normal operation of a system call another higher priority thread may be made runnable by one of a number of means it may be woken up from sleep it may become unblocked by some a
134. n of zero is assumed throughout which allows the ASSISTO9 monitor to download the code to an address determined by the RInOS memory manager This assembler example requires that the file syscalls inc be included in the source code Before this assembly language program can be assembled under Linux making use of cc09 it must be treated by jim2rinus The changes to be made are e include syscalls inc must be written as include syscalls inc equ becomes rmb should read b1kb e fcb becomes byte e a label must cnd with a thus start becomes start G 1 Create a thread using POSIX 1003 1 com patible method Example2 asm Create a POSIX 1003 1 compatible thread with the following attributes 118 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Detach state Detachable Cancel state Cancelable Cancel type Defered Stack size 0x1000 Stack address Don t care Priority 4 The thread wil include Data area parentid childid Define an attr l not take an argument syscalls inc rmb 2 Handle of parent thread rmb 2 Handle of child thread ibute structure for the thread attribute rmb 11 attr_stacksize equ 0 Offset of stack size attribute attr_page equ 2 Offset of stack page attr_stackaddr equ 3 Offset of stack address attribute attr_detachstate equ Offset of detach state attribute attr_cancelstate equ 6 Offset of cancel state attribut
135. n the DAC driver as a mode exists to couple the timer channel 3 to the measurements If the timer is not used ADC conversions will be made whenever requested by a call to the device driver As the conversion time for the ADC is about 30 microseconds no blocking is done and the processor waits until a conversion is ready If the timer is selected then the call blocks until woken by the timer interrupt Multiple reads require the address of a buffer to store the data and the number of conversions to be made must be passed to the driver The conversion rate is specified by the timer which is set by a call to the ADC initialisation function 2 8 5 The PIA driver The PIA diver has four modes in which it can be initialised These are i The standard mode Workshop on Distributed Laboratory Instrumentation Systems AT Abdus Salam ICTP Trieste Novernber 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt ii The handshaking mode iii The LCD board mode iv The Colombo board mode The standard mode is the most general and simplest as it is set up without an interrupt handler A mask supplied in the X register during initialisation is used to determine which lines are sct up as inputs and which as outputs The high byte of X specifies the direction of the A port lines with 1 output and 0 input and the lower byte specifies the B port Byte width data can be read from and written to t
136. ned that it cannot be accessed Be careful different local variables may have the same name in different places of your program You should know what you are asking for db09 knows about the type of all variables you defined but it does not know the type of variables defined in library functions The D command may then be followed optionnally by a format a single character from the following set c for character for floating point i for integer or s for string At present you can only ask for the valucs of a simple variable Members of structures and unions are not yet correctly handled but will be at a later stage 4 5 6 Show the contents of the stack The S command caters for this The present implementation of this command is very rudimentary except when you run db09 with the s option It simply shows the value of the stack pointer itself and 32 bytes starting from does not yet work correctly Workshop ou Distributed Laboratory Instrumentation Systems 87 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt a memory address below the stack pointer and which is a multiple of 16 You have therefore some interpretation to do Note that the values of local variables are easier discovered with the D command 4 5 7 Using an input file containing debugging com mands If you find yourself in a situation where you will have to g
137. newpc cf94 BreakPoint Reached OK we hit first breakpoint PC OP A B X Y U 8 DP EFHINZYC CC 2340 1306 2C 6B 2C5B 4CF6 2D00 4CF2 2D 01000000 40 dbo9 gt d 2400 we inspect pseudo register ZD0 00 01 02 03 04 05 06 OF 08 09 OA OB OC OD OE OF H is oe ee ee MNH 2D00 2C 5B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 AEE a ZDO contains Ox2C5B ab09 gt d 4cfO we also inspect the stack 00 O1 02 03 04 05 06 07 08 09 OA OB OC OD OE OF 4CFO 4C F6 00 03 00 00 21 82 22 A4 21 80 C5 DC 21 00 Perera Pl stack at 4CF2 has 0003 dbO9 gt d 2c50 2c6f let us look at 2C5B Warkshop on Distributed Laboratory Instrumentation Systems 149 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Micraprocessor board C Verkerk and A J Wetherilt 00 01 02 03 04 05 06 O7 08 O9 OA OB OC OD OE OF 2C50 00 08 00 10 00 20 00 40 00 80 00 00 21 00 4B 00 K 2C60 01 00 23 82 21 00 O1 01 02 3B 7E 00 2E 00 00 00 m s e eyes this is tcbmain as ttif map confirms db09 gt zg we continue to run I was interrupted from 12e newpc 0 Oops we did not expect this I was interrupted from 12e newpc 0 at least not so many of them I was interrupted from i2e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupted from 12e newpc 0 I was interrupt
138. ng of one of several pushbuttons depending on the jumper settings on the board Please refer to the notes on College hardware for more information concerning both the Colombo and LCD boards 2 8 6 Installation of a new driver Installation of a new driver for any of the existing bardware can be achieved using the kernel function OSInstallDriver This function allows either a new driver to be installed or the existing driver to be replaced by the default driver depending on the valuc in the 6809 B register The user must supply the following information to the function in the form of a structure in memory see Table 2 18 page 49 isr aadis of interrupt service handler driver New device driver address hbase Address of hardware base scratch Address of device scratch data area Table 2 18 Device driver installation structure Following the installation of the driver appropriate initialisation must be performed by the user It is important to note that since the new driver will be available to all users the device driver and its scratch area must be in common memory 2 9 The modified ASSISTO9 monitor 2 9 1 ASSISTO9 commands The ASSISTO9 monitor is made available by Motorola to provide a full range of debugging tools for the 6809 The original version has been adapted and extended to fulfill the requirements of the paged memory and kernel The Workshop on Distributed Laboratory Instrumentation Systems 49 Abdus Salam
139. nite sleep Returns Nothing On error A ERR_BADTASK Blocking Will block OS Wake 19 Wake a thread Arguments D Thread identifier Returns Nothing On cerror A ERR BADINST ERR BADTASK ERR NOSLEEP Blocking Will not block OSYield 0 Voluntarily yicld to another thread Arguments None Returns Nothing On crror Nothing Blocking Will not block Allocate common memory Arguments A Thread number 0 system X Requested size Returns X Address of allocated block Null on error Oun error A ERR_ CALLOC Blocking Will not block Continued on next page OSCAllocMem 2 o a lable C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 102 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetberilt OSPAllocMem OSPFrecMem Continued from previous page Symbolic name Description and behaviour OS5CFreeMem 21 Frec common memory 22 23 Arguments D Size of memory to be freed X Address of start of memory block Returns Nothing Onerror Nothing Blocking Will not block Allocate paged memory Arguments A Thread number 0 system B Page requested 1 for any page Returns A Page of allocated memory X Address of start of allocated block Y Size of memory allocate
140. ns The null thread is thus the default thread for the system and has its id field set to 1 During system initialisation the null thread is set ready to run This consists of the following actions i A stack is set up for the null thread and default values for each register are stored in the appropriate locations on the stack The addresses of both the start of the region reserved for the null thread stack and the location containing the start of the register set or context are stored in the fields STACKSEG and STACKPTR respectively The size of the reserved stack memory is also stored in the STACKLEN field of the TCB When the null task is dispatched the system uses the information in these fields to load the processor stack pointer register and pull the context from the null thread stack The final value to be pulled from the stack is the address at which the processor will execute its next instruction For the null thread the memory at this address contains a single instruction Workshop on Distributed Laboratory Instrumentation Systems 20 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Field Off Size Category Description set PPTR 0 2 System Link in priority list points to next TCB INSTANCE 2 1 System Instance of this thread ID 3 1 System Thread s identification numb
141. nstructions addd 7 x or suba 56 etc They work on 8 and 16 bit operands Workshop on Distributed Laboratory Instrumentation Systems 94 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt e Multiply instruction it does an unsigned multiplication of the contents of the A and B registers putting the result in D e Compare instructions they compare the contents of an 8 bit or 16 bit register with the contents of the effective address by performing a subtraction They then set the appropriate bit or bits in the CC register e Branches and Long Branches conditional and unconditional branches exist in two flavours The first can branch to a location at most 128 bytes before or 127 bytes beyond the branch instruction itself The long branches can branch 32768 locations backward and 32767 bytes forward The branch to subroutine bsr and long branch to subroutine lbsr also belong to this category e Jump and Jump to Subroutine these two instructions jump to an absolute location The jump to subroutine is associated with a return from subroutine instruction e Increment Decrement Complement Negate Shift and Test instruc tions acting on 8 bit registers or memory bytes inca dec loc cte e Transfer and Exchange instructions which transfer contents of one reg ister to another of the same length or exchange contents between two registers e
142. ntf is called Breakpoint reached This is the entry of _prntf Line 11 file pt4 c We reached line 11 x gt LCD Display pt4 lt x At this point LCD would show pt4 db09 gt We repeat N once more Function Call _mssleep Breakpoint reached Line 12 file pt4 c And reach line 12 via a call to _mssleep gt LCD Display pt4 lt es LCD display is unchanged db09 gt D k We inspect the value of k the loop index Value of k 0 0x0 It is still zero db09 gt N We do another N Line 10 file pt4 c And get back to line 10 again x gt LCD Display pt4 lt x With LCD unchanged dbog gt Repeat the N command Function Call ___mulhi3 Breakpoint reached Fonction Call _prntf Breakpoint reached Line 11 file pt4 c gt LCD Display Hello lt Now LCD shows arg 1 Hello db0g gt N again Function Call _mssleep Breakpoint reached 2 At this point we had to pull out the PTM jumper otherwise the N command will not work Hopefully this is also corrected by now Workshop on Distributed Laboratory Instrumentation Sysiems 154 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Line 12 file pt4 c gt LCD Display Hello lt db09 gt D k Inspection of k shows 1 as result Value of k 1 0x1 db09 gt N We continue
143. o the same object 2 4 1 The Task Control Block Central to thread management is the Task Control Block TCB This is a structure that contains all the information necded by the system to define and manipulate a thread It is constructed during thread creation and is valid during the whole life of a thread The TCB stucture is given in Table 2 1 page 21 Each field of the TCB falls loosely into one of several categories depend ing on its function Fields in the system category are used by RInOS for scheduling and general thread management fields in the semaphore and IPC categories are used by the semaphore and signal message managers respec tively whereas fields in the user category reflect values either set or used by application programs Blank TCBs are created during system initialisation The number of threads that can simultaneously exist is thus set to 32 This limit can be changed up to a maximum of 255 by altering the value MAXTASKS and re assembling However the current limit of 32 tasks is appropriate for most applications considering the available hardware In addition a special task known as the nul thread always exists This thread is special in that it is always available for running and cannot block sleep or be killed It has a lower priority than any other thread and therefore will run only when there are either no other threads in existence or that no other thread can run as a result of blocking sleeping or other reaso
144. o through sev eral debugging sessions and to start each one you need to issue a longish list of commands such as setting a series of breakpoints you may find it convenicnt to write a short input file An example of such an input file is L logo B ttileil c 39 X K ttilet c 39 I To use it you type I in file where in file is the name of your input file This should in general be the very first command you execute but you may use an input file anywhere during the debugging session The last command in the example 1 will close the input file and control over db09 will return to the keyboard 4 5 8 Repeating a command db09 remembers the last command it executed To repeat the previous command it is enough to type a carriage return character the ENTER key There is also a mechanism that allows to repeat a stored command after the execution of any command typed on the keyboard An example is R D ret The effect of this is that after any keyboard command you will execute the command D ret where ret is a variable local or global In this way you can inspect continuously a variable without extra effort The stored command will remain in force until another R command is issued A R command without arguments will simply crase the stored command Only a small subset of the symbolic commands can be specified with the R command D and N Workshop on Distributed Laboratory Instrumentation Systems 88 Abdus Salam ICTP Tries
145. ocation 0x2004 and ending with a null character at location Ox211a Before starting RInOS a few breakpoints will be set one each in the main thread and one in the null thread The null thread has been placed in RAM to allow breakpoints to be set We choose to set the breakpoint in the main thread at the start of the exccutable code This can most easily be found from the code listing but let us find this valuc using the monitor functions As there is no field to denote the entrance point of the code in the TCB we can deduce it from the context placed by RInOS on the stack The stack pointer at offset 12 in the TCB at address 0x164 has the value Ox2cf0 We dump this valuc gt d 2cf0 0 1 2 3 4 5 6 7 8 9 A B CC D E F 2CFO 00 01 02 29 00 B2 00 95 29 00 25 87 C6 11 21 00 0 YL gt The 6809 pulls its registers in the order ccr a b dp x y u pe At offset 10 into the stack 0x2cfa therefore we can find the starting address of the task in memory We can see that this is the address 0x2587 and we set a breakpoint at this location Workshop on Distributed Laboratory Instrumentation Systems 124 Abdus Salam ICTP Trieste Noyember 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherili gt b 2587 00 2587 gt b 12e 00 2587 00 012E gt Note also that the D register A B contains the thread handle 0x0102 Now start RlnOs gt X The monitor will stop at address 0x
146. of 32 tasks can be present in the system provided the total size does not exceed 128 Kbytes and no single program occupies more than 32 Kbytes Programs written in C or in assembly language can be easily compiled on the PC and downloaded to the board They can be debugged at assembly language level directly on the board making use of facilities of ICTPMon or under Linux using a cross debugger db09 For the future various further extensions are planned The most signifi cant are a portable version of RInOS re written in C and more convenient debugging facilities based on gdb Several people contributed to this collection of software and software tools We mention here Carlos Kavka Ulrich Raich Pablo Santamarina and Sergei Borodin Full credit is given in the Acknowledgements 10 Chapter 2 User Manual for RInOS 2 1 Introduction RInOS Real time Integrated Operating System is a real time kernel de signed for use with the ICTP09 board A total of over 40 primitive functions are available for application programs by the use of system calls RInOS is integrated with a modified version of the ASSISTO9 monitor supplied by the Motorola Company for use with their 6809 microprocessor This combi nation of RInOS with ASSISTO9 allows the downloading and debugging of multithreaded application programs at the assembler level A library of C functions has been written so that the user can access all the features of the system from a high
147. oing to create many child threads then you should remember that a limit may be imposed on the amount of local variables cach thread may use In case the reserved space would not suffice you can ask for more with palloc_mem and do some extra work setting up tcbmain For each child thread you create you must specify four things its pri ority its entry point its direct page number and its stack address The easiest way to do this is to write a short subroutine call it make_child or whatever include lt syscalls h gt extern struct creation_block tcbmain int make_child int prior void child_entry int child tcbmain tprio prior Workshop on Distributed Laboratory Instrumentation Systems 78 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt xii xiii xiv tcbmain sseg tcbmain sseg 0x0100 tcbmain tdp tcbmain tdp 1 tcbmain cstart child_entry if child thread_create prior amp tcbmain lt 0 printerr return child Note that tcbmain has been defined as a global structure and that all other values needed to create a new thread are already filled out in this global structure It is important to note that the constant in the example equal to 0x0100 you subtract from tcbmain sseg determines the size of the stack of the thread that called make_child If you used lots of local variables in that parent
148. ola S19 format ready for being downloaded to the board in the ancient situation when a terminal emulator was needed to communicate with the board The main product of the linker is a file in the standard ELF format which is divided into sections containing the executable code in the Mo torola S19 format required by C TPMon for downloading and as a memory image needed by the simulator which is part of db09 and the information for symbolic debugging After linking and loading the memory layout of a program is as shown in Table 3 4 assuming that RInOS decided to allocate space for it starting at address 0x4100 Option Effect i s Intel hex file ihx or Motorola file s19 format m Generate a map file file map x d Define the radix hex or dec for number representation b arca expr Specifies base address for the specific area fileN Files to be linked Table 3 3 Options for the linker aslink Workshop on Distributed Laboratory Instrumentation Systems 57 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt It is strongly recommended to compile multi threaded programs into a single ELF file for downloading If the various threads are compiled and linked separately the size of each single thread may become excessive and each thread would contain a copy of the startup routine which will lead to difficulties
149. olombo board mode Table D 2 Device driver definitions Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 110 Appendix E Structure and definitions reference Field PPTR INSTANCE ID PRIORITY STATUS CODESEG STACKSEG STACKSIZE STACKPTR PAGE PARENT EXITSTS EXITCODE EXITFUNC EFARG MAILBOX SEMALNK TIMRCNT TIMRLNK ESEMALNK SEMAOWND SEMAWAIT MSGSEMA ERRORSTS ATTRIBUTE Size Category System System System System System System System System System System User User User User User IPC Semaphore System System Semaphore Semaphore Semaphore IPC User User system PrRPereS MINN NNN NY NRF REFN RNY NY NNR RP RP eb Description Link in priority Hst points to next TCB Instance of this thread Thread identification number Priority value Thread status Start of thread code segment Pointer to stack segment Size of stack segment Thread stack pointer Page of thread Parent of thread Exit status of thread Return code of thread Ptr to thread exit function Ptr to exit function argument Pointer to mailbox Link to chain of semaphores Sleeping time Link to timer list Link to threads waiting for termination Link to list of semaphores owned by thread Pointer to semaphore thread is waiting to own Message queue counting semaphore Last error status Thread set of attributes
150. omplete the monitor will respond with Task 2 loaded at address 00 2200 gt The TCB of the new task can be examined by doing a memory dump of the first 0x80 bytes of the RInOS work area gt d 100 80 Which will give on the display 0 1 2 3 45 6 7 8 9 A BC OD EF 0100 00 01 01 30 01 01 30 01 01 58 00 00 00 64 00 00 0 0 X d 0110 10 03 00 00 00 40 00 EC 00 00 00 45 00 8C 02 80 Eresi 0120 00 00 00 00 00 02 00 10 00 20 00 00 00 64 20 FE ee 0130 00 00 00 01 00 00 00 EC 01 00 00 45 1E FO 00 0 Eoas 0140 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 eee 0150 00 00 00 00 00 00 00 00 01 30 01 02 04 00 22 00 Dasa 0160 2A 00 03 00 2C FO 00 01 00 00 00 C6 AF 64 00 00 d 0170 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 Le gt Several points are worth noting here The nuli thread is always the first thread and as such has its TCB at address 0x130 The task we have just loaded can be seen at address 0x158 The priority is at offset 4 and can be seen to be 4 as set The task handle at offset 2 is 2 and the status of the task is 0 indicating that it is ready to run when dispatched by the kernel The priority field at offset 4 into the TCB is set to 4 in accordance with the command line The various linked lists set up during initialisation can clearly be scen Starting at the priority list pointer at address 0x108 the list of tasks in order of priority can be
151. onst OOSF 34 06 58 pshs d second part of movhi case PRE_DEC 0061 30 8C A7 59 l ax LCi per address of symbol gt X 0064 1F 10 60 tfr x d ist part of movhi for symbol or label 0066 34 06 61 pshs d second part of movhi case PRE_DEC 0068 DC 00 62 ldd ZD2 first part of movhi for REG 0064 DD 06 63 std ZDO second part of movhi REG 006c 17 00 00 64 lbsr _memcpy CALL VOIDmode _memcpy per 4 bytes QOBF 32 64 65 leas 4 s addhi Ris Ris 4 0071 EC 8D 00 00 66 ldd tid per first part of movhi default 0075 ED 8D 00 00 67 std _mainpid pcr second part of movhi default 0079 CC 00 03 68 ldd 3 first part of movhi for const O07C ED 22 69 std 2 y second part of movhi case PLUS register 1 OO7E EC 22 70 Idd 2 y first part of movhi case PLUS register 1 0080 DD 00 71 std ZD0 second part of movhi REG Q082 17 00 B7 72 lbsr _create_child CALL R ZDG _create_child 0 bytes 0085 DC 00 73 ldd ZD0 first part of movhi for REG O087 DD 00 74 std ZD1 second part of movhi REG 6089 DC 00 75 ldd ZD1 first part of movhi for REG 008B ED amp D 00 02 76 std _cipid per second part of movhi default OO8F 77 L2 OO8F 16 00 03 78 lbra L4 0092 16 00 49 79 lbra L3 0095 80 L4 0095 1F 20 81 tfr y d 0097 C3 00 04 82 addd 4 009A DD 00 83 std ZD1 addhi3 y by 4 gt 2ZD1 009c DC 00 64 ldg 2D1 first part of movhi for REG 009E 34 06 85 pshs d second part of movhi case PRE_DEC OOAG
152. ored in the fields PIPE WDTH and PIPE_MEM respectively iv Two counting semaphores are created to represent FULL and EMPTY states of the pipe The FULL semaphore is initialised to a value of 32 and the EMPTY semaphore to zero When data are placed into the queue the FULL semaphore is decremented and the EMPTY semaphore incremented The opposite occurs for removal of data from the queuc Thus if a read is attempted on an empty queue the EMPTY semaphore with a value of zero will block Conversely a full queue with a FULL semaphore value of zero will block if an attempt is made to write to it The semaphore numbers for the FULL and EMPTY semaphores are placed in the pipe fields PIPE_FULLS and PIPE_EMTYS respectively v Two pointers are established to indicate the front and rear of the queue The positions of the head and tail of the queue are given by the PIPE_FPOSN and PIPE_RPOSN fields respectively These are both initialised to 32 to indicate an empty queue vi Two further mutexes are created to protect the reading and writing Workshop ou Distributed Laboratory Instrumentation Systems Al Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt vii ends of the pipe Before a thread can read or write to the pipe the corresponding mutex should by claimed to prevent other threads from gaining access Finally the mutex lock has an UP performe
153. ory address with each of these stabs iii The linker then further modifies the addresses and adds the addresses and names of the library functions which have been linked in It pro duces an unique output file in standard ELF format This ELF file contains the executable program in two forms one to be used by the debugger db09 when running the m6809 simulator and one which db09 can download via a serial connection to the hardware board In addi tion the ELF file contains all information needed for symbolic debug ging of the user compiled program s At present this information is not available for library functions these can only be debugged using the assembly level facilities iv The debugger db09 was extended considerably to acecpt the ELF file and to make use of the information contained in it It can run in two modes e The first uses the built in simulator of the 6809 instruction set whereas the second Workshop on Distributed Laboratory Instrumentation Systems 80 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6869 Microprocessor board C Verkerk and A J Wetherilt downloads the executable program into the hardware board and then maintains a dialog with the ICTPmon monitor resident on the board v The startup routine crt0 s and the compiler steering script ec09 were modified to reflect the newly created situation vi The libraries lib Odb09 a and liblOreal a were
154. pe 34 Pipe Close a pipe for writing OSROpenPipe 35 Pipe Open a pipe for reading OSRClosePipe 36 Pipe Close a pipe for reading OSWritePipe Pipe Write to an open pipe OSReadPipe Pipe Read from an open pipe Table 2 14 Summary of interprocess communication system calls 2 7 4 Summary of interprocess communication system calls This summary is given in Table 2 14 page 43 2 8 Device Drivers Device drivers are commonly provided within an operating system so that the use of hardware can be simplified and at the same time to provide a common interface for input and output The use of most hardware devices is complicated and involves actions at the assembly language level that should be hidden from most user applications at the expense of efficiency of code RInOS implements device drivers for this reason and provides a set of com mon functions for all of the devices on the JCTP0O9 board The device driver interface is through the second 6809 software interrupt SWJ2 and calls to a driver at the assembly language level proceed as swi2 byte device_number Workshop on Distributed Laboratory Instrumentation Systems 43 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt This is an identical format to the system call interface the only difference being that whereas the software intcrrupt used for system calls masks the interrupts when issued
155. places them into a holding buffer supplied by the user The buffer is filled until the device driver encounters a Carriage return Line feed pair in the input stream These bytes are discarded and a terminating null or zero Workshop on Distributed Laboratory Instrumentation Systems 46 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherili byte is added Multiple transinission is similar Bytes from a user supplied buffer are transmitted until a terminating null byte is encounterd A CR LF pair is then added and transmission halted The IOCTL function allows the user to manipulate directly the registers of the hardware device The format is the same for each driver and is given in table 2 17 pag 47 Details of the device to programme must be known if the IOCTL function is to be used effectively Register Description high X Specifies Read 1 or Write 0 low X Offset of register to be controlled from hardware base B Byte to write to register A Byte read from register Table 2 17 IOCTL usage 2 8 3 The DAC driver The DAC driver is simple in comparison to all other drivers The value to write is passed to the driver and written directly to the appropriate data reg ister There is NO interrupt handler as the DAC does not raise an interrupt 2 8 4 The ADC driver The ADC driver is slightly more complicated tha
156. position independent otherwise the code must have the absolute value 0x2200 as origin of exccutable code as this is the start of free paged memory available to the user Only one absolute module can be downloaded to the ICTP09 beard and an error will be generated if a second module is attempted to be downloaded On the contrary as many relocat able modules as desired within the available memory limits 32k per page can be downloaded The system memory manager will automatically handle the creation of all neccessary structures for the process and assign memory Accompanying each downloaded module is a 0x100 byte area situated imme diately before the start of the memory reserved for the process If desired a set of arguments from the command line can be sent with the code to be downloaded RInOs will make these arguments available to the application on startup Once downloaded an application program can make use of the kernel functions by issuing a software interrupt In assembler language this takes the form Workshop on Distributed Laboratory Instrumentation Sysiems 17 Abdus Salam ICTP Trieste Novembcr 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt swi byte function number Before issuing the software interrupt most system calls require that var ious registers of the 6809 be loaded with parameters that define the action to be performed For example The OSThreadCreate syst
157. ppen to know more about the function s arguments you may now issue the A command indicating the type of each argument preceeded by the type of the function s return value For instance you may happen to know that in a particular situation the function printf receives 3 arguments a string the format an integer and another string which are the things to be printed It will return an integer To see the values of the arguments in this case type A dsds the first d is for the return value sds for the arguments in their natural order After you have reached a breakpoint you can inspect also values of vari ables and do a few other things See further down To leave a breakpoint and resume execution three commands are available G will restart execution at full speed and run upto the end of the program or untill another breakpoint is hit c 5 Workshop on Distributed Laboratory Instrumentation Systems 83 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt or any other decimal number will continue for 5 in this case lines of C code and then stop It will stop before if it gets to a closing brace In other words it will not allow you to get out of the present context block without noticing The third command you may use to leave a breakpoint is N This command will advance one line in your C program and will follow
158. priority Arguments A New priority X Thread identifier 0 current thread Returns Nothing On crror A ERR BADTASK ERR_BADINST Blocking Will not block Get a pointer to the current TCB Arguments Nothing Returns X Address of current thread TCB On crror Nothing Blocking Will not block Set current thread attribute Arguments A Valuc to set mask bits B Mask for attribute Returns Nothing On error Nothing Blocking Will not block Continued on next page OS AtExit 25 OSSet Priority 17 OSGet TaskInfo 26 OSSetThreadAttr 27 Table C 1 System calls Continued Workshop on Distributed Laboratory Instrumentation Systems 101 Abdus Salam ICTP Triesic November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Continued from previous page Symbolic name Description and behaviour OSCancelPoint 28 Cancel current thread if cancellation pending This function does not return if cancellation is successful Arguments Nothing Returns Nothing On crror Nothing Blocking Will not block OSGetLastError 29 Get last error code of current thread Arguments Nothing Returns B Last error code of current thread Onerror Nothing Blocking Will not block OSSleep 18 Put thread to sleep for x clock ticks Arguments X Number of clock ticks to sleep zero indefi
159. pthread_t thread2 void pthread_exit int termval int pthread_join pthreadt thread int termval int pthread_join pthreadt thread int termval int pthread_kill pthread t thread int sig int pthread_mutex_destroy pthread_mutex_t mutex int pthread_mutex_init pthread_mutex_t mutex const pthread zuutexattr_t attr int pthread_mutex_lock pthread_mutex_t mutex int pthread_mutex_trylock pthread_tmutcx_t mutex int pthread_mutex_unlock pthread_mutex t mutex int pthread_once pthread_once_t once_block void init routine void pthread_t pthread_self void int pthread_setcancelstate int state int oldstate int pthread_setcanceltype int type int oldtype int pthread_testcancel void int sched_get_priority_max int policy int sched _get_priority_ min int policy Table 3 12 Function prototypes for libpthread a 3 5 The overall steering script cc09 In order to instruct xgcc to pass the necessary options to the assembler and linker the user should type a command line which with some bad luck may look as follows Workshop on Distributed Laboratory Instrumentation Systems 69 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt xgcc v Wall I usr local micros m6809 include o prog s19 Wa glxs L usr local micros m6809 lib lgcc lc Ilcreal 1I0real lmath0O9 Wl msx W1 b_CODE 0x2100 fusr local
160. r at address 0x108 points directly at the null thread without any other thread in the chain This meaus that the main thread has terminated were it still alive it would be linked into the priority list That the main thread has indeed finished can also be seen from the value of its status field at offset 5 into its TCB address 0x15d This has the value OxcO indicating a suspended zombie thread that can never be removed If the attribute bits had been set to allow the thread to be detached Detach state ON the thread would have been killed outright The thread terminated normally and returned a zero value according to the EXITSTS and EXITCODE fields at offsets into the TCB of 17 and 18 respectively Workshop on Distributed Laboratory Instrumentation Systems 126 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix I System calls from C Function Prototype Corresponding From libereal a System Call char at_exit void exit function int argument OSAtExit char calloc_mem int tid int size OSCAllocMem 20 void cancel_point void OSCancclPoint 28 int cfree mem lt int size void addr OSCFreeMem 21 int create_pipe int width OSCreatePipe 31 int create_sem int sem_typc int init_valuc OSCreateSem 1 int down_hybrid struct sem struct mutex OSDownHybrid 43 int down_sem int sem num OSDownSem 3 int down_user_sem struct user_sem OSDownUserSem 40 int free_sem int sem_mim
161. re intended mainly for teaching purposes can be justified on the grounds of its superior instruction set and clarity of use The 6809 arguably still has the best instruction set of any 8 bit microprocessor or microcontroller and is ideally suited for the current purpose Development tools are widely and freely available at many sites on the Internet which is a great advantage for any device Throughout the design stage stress has always been laid on those areas that will allow the various aspects of microprocessor teaching to be empha sised For this reason two identical serial communications ports have been provided These allow communications drivers to be debugged easily using one port connected via the monitor to the host machine and the second to the hardware application For both ports the baud rate can be set by changing jumper JP2 If faster rates are required the ACIAs at 0xA020 and 0xA030 Figure 2 1 must be configured so that the clock is divided by 1 rather than 16 and the jumpers adjusted accordingly Communication uses only the TxD RxD and ground return lines of the RS232 9 pin ports For interconnection between the board and a host PC null modem cables must be used The 6840 PTM provides 3 timer channels The first is attached to the NMI line and is used by the monitor for tracing through code and the second is used for the system clock by the kernel It issues a clock interrupt on the IRQ line at 10 ms intervals The third clock
162. re2 frdiv getfpac1 getfpac2 intfrac pshfpac2 pulfpac2 putfpacl1 putfpac2 retnmbr sint2flt float dest int src uflt2int umult fitcmp float srel float src2 Converts ASCII representation of floating number into IEEE format in address loe Convert float at sre to a string at dest Internal use only Add float srcl to sre2 and store result in dest Compare two floating point numbers Divide float at srel by Hoat in src2 put result in dest Multiply float at srcl by float in sre2 put result in dest Internal use only Subtract float at sre from float in sre2 put result in dest Emulates the FDIV instruction of 68HC11 Internal use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Internal unconventional use only Convert signed int in src into Hoat in dest Internal use only Internal use only Table 3 11 Functions in libmath09 a for internal use only Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam ICTP Trieste November 26 December 21 2001 68 Software for the 6809 Microprocessor
163. read at offset zero of TCB as 0x158 which in turn points at 0x130 which is null The memory allocated to the new task can also be examined Workshop on Distributed Laboratory Instrumentation Systems 123 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Welherilt gt d 2000 20 0 1 2 3 4 5 6 7 8 9 A BC DE F 2000 00 00 02 02 02 02 02 02 02 02 02 02 02 02 02 02 2010 02 02 02 02 02 02 02 02 02 02 FF FF FF FF FF FF sind Sones Gace gt From the TCB we can find the code segment the stack segment and the stack length at offsets 6 0x15e 8 0x160 and 10 0x162 respectively These show that the code segment starts at address 0x2200 and the stack segment starts at 0x2a00 with a length of 0x300 bytes in agreement with the values seen in the memory allocation table in which the physical address 0x2a00 is represented by the block at location 0x2014 The 0x100 bytes starting at 0x2100 address 0x2002 in the memory allocation table is the process prefix segment which contains the following gt d 2100 20 0 1 2 3 4 OB 6 Oo SB Sek Ber DL ES IF 2100 05 BF 00 FF 4D 61 72 79 20 68 61 64 20 61 20 6C Mary had a 1 2110 69 74 74 6C 65 20 6C 61 6D 62 00 50 00 12 00 40 ittle lamb P gt As expected the number of arguments passed at the command line and stored in location 0x2100 is 5 The argument string can clearly be seen starting at l
164. recommendations and tips 4 1 Things to watch when writing a C pro gram Writing a program in C which is intended to run on the ICTPO09 board is essentially the same as writing a program for any other machine You may work in your home directory or any other directory for which you have write and execute permissions There are only a few points to observe In what follows we assume that you make use of cc09 and do not type separate commands to the compiler assembler and linker i Put comments in your program It will be useful for you and it will make an instructor s life much easier In a preamble explain what the program is supposed to do It is a good idea to use a Makefile You then have to think only once about options dependencies cte After you have gone through this bit of extra work you then can sit back and just type make You should include the following two files in your source syscalls h and ICTP_10 h The second is not required if the LCD display is the only device on the ICTP09 board that you use You should declare function prototypes of the functions you define otherwise xgcc will complain Prototypes of the library funnctions have been defined in syscalls h To avoid further complaints by xgcc cast the return value of a function to void if you are not using it 77 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt v vi vii xi A few variables should b
165. rkshop on Distributed Laboratory Instrumentalion Systerns 137 Abdus Salam IC TP Triesic November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherili 0111 DD 00 154 std ZD1 second part of movhi REG 0113 DC 00 155 ldd 2D1 first part of movhi for REG 0115 ED 22 156 std 2 y second part of movhi case PLUS register 1 0117 16 00 03 157 lbra Lit 0114 17 06 00 158 lbsr _printerr CALL V VOIDmede printerr pcr 0 bytes O11D 159 Lii 011B EC 22 160 ld d 2 y first part of movhi case PLUS register 1 Q11F 34 06 161 pshs d second part of movhi case PRE_DEC 0121 30 8C CF 162 leax LO2 pcr address of symbol gt X 0124 1F i0 163 tfr x d 1st part of movhi for symbol or label 0126 DD 00 164 std ZD0 second part of movhi REG 0128 17 00 00 165 lbsr _prntf CALL R ZD0 _prntf 2 bytes 012B 32 62 166 leas 2 8 addhi Ris R s 2 012D 16 FF D2 167 lbra L 0130 168 L9 0130 16 00 00 169 lbra L7 0133 170 L7 171 5 EPILGGUE 0133 35 10 172 puls x Pulling register ZD1 0135 9F 00 173 stx 2D1 0137 35 20 174 pula y Restore stack frame 0139 32 62 175 leas 2 3 deallocate 2 bytes auto variables 0138 39 176 rts return from function fs a a aa aa a aa a 178 END EPILOGUE for child1 179 ana ae oe ee ee E 180 globl _create_child 013C 181 _create child 182 fp prot rer erren rr re scene ceeses scenes 183 PROLOGUE for create child LBA Gag
166. rocessor has the following addressing modes Absolute the address given in the instruction is an absolute address Motorola calls this addressing mode extended Immediate the operand is found in the location immediately after the instruction Direct the contents of the DP register are concatenated with the 8 bit address associated with the instruction to form a 16 bit address Indexed one of the four Index or Stack Pointer Registers is used to form the effective address This can be in one of the following ways a constant offset is added to the contents of the Index register ldd 75 x or leay 2 y the contents of a register are added to the contents of the index register to form the effective address sta b u post inerement and pre decrement either by 1 or by 2 inc x or std y relative to the program counter A constant is added to the present contents of ihe program counter to form the effective address ldd here pcr or stb there pcr Indirect addressing falls also in this category of indexed address 17 ing e Inherent the instruction does not need an address generally because it operates directly on a register When an instruction needs an address all these addressing modes can be used without exception The instruction set contains e Load and Store instructions which are valid for all 8 and 16 bit regis ters except CC and DP ldd here stx s ete Add and Subtract i
167. s The PIA is the only device which can be opened in different modes to open devices other than the PIA mode should be zero These low level functions are used by the higher level IO functions in libc a At startup the PEA is opened for writing to the LCD display which can display 16 characters A program that does not use any of the other devices on the board can therefore use printf putchar ete without any preliminary In a sense the LCD display is the stdout device Note that when a program is run under db09 with the simulator the usual output devices are not available The functions in 1ibI0 a detect this situation and accept input from the keyboard and redirect output intended for the LCD display to the screen Workshop on Distributed Laboratory Instrumentation Systems 65 Abdus Salam ICTP Tricsie November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Function Purpose Trigonometric functions float sinf float x float cosf float x float tanf float x float atanf float z float asinf float t float acosf float x float deg2rad float x float rad2deg float rt float logf float z float log10f float x float expf float x float ten2xf float x float powf float x float y float sqrtf float float polynom float z float coeff Miscellaneous functions float getpi void float gete void int
168. s the error number is stored in the thread specific variable errno In plain English this means that each thread has its own errno variable located in the direct page allocated to the thread The function printerr will output this error number on the LCD display on the display board This mechanism for reporting errors allows the user to write C code as follows if tid thread_create int prio struct amp tpt lt 0 printerrQ Another library libTO a acts as the bridge between a C program and the input output drivers in RInOS Workshop on Distributed Laboratory Instrumentation Systems 62 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Abdus Salam ICTP Triesie November 26 December 21 2001 Function Prototype Corresponding From libcreal a System Call char at_exit void exit function int argument OSAtExit 25 char calloc_mem int tid int size OSCAllocMem 20 void cancel_point void P OSCancelPoint 28 int cfree_memi int size void addr OSCFreeMem 21 int create_pipe int width OSCreatePipe 31 int create sem int sem type int init value OSCreateSem 1 int down hybrid struct sem struct mutex OSDownHybrid 43 int down_sem int sem_num OSDownSem 3 int down_user_sem struct user_sem OSDownUserSem 40 int free_sem int sem_num OSFreeSem 2 int free_user_sem struct user sem
169. s which is only barely more than the time required to handle a straight forward interrupt request For times longer than this timer channel 3 can be used Workshop on Distributed Laboratory Instrumentation Systems 15 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 2 3 An overview of RInOS Strictly speaking RInOS comprises the kernel which holds the system dis patcher and interrupt handler together with functions for thread and semapho re management and interprocess communications The memory manage ment and default device drivers rely directly on the kernel code and bypass the regular system call mechanisms so that it is difficult to separate them from the kernel proper In addition the modified ASSISTO9 also draws on a number of kernel functions for its operation It is possible to use the ker nel without installing the monitor but then all downloading and debugging facilities are lost This would be the situation for a standalone version with user processes or threads running in ROM RInO S consists of the following modules System initialisation System dispatcher Hardware interrupt handler Process Thread management Semaphore management Signal and message management Pipe management Memory management Device drivers Monitor services Memory on the ICTP09 board is organised into three separate regions ROM 0xc000 0xffff
170. s direct creation of a thread in the manner described shortly The second function OSThreadInstall allows a function to register itself with the system and to start RInOS This is useful for running applications in ROM which are not downloaded by the monitor The steps in thread creation are i A TPT is filled out the priority level set in the 6809 A register and the relevant function either create or install called ii A free TCB is found If one is not available an error is returned to the calling thread iii A context is created using values in the TPT iv A semaphore is created for the thread s mailbox v The PARENT field is filled in using the system variables ctskinst and ctskpid which concatenated together form the parent s full pid The TCB fields EXITSTS EXITCODE EXITFNC and EFARG which refer to the exit status the return code from the thread an optional termination function and the argument to the function respectively are set to zero to indicate default values The ERRORSTS field which records the error status of the last system call made by the thread is similarly set to zero indicating that an crror has not yet occurred vi The fields TIMRCNT and TIMRLNK which are used by the system clock to determine when a thread should be woken if it is asleep are zeroed as a thread starts its life in a runnable state vii The thread is linked into the priority list behind at lower priority any tas
171. s is blocked The UP operation is the reverse of this sequence and is called by a process when it has finished with a resource In an UP operation if there are any processes waiting on the semaphore one or more depending on the semaphore type of these processes is sclected as the next owner of the resource and becomes unblocked If no process is waiting on the semaphore its value is usually incremented up to its maximum allowed level Mutexes are used whenever two or more threads access a common resource and the state of this resource can be changed by one of the threads For instance one thread could write to a buffer which can be read by other threads Before a thread accesses the buffer it must do a DOWN on a mutex When the thread has finished using the buffer it must release it by performing an UP operation on the mutex It must be stressed that successful use of semaphores relics on all processes cooperating together A single anarchistic process easily can cause the whole system to fail by holding onto resources it no longer needs Event semaphores are frequently used to signal the occurrence of specific actions or events Any process interested in receiving notification that an event has occurred can perform a DOWN on an Event semaphore and wait for its release Event semaphores wake all processes waiting on them the first to run being the one with the highest priority It is common to find them being used to wait for hardware triggers
172. s memory by db09 The C source code can thus be used unchanged by db09 s As an extra bonus db09 allows the user to debug the code of the kernel itself When db09 is running it can be interrupted at any time by hitting the escape key This can be changed with the option e hexnumber This facility is extremely useful when a program has gone out of control Hitting escape brings you back into the command loop of db09 so the registers can be displayed memory inspected etc This will in general give precious clues as to what happened Both debuggers have their strengths and weaknesses The ICTPmon dce bugger has the advantage that it runs on the real hardware System calls and IQ calls are executed trucly However the necessity to remove a jumper to cut off clock interrupts makes single stepping awkward and makes system calls to mssleep and wake unusable The db09 cross debugger has a number of advantages as described above but debugging of IO routines is practically excluded unless the user is ready for some breath taking acrobatics The db09 cross debugger when used with the option s has an addi tional advantage it contains a number of commands specific for the RIn0S kernel These commands are of limited interest to an applications pro grammer but they are very useful for developpers They are not included in Table 3 14 page 74 The disassembler may be of more general interest and the command to invoke it is included in the Tabl
173. s the value of zero In this way when a process waits for the next event in a repetitive sequence the occurrence of a previous event does not affect whether or not it blocks Somewhat more rarely encountered but nonetheless of use is the situation Workshop on Distributed Laboratory Instrumentation Systems 32 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Weiherilt where a single event needs to be indicated after which the semaphore will be disposed of RInOS uses such semaphores internally for signal and message handling Semaphore type Value Description MUTEX 0x01 Mutex semaphore COUNT 0x02 Counting semaphore EVENT 0x04 Event counter REVENT OxOc Single event reset after use SEVENT 0x84 Single event freed after use Table 2 8 Semaphore type values During semaphore creation the SEMVAL field of the semaphore should be filled with the desired initial value This may be any value up to a limit of 255 for Counting semaphores but only either zero or one for Mutexes and only zero for Events All other fields in the semaphore should be sct to zero 2 5 2 UP and DOWN operations The DOWN operation on semaphores must guarantee that it cannot be in terrupted by any other process or event It is therefore carried out within the kernel with all interrupts masked during the critical sections The process of performing a DOW
174. se of these functions will reduce the overall program size by close to 2000 0x800 bytes Secondly there are the functions that throw a bridge between a C pro gram and RInOS These functions are collected in libcreal a The pro totypes of the functions in libcreal a are listed in Table 3 6 page 63 and 64 They all arc wrappers providing the necessary interface between a function call in a C program and the sequence of machine instructions needed to gain access to the OS calls in RInOS With very few exceptions these functions return the number 1 in case an error occurred Otherwise they return zero or a positive value which can be cither an integer or a pointer Some do not return at all for obvious reasons The names of the wrapper functions are closely related to the corre sponding system calls For instance RInOS OSCreateThread becomes create_thread for the C programmer OSResetUserESem be comes reset_user_esem etc The only exception is OSSleep which has become mssleep int n The reason is that sleep int n exists in the normal C library libc a where the argument n in dicatcs following the standard the time to sleep in seconds sleep calls in turn mssleep after having multiplied its argument by hundred mssleep int n takes as argument the time in number of clock ticks of 10 milliseconds each mssleep n can be called directly by a user If during a call to one of these functions an error occur
175. serial driver ACIA1 and ACIA2 2 8 3 The DAC driver ot acc ts a eee a he ea Read Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 2 9 3 The 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 2 8 4 The ADC driver sf 4 3 9 8 wb ae 4 a aa 2 8 5 The PIA driver aooaa aaa esa en kw dew 2 8 6 Installation of a new driver aooaa aaa aa The modified ASSISTO9 monitor aooaa aaa 2 9 1 ASSISTO9 commands aaao aa a 2 9 2 The code downloader oaoa a a 2 9 3 Debugging with the modified ASSISTO9 monitor Cross compilation Chain The Cross compiler 20 22 as atscH ee kee gh Fa G Assembler and Linker ties amp Beedle ee The startup routine crt0 0o 02 2 ate Ne US on Program Libraries wee 4 2 oe Bo Bo a a a meh 8 The overall steering script ccCO9 2 ee ee Downloading the program 4 6 2 oe as ae ese DEW REISS sie Lan Ao Ann Coe i et be Ak DO ees Auxilliary programs 2 9S Or a eae hee a eee 4 Putting it all into practice 4 1 4 2 4 3 4 4 4 5 Things to watch when writing a C program New features added in 1999 0 2 ee a Downloading and running your program Debugging your program speak ey woe eee A eS Symbolic Debugging Commands 4 5 1 Creating a log of your debugging session 4 5 2 Setting and using breakpoints 4 5 3 Removing a breakpoint 4 5 4 Executing your program line by
176. sult of some of the functions above may fall outside the range of floating point numbers that can be represented in the 32 bit IEEE format If this happens the error ERANGE is detected and either the largest representable value or zero is returned by the function depending on the error detected overflow or underflow respectively In all cases a more explicit indication of the error can be found by inspection of the location errno in the direct page at offset Ox2e For details of the error numbers and their meaning the reader is invited to consult the file usr local micros m6809 include math09 h v Then there are libraries required by the compiler itself to complete its code gencration These are libgec a and a large part of libmath09 a The first contains those arithmetic operations on integers which are not implemented in the hardware of the 6809 microprocessor The sec ond contains the functions to emulate floating point operations which were not shown in Table 3 9 page 66 These libraries should later be combined into one The calling convention and the way the result is returned are not standard and therefore these functions are of limited interest to the user For completeness the contents of these two librarics are shown in Table 3 10 page 68 and Table 3 11 page 68 The reader should be aware that the functions shown in those tables were mainly written for use by the compiler and for internal use by the floating point package itself
177. swi2 does not Both software interrupts are vectored through the interrupt vector table at the end of ROM and find their way through the monitor into the relevant interrupt handler in the RInOS kernel On receipt of a device software interrupt the handler performs similar actions to the function call dispatcher i The device_number byte is read and the stacked return address incre mented to point at the byte following the device number If the de vice_number byte is larger than the maximum allowed value an error is generated ii The devicenumber is used to calculate the entry for this device in the system interrupt service table This table is copied from ROM to RAM during initialisation and has default entries placed into each of its fields The structure of an entry in the system interrupt service table is shown in Table 2 15 page 44 The interrupt service table contains the addresses of functions and data structures used by both the hardware interrupts and the device drivers in their operation The software in terrupt handler copies the address of the entry in the interrupt service table and the contents of the HARDWARE_ADDR and DATA_ADDR fields into pointer registers of the 6809 and makes a jump to the address given in the DRIVER_ADDR field Field Offset Description ISR_ADDR 0 Interrupt service handler DRIVER_ADDR 2 Device driver address HARDWARE_ADDR 4 Hardware base address DATA ADDR 6 Device scratch data area DDINS
178. t and takes Argument s 007 a pointer to a string 007 as argument db09 gt G We do G to execute atoi Breakpoint reached when returning from atoi return value 7 db09 gt G We saw that atoi returns the integer 7 Breakpoint reached at entry of function prntf called from line 14 If number and type of arguments known use A command Workshop on Distributed Laboratory Instrumentation Systems 155 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherili Guessed ist argument 8964 0x2304 Correct address of format There may be more arguments on the stack Stack Pointer 3968 At 3968 return address then address of string 007 210E and value of k 0007 0O 1i 2 3 4 5 678 9 A BCD E F 3960 23 04 39 72 3A 00 23 C5 23 A7 21 OE 00 O7 00 04 9r 3970 21 84 21 88 00 03 00 07 22 97 21 80 C5 D6 21 00 1 Welle gt db09 gt A dssd We know arguments and return of prntf Use A Argument s s s d 4x n 007 7 Here are the 3 arguments db09 gt G Do G Return value of prntf follows Breakpoint reached when returning from prntf return value 0 db09 gt D k Inspect value of k again No local symbol k in present context We are out of bounds db09 gt N Now we do an N command again Line 15 file pt4 c To
179. t i inf db09 gt Clock Interrupts have been disabled db09 gt Watchpoint 0 at address A030 modified from D101 PC OP A B X Y U 5 DP EFHINZVC Cc D103 8601 03 OA 4030 115D 1EBO 1EBO 00 11010000 DO Watchpoint 0 at address A030 modified from D10F PC OP A B X Y U 5 DP EFHINZYC CC D111 6D48 91 OA 4030 115D 1EBO 1EBO 00 11011000 D8 BreakPoint Reached PC UP A B X Y U 8 DP EFHINZVC CC C006 1322 01 00 11DA 1144 10E0 1ECO 00 01000000 40 db09 gt Clock Interrupts have been enabled db09 gt N Address Stop 0 A030 0 dbO9 gt N Address Skip Hit 000 C006 000001 000000 db09 gt db09 gt g we don t set breakpoints now Hello World IT WORKS NOW 1 Signal 2 hit esc key db0gor see where we are PC OP A B X Y U 5 DP EFHINZVC CC 012E 20FE 00 00 0000 0000 0000 1EFC 00 00000000 00 In the NULL THREAD db09 gt x Everything is fine so stop rinus katje romtest We managed to get our super Hello World program to work correctly Workshop on Distributed Laboratory Instrumentation Systems 151 Abdus Salam ICTP Trieste November 26 December 21 2001 Appendix N An example on board symbolic debugging session For this example of an on board symbolic debugging session using db09 we have chosen a short program pt4 c which illustrates the passing of argu ments to the main program In this example the use of nearly all commands available for symbolic debug
180. t is properly initialised The mutex lock is created first and is initialised to zero The interrupts are then unmasked as the critical section has been performed Now if a thread tries to claim the pipe by performing a DOWN on the lock mutex it will block until the mutex is released by the pipe creation function Workshop on Distributed Laboratory Instrumentation Systems 40 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherill Field Offset Size Description PIPE_USED 0 Pipe in use flag 1 if free PIPE WDTH 1 Pipe width in bytes PIPE_MEM 2 Pointer to allocated memory PIPE_FRNT 4 Pointer to front of buffer PIPE_REAR 6 Pointer to rear of buffer PIPE_FPOSN 8 Index of front PIPE_RPOSN 9 PIPE_ FULLS 10 PIPE_EMTYS 11 PIPE WMTX 12 PIPE RMTX 13 PIPE LMTX 14 Index of rear Full semaphore Empty semaphore Write semaphore loek Read semaphore loek Pipe resource lock a Table 2 13 Pipe structure offsets iii Memory is now reserved in the Common RAM area to be accessible by all threads The amount of memory reserved is determined by the width of the pipe requested by the calling thread The length of the queue is always 32 bytes long one memory block but the width can be up to 255 bytes An error will be generated if a pipe of zero width is requested The pipe width and the address of the allocated memory are st
181. te November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt 4 5 9 Starting and exiting The X command starts the kernel running and launches the user program To exit from db09 type exit when the db09 gt gt shows CAVEAT The development of the symbolic debugging facility is not yet entirely fin ished You may therefore have some surprises We apologize and we will be interested to know about the possible bugs you may detect Workshop on Distributed Laboratory Instrumentation Systems 89 Abdus Salam ICTP Trieste November 26 December 21 2001 Chapter 5 Bibliography I Andrew 5 Tanenbaum Modern Operating Systems Prentice Hall International 1987 The ASSISTO9 monitor 6809 Programming manual Motorola Ine Jean J Labrosse p COS the Real Time Kernel R amp D Publica tions 1992 The MCX11 Real Time Executive Motorola Inc The RTEMS Real Time Executive Real Time Executive for Multi processor Systems Jan 1996 Available from rtems redstone army mil B Nichols D Buttlar J Farrell Pthreads Programming O Reilly amp Associates Inc 1996 Richard M Stallman Using and Porting GNU CC Free Software Foundation Inc 1993 ISBN 1 882114 35 3 Can be extracted from the gcec info files Documentation for the cross assembler linker can be found in the di rectory usr local micros m6809 doc
182. ten in Position Independent Code The name of the object module or library must be given as argument The program will point at all locations where the code is suspect i e possibly not PIC vi jim2rinus This program in reality a Perl script translates assem bler directives from the format required by one type of assembler jir s into those needed for another rinus It can be found in one of the subdirectories and can be easily adapted for other pairs of assemblers The command line is jim2rinus lt prog asm gt prog s Workshop on Distributed Laboratory Instrumentation Systems 75 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt vii elvn2nin This Perl script translates from 68HC11 assembly source code into m6809 assembly source It is specialized for a certain set of assembler directives but can be adapted for another set It can be found again in one of the subdirectories either as elyn2nin or as 1ito9 The command line is elvn2nin lt progil asm gt progo9 s Workshop on Distributed Laboratory instrumentation Systems 76 Abdus Salam ICTP Trieste November 26 December 21 2001 Chapter 4 Putting it all into practice This chapter will outline the procedure to follow from writing a C program through the compilation and downloading upto debugging it Besides the steps to follow it will contain a few
183. the processes block until a button is pressed or some other event requiring attention occurs 2 5 1 Semaphore creation Under RInQS all three types of semaphore are implemented Space in the kernel is reserved for a total of 256 semaphores referred to as numbered or system semaphores Some 80 of these are used by system processes such Workshop on Distributed Laboratory Instrumentation Systems 31 Abdus Salam ICTP Tricste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt Ficld Offset Size Description SEMTYP 0 1 Semaphore type SEMVAL 1 1 Semaphore value NXTSEM 2 2 j Link to list of threads waiting on this sema SEMOWNER 4 2 Current semaphore owner SEMOLNK 6 2 Link to list of owner s semaphores Table 2 7 Semaphore structure definitions as messages signals and the default device drivers and are created during system initialisation The remainder are available for use by an application program Alternatively RInOS also allows the creation of dynamic or user semaphores using memory owned by the application In this case the appli cation creates the semaphore structure given in Table 2 7 page 32 and uses a pointer to this structure when performing operations on the semaphore The structure is common to both types of semaphore the difference between the two types being that system semaphores all have space reserved dur in
184. these functions do not use the number of the physical device but a logical device number which distinguishes between input and output devices and devices which can do both They are defined in the header file ICTP_I0 h Their denominations are shown in Ta ble 3 8 page 65 ICTP_IQ_ioct1 is an exception to this rule it uses the Workshop on Distributed Laboratory Instrumentation Systems Abdus Salam 1CTP Trieste November 26 December 21 2001 64 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt physical device number For example you open the PIA for writing to the LED array and then you write to the LED array with ICTP_IO_open ICTP_IO_PIA PIA_ICTP_DSPL_LED_MODE ICTP_IO_write ICTP_IO_LED buf size Denomination Description Standard devices ICTP_IO_ACIA1 ACTA equivalent to stdin 0 ICTP_IO_ACIA2 ACTA2 2 ICTP_IO_PIA Devices for input only ICTPIOSWITCHES ICTP IO_ ADC ICTP_IO_ADC1 ICTP_IO_ADC2 Devices for output only ICTP_IO_LCD ICTP_IO_LED ICTP_IO_DAG ICTP_IO_DAC1 ICTP_10_DAC2 Miscellaneous devices ICTP_IO_TIMER3 PIA stdout if LCD panel used 1 Switches on the IO board 3 Channel 1 of ADC on 6809 board 4 ADC Channel 1 4 ADC Channel 2 5 LCD panel on IO board 6 LED array on IO board 7 Channel 1 of DAC on 6809 board 8 8 9 DAC Channel 1 DAC Channel 2 Channel 3 of timer Table 3 8 Denominations of logical device
185. thread it may be wise to reserve a larger stack xgcc will put initialized global variables in the DATA area and unini tialized global variables in the BSS area For an example of a map file see Appendix H The use of global variables is recommended for two reasons Firstly memory for them is allocated independently of space reserved for stacks and direct pages Secondly for multi threaded pro grams they constitute the most convenient way of sharing data Don t forget to use a mutex if necessary Watch xgcc s output to the screen All errors and warnings including those detected by the assembler or linker will be displayed Don t panic if yon get a message which says something like this Inter nal compiler error cci got fatal signal 13 In most cases it means that you did something so strange that even cc1 did not expect it As this message is the last thing cc1 will tell you you are on your own to find where you stumbled Call an instructor if necessary There is a small chance that you found a real bug in the compiler When you have compiled your program as a result of having issued the following command line cc09 v Wall myprog c or a similar one e g without the v and Wall options check that you have obtained an ELF file myprog Workshop on Distributed Laboratory Instrumentation Systems 79 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk
186. tialisation occurs during system initialisation prior lo any memory claims by the system Workshop on Distributed Laboratory Instrumentation Systems 35 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt Function Number Category Description OSCreateSem 1 System Create new system semaphore OSFrecSem 2 System Release existing system semaphore OSDownSem 3 System Perform a down on a given system semaphore OSUpSem 4 System Perform an up on a given system semaphore OSResetESem 5 System Reset an event system semaphore OSFreeUserSem 39 User Release existing user semphore OSDownUserSem 40 User Perform a down on a given user semaphore OSUpUserSem 41 User Perform an up on a given user semaphore OSReset UserESem User Reset an event user semaphore Down on hybrid semaphore mutex combination OSDownHybrid User Table 2 9 Summary of semaphore management system calls 2 6 1 The common memory manager The common memory manager is simpler than the paged memory manager as it has only to deal with 8 kbytes of RAM as opposed to 128 kbytes Its mechanism is straightforward The first 256 bytes of common RAM is reserved for a memory table representing the available 8 kbytes Each byte in the memory table therefore is mapped into 32 bytes of RAM During system initialisation the entire table is filled
187. tion of streams of data between two threads After creation a pipe can be opened for reading by one thread and writing by another The writer places data at one end of the pipe and the reader removes it at the other end RiInOS does not have system calls for shared memory as it is considered a trivial matter to establish properly protected shared memory with the avail able primitives However RInOS does implement message passing signals and pipes for interprocess communication and their usage is discussed in the following sections 2 7 1 Messages A message is a structure with fields for holding data and other valucs and is shown in Table 2 11 page 39 The data to be sent with the message are pointed to by the MSG field of the message structure Each message block is initialised during system initialisation by writing a one in the MSGUSED field to indicate that the message is free All other fields are zeroed When a Message is required the message table is scanned for a free block and if found claimed by writing a zero in its MSGUSED field If one is not found the ERR_BADMSG error is returned to the caller Once a message block has been claimed and the data pointer written into the MSG field it is linked into the Workshop on Distributed Laboratory Instrumentation Systems 38 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board Verkerk and A J Wetherilt F
188. ultiple access A user can test the lock and claim the resource if it is free in a single atomic action Once the test on the lock has started no other process can interrupt the test which then runs to completion If the resource guarded by the semaphore is free its use Workshop on Distributed Laboratory Instrumentation Systems 30 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt is given to the process requesting the resource If the resource is already in use the process will block until the resource becomes free again Semaphores come in three basic varieties The Mutex or binary semapho re the Counting semaphore and the Event semaphore Each type shares a number of common features but has some characteristics of their own A semaphore is always created with an initial value Counting sema phores can take any value between zero and a maximum value whilst Event semaphores and Mutexes are always either zero or one The Mutex is actu ally a special case of the counting semaphore with a maximum value of one Apart from creation and destruction two operations are generally defined for a semaphore UP and DOWN The operation of DOWN on a semaphore tests the current value and if non zero decrements the value and allows the process performing the operation to continuc If the value is already zero it is not decremented further and the calling proces
189. umbers in hexadecimal Undefined symbols are made global All user defined symbols are made global dangerous Create a listing file filename extension lst Create an object file extension o Create a symbol table in a file with ext sym Table 3 2 Options for the assembler as6809 Apart from the usual assembler directives other less familiar ones are accepted area area name arguments follow area name and globl symbol name They convey information to the linker The area directive defines the memory region the following lines belong to The area directive specifies for instance CODE or _DATA or BSS and others The arguments specify if the area should be relocated and if it must be concatenated with other defined areas with the same name The follow directive is used to define the order in which the different areas should appear in memory globl specifies that a symbol is global so that the linker may fill in the correct address for references to it Very recently the assembler has been modified to handle correctly the stabs directive producing information which can be further treated by the linker The other assembler directives may be different from the ones used by other cross assemblers for the 6809 microprocessor A Perl script exists to Workshop on Distributed Laboratory lustrumentation Systems 56 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809
190. up_user_sem struct user_sem void wait_signal int sig num int wake int pid int wr_close_pipe int pipe_id int wr_open_pipe int pipe_id int write_pipe int pipe_id char data int yield void int wait_message int pid char message OSWait Message C Verkerk and A J Wetherilt Corresponding System Call OSThreadInstall 12 OSThread Join 15 OSThreadKill 16 OSUpSem 4 OSUpUserSem 41 OSWaitSignal 10 OSWake 19 OSWClosePipe 34 OSWOpenPipe 33 OSWritcPipe 37 OSYield 0 Table 3 6 Interface Functions for RInOS System Calls Continued Function int ICTP_IO close void int ICTP_IO ioctl int dev int mode int value int ICTP IO_open int dev int mode int ICTP 10_read int dev char buf int n int ICTP_IO_write int dev char buf int n Purpose Closes resets all devices reads writes directly to hard ware registers of physical dev opens logical dew in mode reads n bytes from logical dew into buf returns number of chars read writes n bytes from buf to logical dev returns number of chars written Table 3 7 Functions available in liblO a The functions defined in libIO a are the equivalent of the low level in put output functions of standard C open close read write and ioctl To avoid confusion they are here renamed to ICTP_10_open cte Their prototypes are listed in Table 3 7 page 64 The reader should note that
191. ware for the 6809 Microprocessor board C Verkerk and A J Wetherilt JP 1 Te aga TR io Sa Q ACIA2 FIRG e Lei IRQ ACIAI a FIRQ E NMI MONITOR pe zi IRQ PYM a FIRQ pelle IRQ PIA FIRQ JP 2 Baud Rate ke aari 4800 1200 J 600 Dashed line indicates default jumper scttings Figure 2 3 Jumper Settings for the ICTP09 Board MON signal from timer channel 1 which is jumpered to the NMI line must be jumpered to the IRQ line Jumpering to the FIRQ line without special provision will cause unpredictable results and generally will hang the system Refer to Figure 2 3 for a description of the jumper settings Random access memory is used to provide i a common area for system and application program use and ii an area in which large processes can be loaded These are supplied by a 2764 equivalent 8k RAM at 0x0000 Ox FFF and a 581000 128k RAM at 0x2000 0x9FFF Since the entire address space of the 6809 is only 64k the 128k of the 581000 is divided into 4 pages each of 32k in size by decoding the upper two address lines of the 581000 with an address latch Writing the values 0 3 to the latch will cause the appropriate page to be set It is advised that application processes do not interfere with this register when the kernel is running Two channels each of ADC and DAC are provided No interrupt ca pability is provided for the ADC channels as at a clock rate of one MHz conversion takes less than approximately 25 y
192. was modified to generate Position Independent Code The cross assemblers for the 6809 and 6811 and the cross linker were originally developed by A R Baldwin of Kent State University and enhanced by Ken Hornstein kenh cmf nrl navy mil 91 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt e Part of the C library dibc a was originally written by T E Jones and later adapted to our particular version of the cross compiler Hib math09 a contains adaptations of routines originally written by His cocks e Ulrich Raich made a new GUI for the terminal emulator seyon thereby greatly simplifying the downloading procedure e The original simulator for the 6809 was written by L C Benschop Eindhoven the Netherlands Pablo Santamarina added the debugger part Sergei Borodin added watchpoints during the Regional College of Spring 1997 and finally the simulation of clock interrupts was added in January 1998 In the meantime the program changed name from the original v09 to dbO9 e The simulator of the IO devices the Colombo board and Chu Suan Ang s Display board was written by Ulrich Raich It runs under X11 and visualizes on the screen the effect of IO operations The user program written in C is compiled into cade for the Intel processor of the PC The user program can thus be debugged with xxgdb Workshop on Distributed Laboratory Instrumentation Systems 92 Abdus Salam ICTP Trieste November 26 D
193. ween low and high or low and low 16 if you don t specify high or from the last dump if you write only d Go to location if not specified go to current program counter value Sect memory at addr whith byte addr 1 byte2 etc Set memory range to byte single step Continue for n instructions or forever or until next breakpoint Show all breakpoints Set a breakpoint at addr skip it skip times before it stops Kills a breakpoint at addr Kills all breakpoints Open filename for input read from file until EOF Without params close file Open filename for output send output and keyboard or file input to the file Without parameters close the file Turn on trace mode and optionally set trace file Turn trace off close trace file if open Enable clock interrupts Disable clock interrupts Set a watchpoint at lt addr gt Clear ALL watchpoints Clear watchpoint at lt addr gt Disassemble from addr n instructions Repeat the last command Table 3 14 Commands supported by the Cross debugger dbO09 3 8 Auxillary programs A few auxilliary programs are available in the usr local micros m6809 directory or its subdirectories which may be of use in certain circumstances These programs are Workshop on Distributed Laboratory Instrumentation Systems 74 Abdus Salam ICTP Trieste November 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt i
194. with another N Line 10 file pt4 c And go once more through the loop body kk k gt LCD Display Hello lt db09 gt D k Value of k 2 0x2 k has become 2 db09 gt N Function Call _mulhi3 Breakpoint reached Function Call _prntf Breakpoint reached Line 11 file pt4 c k gt LCD Display 007 lt 44 And LCD now shows the string 007 db09 gt G We go forward with the G command Breakpoint reached at line pt4 c 13 and reach the break at line 13 db09 gt D k We are outside the loop and not yet inside No local symbol k in present context line 13 which explains this db09 gt B prntf We set an extra breakpoint db09 gt B And check N Address Skip Hit 000 2373 000000 000000 line pt4 c 13 001 23F5 000000 000000 atoi 002 23C5 000000 000000 prntf All OK db09 gt G We do G again and hit the break at atoi Breakpoint reached at entry of function atoi called from line 13 If number and type of arguments known use A command Guessed 1st argument 8462 0x210e This guess is correct There may be more arguments on the stack Stack Pointer 396C db09 shows value of the stack pointer At 396C is the return address 2383 Oo i 2 3 4 5 6 7 8 9 AB C D E F 3960 EO 21 QE 3A 21 84 39 72 3A 00 23 F5 23 83 00 04 9r 3970 21 84 21 88 00 03 00 03 22 97 21 80 C5 D6 21 00 Wg Mea Ny db09 gt A ds We know that atoi returns an in
195. with the value Oxff to indicate that each 32 byte block is available for usc Next those arcas used by the system are identified and marked with 0 this being the id of the system Subsequent requests for common memory scan the table looking for blocks large enough to accomodate the request The algorithm is a simple scan using the first such available block rather than the best fit or other search strategies Each block is marked with the id of owner to prevent its use by another process later Deallocation is performed similarly A pointer to the allocated memory together with the size of memory to free are passed to the OSCFreeMem system call The pointer is converted into a memory Workshop on Distributed Laboratory Instrumentation Systems 36 Abdus Salam ICTP Trieste November 26 December 21 2001 Soflware for the 6809 Microprocessor board C Verkerk and A J Wetheri table address and the size of memory into a number of blocks This number of blocks starting with the address in the table are marked with Oxff to indicate that the memory is free If an error occurs the value ERR CALLOC value is returned 2 6 2 The paged memory manager The page register is a latch at address Oxa040 Its function is to switch the various pages of memory as required by the loader and RInOS Each 32 kbyte page starts at address 0x2000 and has its first 256 bytes reserved for use as a memory table In this case one byte of the table is mapped into 1
196. wn loaded to the ICTP09 board can automatically be registered with RINOS and have both memory reserved and a TCB created for it The two cases of ab solute and position independent code are distinguished the la size and l size commands respectively In both cases the size of the code input as a command parameter is used to reserve memory for the process The absolute loader assumes that the code will be sent to address 0x2200 which is the first free address available for executable code under RINOS whereas the loader for position independent code requests a suitable address from the kernel memory manager A thread creation structure is created and the address of the thread s memory is recorded At this stage a stack is cre ated and the starting address and length are placed in the appropriate fields of the structure The stack size defaults to 0x100 bytes but can be set to any desired size via the ss size command As optional parameters both commands accept the priority of the new thread and a list of arguments sep arated by blanks If present the priority is read and placed into the creation structure Similarly the arguments are read individually and copied directly to the process segment prefix 0x100 bytes prior to the start of the process Workshop on Distributed Laboratory Instrumentation Systems 50 Abdus Salam LOTP Trieste Novernber 26 December 21 2001 Software for the 6809 Microprocessor board C Verkerk and A
197. x0 globl main main iij PROLOGUE for main leas 27 5 allocate 27 bytes auto variables pshs y Save stack frame tir s y Set current stack frame 135 Software for the 6809 Microprocessor board C Verkerk and A J Wetherilt 0020 9E 00 30 ldx 2ZD1 0022 34 16 31 pshs x pushed register ZD1 0024 9E 00 32 Ide 2D2 0026 34 10 43 pshs x pushed register ZD2 34 END PROLOGUE 0028 17 00 00 35 lbsr _ _main CALL OIDmode ___main per 0 bytes O02B 1F 20 36 tir y d 002D C3 00 D4 37 addd 4 0030 DD 00 38 std ZD1 addhid y by 4 gt ZD1 G032 1F 20 39 tfr y d 0034 C3 00 04 40 addd 4 6037 DD 00 41 std ZD2 addhi3 y by 4 gt ZD2 6039 CC 00 OB 42 ldd 11 first part of movhi for const 003C 34 06 43 pshs d second part of movhi case PRE_DEC 003E 30 8C BF 44 leax LCO pcr address of symbol gt X 0041 1F 10 45 tfrx d 1st part of movhi for symbol or label 0043 34 06 46 pshs d second part of movhi case PRE_DEC 0045 DC 00 47 ldd 2D2 first part of movhi for REG 0047 DD 06 48 std ZDO second part of movhi REG 0049 17 00 00 49 lbsr _memcpy CALL VOIDmode _memcpy pcr 4 bytes 004C 32 64 50 leas 4 5 addhi Ris Ris 4 004E iF 20 51 tfr y d 0050 3 00 OF 62 addd 15 0053 DD 00 53 std ZD1 addhi3 y by 15 gt ZD1 0055 1F 20 54 tfr y d 0057 C3 00 OF 55 addd 15 6054 DD 00 56 std ZD2 addhi3 y by 15 gt ZD2 005C CC 00 OF 57 ldd 14 first part of movhi for c

Download Pdf Manuals

image

Related Search

Related Contents

- E-POS  Tecumseh AVA2512ZXG Drawing Data    Benchtop Peristaltic Dispenser Peristaltische Schlauchpumpe  Bosch Power Tools 11241EVS Drill User Manual  SC_downloads_files/Single RF User Manual 4.2  Bedienungsanleitung  DrawPlus X5 Manual  Dexford PE 300  Switchvox PBX User Manual  

Copyright © All rights reserved.
Failed to retrieve file