34
1 System Calls (TRAPS) System Calls (TRAPS) and Subroutines and Subroutines Patt and Patel Ch. 9 Patt and Patel Ch. 9

1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

Embed Size (px)

Citation preview

Page 1: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

1

System Calls (TRAPS) and System Calls (TRAPS) and Subroutines Subroutines

Patt and Patel Ch. 9Patt and Patel Ch. 9

Page 2: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

2

System CallsSystem CallsCertain operations require Certain operations require specialized knowledge specialized knowledge and and protectionprotection::

– specific knowledge of I/O device registers and the sequence of operations needed to use them

– I/O resources shared among multiple users/programs; a mistake could affect lots of other users!

Not every programmer knows (or wants to know) Not every programmer knows (or wants to know) this level of detailthis level of detail

Provide Provide service routinesservice routines oror system callssystem calls (part of (part of operating system) to safely and conveniently operating system) to safely and conveniently perform low-level, perform low-level, privilegedprivileged operations operations

Page 3: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

3

System CallSystem Call

1. User program invokes system call.1. User program invokes system call.

2. Operating system code performs 2. Operating system code performs operation.operation.

3. Returns control to user program.3. Returns control to user program.

In LC-3, this is done through the TRAP mechanism.

Page 4: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

4

LC-3 TRAP MechanismLC-3 TRAP Mechanism

1. A set of service routines.1. A set of service routines.

– part of operating system -- routines start at arbitrary addresses(convention is that system code is below x3000)

– up to 256 routines

2. Table of starting addresses.2. Table of starting addresses.

– stored at x0000 through x00FF in memory– called System Control Block in some architectures

3. TRAP instruction.3. TRAP instruction.

– used by program to transfer control to operating system– 8-bit trap vector names one of the 256 service routines

4. A linkage back to the user program.4. A linkage back to the user program.

– want execution to resume immediately after the TRAP instruction

Page 5: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

5

TRAP InstructionTRAP Instruction

•Trap vectorTrap vector

– identifies which system call to invoke– 8-bit index into table of service routine addresses

• in LC-3, this table is stored in memory at 0x0000 – 0x00FF• 8-bit trap vector is zero-extended into 16-bit memory address

•Where to goWhere to go

– lookup starting address from table; place in PC

•How to get backHow to get back

– save address of next instruction (current PC) in R7

Page 6: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

6

TRAPTRAP

NOTE: PC has already been incremented during instruction fetch stage.

Page 7: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

7

RET (JMP R7)RET (JMP R7)

How do we transfer control back to instruction How do we transfer control back to instruction following the TRAP?following the TRAP?

•We saved old PC in R7.We saved old PC in R7.

– JMP R7 gets us back to the user program at the right spot.– LC-3 assembly language lets us use RET (return)

in place of “JMP R7”.

•Must make sure that service routine does not Must make sure that service routine does not change R7, or we won’t know where to return.change R7, or we won’t know where to return.

Page 8: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

8

TRAP Mechanism TRAP Mechanism OperationOperation

1. Lookup starting address.2. Transfer to service routine.3. Return (JMP R7).

Page 9: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

9

Example: Using the TRAP Example: Using the TRAP InstructionInstruction

.ORIG x3000.ORIG x3000

LDLD R2, TERMR2, TERM ; ; Load negative ASCII ‘7’Load negative ASCII ‘7’LDLD R3, ASCIIR3, ASCII ; ; Load ASCII differenceLoad ASCII difference

AGAINAGAIN TRAPTRAP x23 x23 ; ; input characterinput characterADDADD R1, R2, R0R1, R2, R0 ; ; Test for terminateTest for terminateBRzBRz EXITEXIT ; ; Exit if doneExit if doneADDADD R0, R0, R3R0, R0, R3 ; ; Change to lowercaseChange to lowercaseTRAPTRAP x21 x21 ; ; Output to monitor...Output to monitor...BRnzp AGAINBRnzp AGAIN ; ; ... again and again...... again and again...

TERMTERM .FILL.FILL xFFC9 xFFC9 ; ; -‘7’-‘7’ASCIIASCII .FILL.FILL x0020 x0020 ; ; lowercase bitlowercase bitEXITEXIT TRAPTRAP x25 x25 ; ; halthalt

.END.END

Page 10: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

10

Example: Output Service RoutineExample: Output Service Routine

.ORIG x0430.ORIG x0430 ; ; syscall addresssyscall addressSTST R7, SaveR7R7, SaveR7 ; ; save R7 & R1save R7 & R1STST R1, SaveR1R1, SaveR1

; ; ----- Write character----- Write characterTryWriteTryWrite LDILDI R1, CRTSRR1, CRTSR ; ; get statusget status

BRzpBRzp TryWriteTryWrite ; ; look for bit 15 onlook for bit 15 onWriteItWriteIt STISTI R0, CRTDRR0, CRTDR ; ; write charwrite char; ; ----- Return from TRAP----- Return from TRAPReturnReturn LDLD R1, SaveR1R1, SaveR1 ; ; restore R1 & R7restore R1 & R7

LDLD R7, SaveR7R7, SaveR7RETRET ; ; back to userback to user

CRTSRCRTSR .FILL.FILL xF3FCxF3FCCRTDRCRTDR .FILL.FILL xF3FFxF3FFSaveR1SaveR1 .FILL.FILL 00SaveR7SaveR7 .FILL.FILL 00

.END.END

stored in table,location x21

Page 11: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

11

TRAP Routines and their Assembler TRAP Routines and their Assembler NamesNames

vectorvector symbosymboll

routineroutine

x20x20 GETCGETC read a single character (no read a single character (no echo)echo)

x21x21 OUTOUT output a character to the output a character to the monitormonitor

x22x22 PUTSPUTS write a string to the consolewrite a string to the console

x23x23 ININprint prompt to console,read print prompt to console,read and echo character from and echo character from keyboardkeyboard

x25x25 HALTHALT halt the programhalt the program

Page 12: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

12

Saving and Restoring RegistersSaving and Restoring Registers

Must save the value of a register if:Must save the value of a register if:

– Its value will be destroyed by service routine, and– We will need to use the value after that action.

Who saves?Who saves?

– caller of service routine?•knows what it needs later, but may not know

what gets altered by called routine– called service routine?

•knows what it alters, but does not know what will be needed later by calling routine

Page 13: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

13

ExampleExampleLEALEA R3, BinaryR3, BinaryLDLD R6, ASCIIR6, ASCII ; char->digit template ; char->digit templateLDLD R7, COUNTR7, COUNT ; initialize to 10 ; initialize to 10

AGAINAGAIN TRAPTRAP x23x23 ; Get char ; Get charADDADD R0, R0, R6R0, R0, R6 ; convert to number ; convert to numberSTRSTR R0, R3, #0R0, R3, #0 ; store number ; store numberADDADD R3, R3, #1R3, R3, #1 ; incr pointer ; incr pointerADDADD R7, R7, -1R7, R7, -1 ; decr counter ; decr counterBRpBRp AGAINAGAIN ; more? ; more?BRnzp NEXTBRnzp NEXT

ASCIIASCII .FILL.FILL xFFD0 xFFD0COUNTCOUNT .FILL.FILL #10 #10BinaryBinary .BLKW #10.BLKW #10 What’s wrong with this routine?

What happens to R7?

Page 14: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

14

Saving and Restoring RegistersSaving and Restoring Registers

Called routine -- Called routine -- “callee-save”“callee-save”

– Before start, save any registers that will be altered (unless altered value is desired by calling program!)

– Before return, restore those same registers

Calling routine -- Calling routine -- “caller-save”“caller-save”

– Save registers destroyed by own instructions or by called routines (if known), if values needed later

• save R7 before TRAP• save R0 before TRAP x23 (input character)

– Or avoid using those registers altogether

Values are saved by storing them in memory.Values are saved by storing them in memory.

Page 15: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

15

QuestionQuestion

Can a service routine call another Can a service routine call another service routine?service routine?

If so, is there anything special the If so, is there anything special the calling service routine must do?calling service routine must do?

Page 16: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

16

What about User Code?What about User Code?

Service routines provide three main Service routines provide three main functions:functions:

1. Shield programmers from system-specific details.1. Shield programmers from system-specific details.

2. Write frequently-used code just once.2. Write frequently-used code just once.

3. Protect system resources from malicious/clumsy3. Protect system resources from malicious/clumsy programmers. programmers.

Are there any reasons to provide the same Are there any reasons to provide the same functions for non-system (user) code?functions for non-system (user) code?

Page 17: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

17

SubroutinesSubroutinesA A subroutinesubroutine is a program fragment that: is a program fragment that:

– lives in user space– performs a well-defined task– is invoked (called) by another user program– returns control to the calling program when finished

Like a service routine, but not part of the OSLike a service routine, but not part of the OS– not concerned with protecting hardware resources– no special privilege required

Reasons for subroutines:Reasons for subroutines:– reuse useful (and debugged!) code without having to

keep typing it in– divide task among multiple programmers– use vendor-supplied library of useful routines

Page 18: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

18

JSR InstructionJSR Instruction

Jumps to a location (like a branch but Jumps to a location (like a branch but unconditional), and saves current PC (addr of unconditional), and saves current PC (addr of next instruction) in R7.next instruction) in R7.

– saving the return address is called “linking”– target address is PC-relative (PC + Sext(IR[10:0]))– bit 11 specifies addressing mode

• if =1, PC-relative: target address = PC + Sext(IR[10:0])

• if =0, register: target address = contents of register IR[8:6]

Page 19: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

19

JSRJSR

NOTE: PC has already been incrementedduring instruction fetch stage.

Page 20: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

20

JSRR InstructionJSRR Instruction

Just like JSR, except Register addressing mode.Just like JSR, except Register addressing mode.

– target address is Base Register– bit 11 specifies addressing mode

What important feature does JSRR provide that What important feature does JSRR provide that JSR does not?JSR does not?

Page 21: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

21

JSRRJSRR

NOTE: PC has already been incrementedduring instruction fetch stage.

Page 22: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

22

Returning from a Returning from a SubroutineSubroutine

RET (JMP R7) gets us back to the RET (JMP R7) gets us back to the calling routine.calling routine.

– just like TRAP

Page 23: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

23

Example: Negate the value in R0Example: Negate the value in R0

2sComp2sComp NOTNOT R0, R0R0, R0 ; ; flip bitsflip bitsADDADD R0, R0, #1R0, R0, #1 ; ; add oneadd oneRETRET ; ; return to callerreturn to caller

To call from a program (within 1024 instructions):To call from a program (within 1024 instructions):

; need to compute R4 = R1 - R3; need to compute R4 = R1 - R3ADDADD R0, R3, #0R0, R3, #0 ; ; copy R3 to R0copy R3 to R0JSRJSR 2sComp2sComp ; ; negatenegateADDADD R4, R1, R0R4, R1, R0 ; ; add to R1add to R1......

Note: Caller should save R0 if we’ll need it later!Note: Caller should save R0 if we’ll need it later!

Page 24: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

24

Passing Information to/from Passing Information to/from SubroutinesSubroutines

ArgumentsArguments

– A value passed in to a subroutine is called an argument.– This is a value needed by the subroutine to do its job.– Examples:

• In 2sComp routine, R0 is the number to be negated• In OUT service routine, R0 is the character to be printed.• In PUTS routine, R0 is address of string to be printed.

Return ValuesReturn Values

– A value passed out of a subroutine is called a return value.– This is the value that you called the subroutine to compute.– Examples:

• In 2sComp routine, negated value is returned in R0.• In GETC service routine, character read from the keyboard

is returned in R0.

Page 25: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

25

Using SubroutinesUsing Subroutines

In order to use a subroutine, a programmer must In order to use a subroutine, a programmer must know:know:

– its address (or at least a label that will be bound to its address)

– its function (what does it do?)• NOTE: The programmer does not need to know

how the subroutine works, but what changes are visible in the machine’s state after the routine has run.

– its arguments (where to pass data in, if any)– its return values (where to get computed data, if any)

Page 26: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

26

Saving and Restore RegistersSaving and Restore RegistersSince subroutines are just like service routines,Since subroutines are just like service routines,we also need to save and restore registers, if needed.we also need to save and restore registers, if needed.

Generally use “callee-save” strategy, except for return Generally use “callee-save” strategy, except for return values.values.

– Save anything that the subroutine will alter internallythat shouldn’t be visible when the subroutine returns.

– It’s good practice to restore incoming arguments to their original values (unless overwritten by return value).

RememberRemember: You MUST save R7 if you call any other: You MUST save R7 if you call any othersubroutine or service routine (TRAP).subroutine or service routine (TRAP).

– Otherwise, you won’t be able to return to caller.

Page 27: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

27

ExampleExample(1)(1) Write a subroutine Write a subroutine FirstCharFirstChar to: to:

find the first occurrenceof a particular character (in R0) in a string (pointed to by R1); return pointer to character or to end of string (NULL) in R2.

(2) Use FirstChar to write (2) Use FirstChar to write CountCharCountChar, which:, which:

counts the number of occurrences of a particular character (in R0) in a string (pointed to by R1);return count in R2.

Can write the second subroutine first, without knowing Can write the second subroutine first, without knowing the implementation of FirstChar!the implementation of FirstChar!

Page 28: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

28

CountChar Algorithm (using CountChar Algorithm (using FirstChar)FirstChar)

save regs

call FirstChar

R3 <- M(R2)

R3=0

R1 <- R2 + 1

restoreregs

return

no

yes

save R7,since we’re using JSR

Page 29: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

29

CountChar CountChar ImplementationImplementation

; ; CountChar: subroutine to count occurrences of a charCountChar: subroutine to count occurrences of a charCountCharCountChar

STST R3, CCR3R3, CCR3 ; ; save registerssave registersSTST R4, CCR4R4, CCR4STST R7, CCR7R7, CCR7 ; ; JSR alters R7JSR alters R7STST R1, CCR1R1, CCR1 ; ; save original string ptrsave original string ptrANDAND R4, R4, #0R4, R4, #0 ; ; initialize count to zeroinitialize count to zero

CC1CC1 JSRJSR FirstCharFirstChar ; ; find next occurrence (ptr in R2)find next occurrence (ptr in R2)LDRLDR R3, R2, #0R3, R2, #0 ; ; see if char or nullsee if char or nullBRzBRz CC2CC2 ; ; if null, no more charsif null, no more charsADDADD R4, R4, #1R4, R4, #1 ; ; increment countincrement countADDADD R1, R2, #1R1, R2, #1 ; ; point to next char in stringpoint to next char in stringBRnzpBRnzp CC1CC1

CC2CC2 ADDADD R2, R4, #0R2, R4, #0 ; ; move return val (count) to R2move return val (count) to R2LDLD R3, CCR3R3, CCR3 ; ; restore regsrestore regsLDLD R4, CCR4R4, CCR4LDLD R1, CCR1R1, CCR1LDLD R7, CCR7R7, CCR7RETRET ; ; and returnand return

Page 30: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

30

FirstChar AlgorithmFirstChar Algorithm

save regs

R2 <- R1

R3 <- M(R2)

R3=0

R3=R0

R2 <- R2 + 1

restoreregs

return

no

no

yes

yes

Page 31: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

31

FirstChar ImplementationFirstChar Implementation; ; FirstChar: subroutine to find first occurrence of a charFirstChar: subroutine to find first occurrence of a charFirstCharFirstChar

STST R3, FCR3R3, FCR3 ; ; save registerssave registersSTST R4, FCR4R4, FCR4 ; ; save original charsave original charNOTNOT R4, R0R4, R0 ; ; negate R0 for comparisonsnegate R0 for comparisonsADDADD R4, R4, #1R4, R4, #1ADDADD R2, R1, #0R2, R1, #0 ; ; initialize ptr to beginning of initialize ptr to beginning of

stringstringFC1FC1 LDRLDR R3, R2, #0R3, R2, #0 ; ; read characterread character

BRzBRz FC2FC2 ; ; if null, we’re doneif null, we’re doneADDADD R3, R3, R4R3, R3, R4 ; ; see if matches input charsee if matches input charBRzBRz FC2FC2 ; ; if yes, we’re doneif yes, we’re doneADDADD R2, R2, #1R2, R2, #1 ; ; increment pointerincrement pointerBRnzpBRnzp FC1FC1

FC2FC2 LDLD R3, FCR3R3, FCR3 ; ; restore registersrestore registersLDLD R4, FCR4R4, FCR4 ; ; RETRET ; ; and returnand return

Page 32: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

32

Library RoutinesLibrary Routines

Vendor may provide object files containing useful Vendor may provide object files containing useful subroutinessubroutines

– don’t want to provide source code -- intellectual property– assembler/linker must support EXTERNAL symbols (or starting

address of routine must be supplied to user).......EXTERNAL.EXTERNAL SQRTSQRT

......LDLD R2, SQAddr ; R2, SQAddr ; load SQRT addrload SQRT addrJSRRJSRR R2R2......

SQAddrSQAddr .FILL.FILL SQRT SQRT

Using JSRR, because we don’t know whether SQRT is within 1024 Using JSRR, because we don’t know whether SQRT is within 1024 instructions.instructions.

Page 33: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

33

Questions?Questions?

Page 34: 1 System Calls (TRAPS) and Subroutines Patt and Patel Ch. 9

34