Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE3601 CSE 360: Introduction to Computer Systems Course Notes Bettina Bair

Similar presentations


Presentation on theme: "CSE3601 CSE 360: Introduction to Computer Systems Course Notes Bettina Bair"— Presentation transcript:

1 CSE3601 CSE 360: Introduction to Computer Systems Course Notes Bettina Bair (bbair@cse.osu.edu) http://carmen.osu.edu http://www.cse.ohio-state.edu/~bbair Copyright © 1998-2006 by Rick Parent, Todd Whittaker, Bettina Bair, Pete Ware, Wayne Heym

2 CSE3602 Section Details u MTWF 9:30 & 2:30, DL 305 u Bettina Bair (bbair@cse.osu.edu) u Homepage: –http://www.cse.ohio-state.edu/~bbair u Office: Dreese Labs 493 u Hours: MW 10:30, TF 1:30 –or by appointment u Phone: 292-2565 u Grader: –Hamid Ettefagh (ettefagh.4@osu.edu)ettefagh.4@osu.edu –John Colvin (colvin.68@osu.edu)

3 CSE3603 Topics of Discussion u Course description u Required texts u Policies u Syllabus u Expectations

4 CSE3604 Description: u Introduction to computer architecture at the machine language and assembly language level; assembly language programming and lab.  Prerequisites: CSE 214 or 222 or H222

5 CSE3605 Text: 1. Computer Systems: Architecture, Organization, and Programming, Arthur B. Maccabe, Irwin, 1993. 2. Sparc Architecture, Assembly Language Programming & C, Richard Paul, Prentice Hall – a good reference, if you are interested 3. Class handouts 4. Material online at http://carmen.osu.edu

6 CSE3606 Grading Policy: u An assigned grader will grade all homeworks and labs – your lecturer will grade all exams. u Missed assignments or tests without prior approval will receive a grade of zero. u Reasonable excuses must be given in writing to me one week prior to the due date or test date, at which time the circumstances will be evaluated, and approval granted or rejected. u No late homeworks or labs will be accepted. u Exams are closed book, closed notes, and cover all of the material up to that point.

7 CSE3607 Grading Weights: Homeworks (6)25%as assigned Labs (3)25%as assigned Midterm20%around the 6th week Final30% as indicated in master schedule Grading Scale - to be determined

8 CSE3608 Students with Disabilities u If you need an accommodation based on the impact of a disability, please contact me to arrange an appointment as soon as possible. u Office for Disability Services –verifies the need for accommodations –Helps develop accommodation strategies. u If you have not previously contacted the Office for Disability Services, I encourage you to do so.

9 CSE3609 Academic Misconduct u Academic misconduct is defined as any activity which tends to compromise the academic integrity of the institution, or subvert the educational process. u University policy requires that all cases of suspected academic misconduct be submitted to the Committee for Academic Misconduct for a hearing and evaluation. –Any academic misconduct will be dealt with via the appropriate University authorities.

10 CSE36010 Academic Misconduct u Homework, lab assignments, and exams are to be your own work. u High-level discussion of assignments is encouraged, but the more specific your discussion, the closer you come to cheating. –The policy on collaboration with others is fairly liberal -- but please don't be tempted to test its limits.

11 CSE36011 Academic Misconduct u You may not write or otherwise record any part of your solution to an assignment while someone is helping you. u You may not take a physical or electronic copy of any part of a solution to an assignment from anyone. u You may not give a physical or electronic copy of any part of a solution to an assignment to anyone.

12 CSE36012 Academic Misconduct u You are encouraged to talk with others (especially others in the class) about the design, logic, and implementation of a program. –Do not give anyone or take from anyone written or recorded material –Do write up your own solution without assistance. u Professional ethics: –You may not turn in an assignment solution from a previous quarter's offering of the course

13 CSE36013 Expectations u Read your e-mail u Read, reply to the class discussion group on Carmen u Attend class (it’s correlated to results!) u Complete homeworks and labs on time u Read the assigned pages from the text

14 CSE36014 Can I change my section? u Not until Brutus updates –at the end of the first week –only if there are seats available. u Priority will be given –CSE Majors that are Graduating Seniors –CSE Majors –People who attend class the first week

15 CSE36015 Can I work on assignments from home? u Submission via Carmen “dropbox” u HW: MS Word, PDF, or text format u Labs: –Submitted as text formatted source (*.s) file –Require access to ISEM application t Available thru your CSE account: stdsun.cse.ohio-state.edu –SSH, telnet and file transfer (ftp) protocols are useful –Read more about remote access on Carmen t ISEM may also be available online – where? How? I don’t know.

16 CSE36016 Who do I approach if I have a problem with grading? u For labs and homework, contact your grader first –See me if not resolved u For exams, contact me

17 CSE36017 The Carmen Discussion Group u carmen.osu.edu u It’s a place for students to discuss issues related to course work. u Post any questions you might have. u Use discretion when making a posting. u Look out for important announcements. u Instructors/Graders answer questions whenever they can.

18 CSE36018 Course Objectives u Principles of Computer Organization and Architecture –Basic Machine Representation of Signed Integers, Character Strings, Arrays, Stacks, Records, Linked Lists; u Assembly Language Programming. –Fundamentals of Computer Instruction Set Architectures; –Low Level Algorithms for Data Manipulation and Conversion and Parameter Passing

19 CSE36019 150+ Years of Amazing Computers Sherman, set the WABAC Machine to the year 1822…

20 CSE36020 Babbage’s Difference Engine, 1822 Babbage's difference engine No. 2, finally built in 1991 Could hold 7 numbers of 31 decimal digits Could tabulate 7th degree polynomials

21 CSE36021 Ada Lovelace, the first programmer u Mathematician, Patron u Wrote a program for Babbage’s (theoretical) Analytical Engine to calculate the Bernoulli sequence, in 1843 u In 1979, a contemporary programming language was named Ada in her honour.

22 CSE36022 1890: Hollerith Tabulating System u Census Counter u Hollerith Tabulating System Was A System Of Machines –Punch, –Tabulator –Sorting Box u Hollerith's Business Joined A Firm That Later Became IBM.

23 CSE36023 1943-45: Eniac u Electrical Numerical Integrator And Computer u Built To Compute Ballistics Tables For U.S. Army Artillery During World War II. –1,000 Times Faster Than Any Existing Device. u External Plug Wires Used To Program The Machine u Principal Designers, J. Presper Eckert And John Mauchley u Cost, About $400,000

24 CSE36024 Vacuum Tubes u ENIAC –Used Some 18,000 Vacuum Tubes. –30 Feet By 50 Feet –Weighed 30 Tons The ENIAC was a decimal machine!

25 CSE36025 Programming the Eniac

26 CSE36026 Original Eniac Programmers

27 CSE36027 The Bug u In 1947, engineers found A moth stuck in one of the components. u Taped it in their logbook u Labeled it "first actual case of bug being found."

28 CSE36028 Grace Hopper (1906-1992) u 1953: Invented The Compiler –Translates English Language Instructions Into Language Of The Target Computer –"Lazy" And Hoped That "The Programmer May Return To Being A Mathematician." u Led To The Development Of The Business Language Cobol. u Retired From The U.S. Navy As A Rear Admiral.

29 CSE36029 IAS (1946-1952) u Institute For Advanced Study At Princeton University. u Designed And Directed By John Von Neumann. u Cost: Several Hundred Thousand Dollars. Used externally stored programs that could be loaded and executed.

30 CSE36030 1949: Core Memory u A Small Ring, Or Core, Of Ferrite (A Ferromagnetic Ceramic) Can Be Magnetized In Either Of Two Opposite Directions. u A Core Can Be Used For Storing One Bit Of Information. u For Almost 15 Years, 'Core' Was The Most Important Memory Device. u The Invention Of Core Memory Was A Leap Forward In Cost- effectiveness And Reliability.

31 CSE36031 1950s Assembly Programming Class This would be so much easier with a computer…

32 CSE36032 1965: PDP8 u Programmed Data Processor u 50,000+ Sold u Cost: $18,000. u Speed: 1.5 Micro-second Cycle Time u Primary Memory: 4K –12-bit Word Core Memory u Power: 780 Watts What does cycle time mean?

33 CSE36033 1960s/70s Card Reader Card is pre-printed with FORTRAN field layouts

34 CSE36034 1977: Trs-80 u Radio Shack "Trash-80," u 4K Of Memory u Could Not Handle Lowercase Letters u Only Three Error Messages: –"HOW?" t Whenever The User Tried To Perform An Illegal Function –"What" t When A Syntax Error Occurred –"Sorry" t When The Available Memory Ran Out u Cost Only $400! u Some 55,000 Machines Sold In First Year

35 CSE36035 1979: Vic-20 u Processor Speed: 1.0227 Mhz. u ROM: 16kb u RAM: 5kb (3.5kb User Memory) –Expandable To 32kb. u Screen: 22 Columns By 23 Rows. –Character Dot Matrix: 8 By 8 Or 8 By 16 (User Programmable). –Screen Dot Matrix: 176 By 184 With Up To 16 Colors. u Sound: 3 Voices Plus White Noise. u Media: Tape Drive Bettina’s first PC!

36 CSE36036 1984: Macintosh u Revolutionary Graphical User Interface (GUI). –A Device Called A Mouse –Pictorial Symbols (Icons) On The Screen. –Select Commands, Call Up Files, Start Programs, Etc. u Original Selling Price: $2,495

37 CSE36037 What if you had to build your own computer – from scratch?

38 CSE36038 Course Objectives u Understanding the architecture (how the computer executes assembly language instructions) is the more important aspect of a course at this level. u The fundamental concept to understand is that everything in the computer is represented by ones and zeros (by electric current flowing or not flowing at a specific place, or by something being magnetized one direction or the other, etc.).

39 CSE36039 Course Objectives u At the lowest level, this course will cover various binary formats of assembly language instructions and various ways in which data can be represented using ones and zeros and how these can be organized into a program. u At high levels, assembly language programming techniques will be studied and a specific assembly language will be used to illustrate these techniques.

40 CSE36040 Homework #0-0 u Log into Carmen u See if you can find the following: –Contact information for your instructor. –Course policy on late assignments –Course notes (slides) –Reading assignment for the second class-meeting –Dropbox and deadline for first homework –Story of Mel, A Real Progammer in the discussion group

41 CSE36041 Homework #0-1 u Purchase the textbook written by Maccabe. u Read the assigned material for the week u Pledge to do the reading assignment before each class meeting.

42 CSE36042 Homework #0-10 u Login to your CS unix account, on stdsun.cse.ohio- state.edu. u Your default password is the last four digits of your social security number followed by your first and last initials. –For example, Luke Skywalker, whose social security number is 123-45-6789, has a password of 6789ls. u In a CSE laboratory room, you will have to log in to the Windows PC first. –Your initial password there is the same as for UNIX except that it has an additional exclamation mark (‘!’) at the end. Luke Skywalker’s initial Windows password is 6789ls!

43 CSE36043 Make a Table on an Index Card u Show Different Representations of Numeric Values. –Column Headings Should be: DecimalOctalHexadecimalBinary

44 CSE36044 One Row for Each Numeric Value. u Show, in Increasing Order, –Representations for 0, 1, 2, 3, 4, … 20 –Then, 2 5, 2 6, … 2 16 –Finally 2 20, 2 30, 2 31, 2 32

45 CSE36045 For Example, DecimalOctalHexBinaryNoteRoman Nat’l Lang 0000 zero 11112 0 Ione 222102 1 IItwo And so on. 20241410100 XXIVTwenty 3240201000002 5 XXXII.. And so on... 2 16 2 20 2 30 2 31 2 32

46 CSE36046 Information Representation 1 u Positional Number Systems: position of character in string indicates a power of the base (radix). Common bases: 2, 8, 10, 16. (What base are we using to express the names of these bases?) –Base ten (decimal): digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 form the alphabet of the decimal system.  E.g., 316 10 = –Base eight (octal): digits 0, 1, 2, 3, 4, 5, 6, 7 form the alphabet.  E.g., 474 8 =

47 CSE36047 Information Representation 2 –Base 16 (hexadecimal): digits 0-9 and A-F.  E.g., 13C 16 = –Base 2 (binary): digits (called “bits”) 0, 1 form the alphabet.  E.g., 100110 = –In general, radix r representations use the first r chars in {0…9, A...Z} and have the form d n-1 d n-2 …d 1 d 0. Summing d n-1  r n-1 + d n-2  r n-2 + … + d 0  r 0 will convert to base 10. Why to base 10?

48 CSE36048 Information Representation 3 u Base Conversions –Convert to base 10 by multiplication of powers  E.g., 10012 5 = ( ) 10 –Convert from base 10 by repeated division  E.g., 632 10 = ( ) 8 –Converting base x to base y: convert base x to base 10 then convert base 10 to base y

49 CSE36049 Information Representation 4 –Special case: converting among binary, octal, and hexadecimal is easier t Go through the binary representation, grouping in sets of 3 or 4.  E.g., 11011001 2 = 11 011 001 = 331 8 11011001 2 = 1101 1001 = D9 16  E.g., C3B 16 = ( ) 8

50 CSE36050 Information Representation 5 u What is special about binary? –The basic component of a computer system is a transistor (transfer resistor): a two state device which switches between logical “1” and “0” (actually represented as voltages on the range 5V to 0V). –Octal and hexadecimal are bases in powers of 2, and are used as a shorthand way of writing binary. A hexadecimal digit represents 4 bits, half of a byte. 1 byte = 8 bits. A bit is a binary digit. –Get comfortable converting among decimal, binary, octal, hexadecimal. Converting from decimal to hexadecimal (or binary) is easier going through octal.

51 CSE36051 Information Representation 6 BinaryHexDecimalBinaryHexDecimal 000000100088 000111100199 0010221010A10 0011331011B11 0100441100C12 0101551101D13 0110661110E14 0111771111F15

52 CSE36052 Information Representation 7 u Ranges of values –Q: Given k positions in base n, how many values can you represent? –A: n k values over the range (0…n k -1) 10 n=10, k=3: 10 3 =1000 range is (0…999) 10 n=2, k=8: 2 8 =256 range is (0…255) 10 n=16, k=4: 16 4 =65536 range is (0…65535) 10 –Q: How are negative numbers represented?

53 CSE36053 Information Representation 8 u Integer representation: –Value and representation are distinct. E.g., 12 may be represented as XII, C 16, 12 10, and 1100 2. Note: -12 may be represented as -C 16, -12 10, and -1100 2. –Simple and efficient use of hardware implies using a specific number of bits, e.g., a 32-bit string, in a binary encoding. Such an encoding is “fixed width.” –Four methods: (fixed-width) simple binary, signed magnitude, binary coded decimal, and 2’s complement. –Simple binary: as seen before, all numbers are assumed to be positive, e.g., 8-bit representation of 66 10 = 0100 0010 2 and 194 10 = 1100 0010 2

54 CSE36054 Information Representation 9 –Signed magnitude: simple binary with leading sign bit. 0 = positive, 1 = negative. E.g., 8-bit signed mag.: 66 10 = 0100 0010 2 -66 10 = 1100 0010 2 What ranges of numbers may be expressed in 8 bits? Largest: Smallest: Extend 1100 0010 to 12 bits:

55 CSE36055 Information Representation 10 Problems: (1) Compare the signed magnitude numbers 1000 0000 and 0000 0000. (2) Must have “subtraction” hardware in addition to “addition” hardware. –Binary Coded Decimal (BCD): use a 4 bit pattern to express each digit of a base 10 number 0000 = 0 0001 = 1 0010 = 2 0011 = 3 0100 = 4 0101 = 5 0110 = 6 0111 = 7 1000 = 8 1001 = 9 1010 = + 1011 = - E.g., 123 : 0000 0001 0010 0011 +123 : 1010 0001 0010 0011 -123 : 1011 0001 0010 0011

56 CSE36056 Information Representation 11 BCD Disadvantages: –Takes more memory. 32 bit simple binary can represent more than 4 billion discrete values. 32 bit BCD can hold a sign and 7 digits (or 8 digits for unsigned values) for a maximum of 110 million values, a 97% reduction. –More difficult to do arithmetic. Essentially, we must force the Base 2 computer to do Base 10 arithmetic. BCD Advantages: –Used in business machines and languages, i.e., in COBOL for precise decimal math. –Can have arrays of BCD numbers for essentially arbitrary precision arithmetic.

57 CSE36057 Information Representation 12 –Two’s Complement t Used by most machines and languages to represent integers. Fixes the -0 in the signed magnitude, and simplifies machine hardware arithmetic. t Divides bit patterns into a positive half and a negative half (with zero considered positive); n bits creates a range of [-2 n-1 … 2 n-1 -1]. CODE 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Simple 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Signed +0 1 2 3 4 5 6 7 -0 -2 -3 -4 -5 -6 -7 2’s comp 0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2

58 CSE36058 Information Representation 13 –Representation in 2’s complement; i.e., represent i in n-bit 2’s complement, where -2 n-1  i  +2 n-1 -1 t Positive numbers: same as simple binary t Negative numbers: –Obtain the n-bit simple binary equivalent of | i | –Obtain its negation as follows: Invert the bits of that representation Add 1 to the result t Ex.: convert -320 10 to 16-bit 2’s complement t Ex.: extend the 12-bit 2’s complement number 1101 0111 1000 to 16 bits.

59 CSE36059 Information Representation 14 u Binary Arithmetic –Addition and subtraction only for now –Rules: similar to standard addition and subtraction, but only working with 0 and 1. t 0 + 0 = 00 - 0 = 0 t 1 + 0 = 11 - 0 = 1 t 0 + 1 = 11 - 1 = 0 t 1 + 1 = 1010 - 1 = 1 –Must be aware of possible overflow.  Ex.: 8-bit signed magnitude 0101 0110 + 0110 0011 =  Ex.: 8-bit signed magnitude 0101 0110 - 0110 0011 =

60 CSE36060 Information Representation 15 u 2’s Complement binary arithmetic –Addition and subtraction are the same operation –Still must be aware of overflow.  Ex.: 8 bit 2’s complement: 23 10 + 45 10 =  Ex.: 8 bit 2’s complement: 23 10 - 45 10 =  Ex.: 8 bit 2’s complement: 100 10 + 45 10 =

61 CSE36061 Information Representation 16 –2’s Complement overflow t Opposite signs on operands can’t overflow t If operand signs are same, but result’s sign is different, must have overflow

62 CSE36062 Information Representation 17 u Characters and Strings –EBCDIC, Extended Binary Coded Decimal Interchange Code t Used by IBM in mainframes (360 architecture and descendants). t Earliest system –ASCII, American Standard Code for Information Interchange. t Most common system –Unicode, http://www.unicode.org t New international standard t Variable length encoding scheme with either 8- or 16-bit minimum t “a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.”

63 CSE36063 Information Representation 18 u ASCII –see table 1.7 on pg. 18. t In Unix, run “man ascii”. –7 bit code t Printable characters for human interactions t Control characters for non-human communication (computer- computer, computer-peripheral, etc.) –8-bit code: most significant bit may be set t Extended ASCII (IBM), includes graphical symbols and lines t ISO 8859, several international standards t Unicode’s UTF-8, variable length code with 8-bit minimum

64 CSE36064 ASCII u Easy to decode –But takes up a predictable amount of space u Upper and lower case characters are 0x20 (32 10 ) apart u ASCII representation of ‘3’ is not the same as the binary representation of 3. –To convert ASCII to binary (an integer), ‘3’-‘0’ = 3 u Line feed (LF) character –000 1010 2 = 0x0a = 10 10 –‘\n’ = 0xa

65 CSE36065 Information Representation 19 u Decode: 1000001, 1010011, 1000011, 1001001, 1001001, 0100000, 1101001, 1110011, 0100000, 1100101, 1100001, 1110011, 1111001, 0000000 –Or (in hex): 41 53 43 49 49 20 69 73 20 65 61 73 79 00 u How many bytes is this? u What’s the use of the ’00’? u String definition is programming language dependent. u C, C++: strings are arrays of characters terminated by a null byte.

66 CSE36066 Information Representation 20 u Simple data compression –ASCII codes are fixed length. –Huffman codes are variable length and based on statistics of the data to be transmitted. t Assign the shortest encoding to the most common character. –In English, the letter ‘e’ is the most common. –Either establish a Huffman code for an entire class of messages, –Or create a new Huffman code for each message, sending/storing both the coding scheme and the message. t “a widely used and very effective technique for compressing data; savings of 20% to 90% are typical, depending on the characteristics of the file being compressed.” (Cormen, p. 337)

67 CSE36067 ECL - Expected Code Length CharFixed len encoding FreqVar len encoding # bitsExpected # bits  00.511  01.25012.5  10.150013.45  11.100003.3 Avg len21.75

68 CSE36068 Information Representation 21 u Huffman Tree for “a man a plan a canal panama” –Determine frequencies of letters (example ignores spaces) –Create a forest of single node trees. t Choose the two trees having the smallest total frequencies (the two “smallest” trees) t Merge them together (lesser frequency as the left subtree. t Continue merging until only one tree remains.

69 CSE36069 Information Representation 22 Huffman Tree for "a man a plan a canal panama" 'a'.4762 'n'.1905 'c'.0476 'l'.0952.1428 'm'.0952 'p'.0952.1905.3333.5238 1.0 u Reading a ‘1’ calls for following the left branch. u Reading a ‘0’ calls for following the right branch. u Decoding using the tree: To decode ‘0001’, start at root and follow r_child, r_child, r_child, l_child, revealing encoded ‘m’.

70 CSE36070 Information Representation 23 u Comparison of Huffman and 3-bit code example –3-bit: 000 011000100 000 101010000100 000 001000100000010 101000100000011000 = 63 bits –Huffman: 1 0001101 1 00000010101 1 001110110010 0000101100011 = 46 bits –Savings of 17 bits, or 27% of original message

71 Tree for: ABE DEFACED A FADED BED CSE36071 BC F ADE 9/1910/19 5/19 3/19 freq A4/19 B2/19 C1/19 D5/19 E5/19 F2/19

72 CSE36072 ECL - Expected Code Length CharFixed len encoding FreqVar len encoding # bitsExpected # bits  00.511  01.25012.5  10.150013.45  11.100003.3 Avg len21.75

73 ECL for: ABE DEFACED A FADED BED freqcodeecl A4/19118/19 B2/1910008/19 C1/1910014/19 D5/190110/19 E5/190010/19 F2/191016/19 ecl = 2.42 CSE36073 Use the same encodings to decode 11 10000011010001 11100100 1001111000

74 CSE36074 Parity: Simple error detection u Data transmission, aging media, static interference, dust on media, etc. demand the ability to detect errors. –Ex.: send ASCII ‘S’ : send 1010011, but receive 1010010(‘R’) ? u Single bit errors detected by using parity checking. u Parity, here, is the “the state of being odd or even.”

75 CSE36075 Information Representation 24 u How to detect a 1-bit error: –Add a 1-bit parity to make an odd or even number of bits per byte. –Parity bit is stripped by hardware after checking. Sender/receiver both agree to odd or even parity. –2 flipped bits in the same encoding are not detected. What if parity bit is flipped?

76 CSE36076 Information Representation 25 u Two meanings for Hamming distance. 1.Specific. A count of the number of bits different in two encodings. E.g.,dist(1100, 1001) = dist(0101, 1101) = 2.General. The minimum over all distinct pairs in an entire code. t The ASCII encoding scheme has a Hamming distance of 1. t A simple parity encoding scheme has a Hamming distance of 2. u Hamming distance serves as a measure of the robustness of error checking (as a measure of the redundancy of the encoding).

77 CSE36077 Basic Components 1 u Terminology from Ch. 2: –Flip flop: basic storage device that holds 1 bit –D flip flop: special flip flop that outputs the last value that was input to it (a data signal). –Clock: two different meanings: (1) a control signal that oscillates (low to high voltage) every x nanoseconds; (2) the “write select” line for a flip flop.

78 CSE36078 Basic Components 2 –Register: collection of flip flops with parallel load. Clock (or “write select”) signal controlled. Stores instructions, addresses, operands, etc. –Bus: Collection of related data lines (wires).

79 CSE36079 Basic Components 3 –Combinational circuits: implement Boolean functions. No feedback in the circuit, output is strictly a function of input. t Gates: and, or, not, xor E.g., xy +  z

80 CSE36080 Basic Components 4 –Gates can be used in combination to implement a simple (half) adder. t Addition creates a value, plus a carry-out. Z = X  Y CO = X  Y X Y Z CO

81 CSE36081 Basic Components 5 –Sequential Circuits: introduce feedback into the circuit. Outputs are functions of input and current state. –Multiplexers: combinational circuits that use n bits to select an output from 2 n input lines. D C Q

82 CSE36082 Basic Components 6 u Von Neumann Architecture –Can access either instructions or data from memory in each cycle. –One path to memory (von Neumann bottleneck) –Stored program system. No distinction between programs and data

83 CSE36083 Basic Components 7 Examples of Von Neumann architecture to be explored in this course: u SAM: tiny, good for learning architecture u MIPS: text’s example assembly language u SPARC: labs u M68HC11: used in ECE 567 (taken by CSE majors) Roughly, the order of presentation in this course is as follows: u A couple of days on the Main Memory System u Weeks on the Central Processing Unit (CPU) u Finish the course with the I/O System

84 CSE36084 Memory Subsystem – the busses Address Bus Data Bus 000 001 010 011 100 101 n-bit Addressible n k The number of elements depend on the size of the address bus. If k=3, how many addresses? If k=4, how many addresses? # Addresses = 2 k

85 CSE36085 Memory Subsystem – the busses Address Bus Data Bus 000 001 010 011 100 101 n-bit Addressible n k Capacity depends on how many bits in each element, or the size of the data bus. If n=1 and k=3, how many bits? If n=2? If n=8 and k=3, how many Bytes? Bit capacity = 2 k * n

86 CSE36086 Memory Element & Address Sizes If a machine’s memory is 5-bit addressable, then, at each distinct address, 5 bits are stored. The contents at each address are represented by 5 bits. If 3 bits are used to represent memory addresses, then the memory can have at most 2 3 = 8 distinct addresses. Such a memory can store at most 8  5 = 40 bits of data. If the data bus is 10 bits wide, then up to 10 bits at a time can be transferred between memory and processor; this is a 10-bit word. Address Contents DecimalBinary 000000011 100101111 201001110 301110100 410000101 510101110 611010100 711110011

87 CSE36087 Memory Subsystem - Addressibility u Addressibility is the size of the memory element u The size of the element may be smaller than the size of the data bus. –If n=8, only 1 Byte Addressible –If n=16, 1 or 2 Byte Addressible Address Bus Data Bus 000 001 010 011 100 101 n-bit Addressible n k How does Addressibility affect capacity?

88 CSE36088 Memory Subsystem - Addressing u Memory may be organized into banks, with bit labels u The GLOBAL address of each addressible element would be: [relative address] & [bank address] Address Bus Data Bus 000 001 010 011 100 101 Bank 0 Bank 1 000 0 001 0 010 0 011 0 100 0 101 0 000 1 001 1 010 1 011 1 100 1 101 1 See the pattern that forms?

89 CSE36089 Memory Subsystem - Alignment Data bus is 4x the size of addressible element. So, you may read (or write) one or more Bytes at a time… But only from/to the same row of memory! Address Bus Data Bus 000 001 010 011 100 101 32 Okay to read/write 2 Bytes from 10010? 2B from 01011? 4B from 01100? 4B from 00101? Bank 00 000 00 001 00 010 00 011 00 100 00 101 00 Bank 01 000 01 001 01 010 01 011 01 100 01 101 01 Bank 10 000 10 001 10 010 10 011 10 100 10 101 10 Bank 11 000 11 001 11 010 11 011 11 100 11 101 11 8- bit

90 CSE36090 Memory Subsystem - Alignment Address Bus Data Bus 000 001 010 011 100 101 Bank 00 000 00 001 00 010 00 011 00 100 00 101 00 Bank 01 000 01 001 01 010 01 011 01 100 01 101 01 Bank 10 000 10 001 10 010 10 011 10 100 10 101 10 32 Bank 11 000 11 001 11 010 11 011 11 100 11 101 11 8- bit u Where are operands of various sizes positioned? –1 Bytes Aligned t on any address –2 Byte Aligned t on “halfword” boundary t addresses divisible by 2 t end in hex 0,2,4,6,8,A,C,E) –4 Byte Aligned t on “word” boundary t addresses divisible by 4 t end in hex 0,4,8,C)

91 CSE36091 Contrast with bit ordering Basic Components 11 u Byte ordering: how numeric data is stored in memory –Ex.: 247896511 10 = 0EC699BF 16 –Stored at address 0 0OE 1C6 299 3BF 0 199 2C6 30E Big Endian High order (big end) is at byte 0 76543210 10111111 Little Endian Low order (little end) is at byte 0

92 CSE36092 Basic Components 12 u Read/Write operations: must know the address to read or write. (read = fetch = load, write = store) t CPU puts address on address bus t CPU sends read signal –(R/  W=1, CS=1) –(Read/don’t Write, Chip Select) t Wait t Memory puts data on data bus –reset (CS=0) D0 D1 D(n-1) A0 A1 A(m-1) CS R/  W

93 CSE36093 Basic Components 13 u Types of memory: –ROM: Read Only Memory: non-volatile (doesn’t get erased when powered down; it’s a combinational circuit!) –PROM: Programmable ROM: use a ROM burner to write data to it initially. Can’t be re-written. –EPROM: Erasable PROM. Uses UV light to erase. –EEPROM: Electrically Erasable PROM. –RAM: Random access memory. Can efficiently read/write any location (unlike sequential access memory). Used for main memory. t Many variations (types) of RAM, all volatile –SDRAM, DDR SDRAM –RDRAM –www.tomshardware.com

94 CSE36094 Instructional Sparc Emulator - ISEM u Editing, Assembling, Linking, and Loading –There are three components to the Instructional SPARC Emulator (ISEM) package that we use for this class: t the assembler, t the linker, and t the emulator/debugger.

95 CSE36095 Instructional Sparc Emulator - ISEM – u Editing –There are a number of programs that you can use to create your source files. t Emacs is probably the most popular; t vi is also available, but its command syntax is difficult to learn and use; t using pine program, you can use the pico editor, which combines many features of Emacs into a simple menu-driven facility. –Start Emacs by “xemacs sourcefile.s &”, which creates the file called sourcefile.s. –Use the tutorial, accessed by typing "Ctrl-H Ctrl-H t". –For other editors, you are on your own.

96 CSE36096 Example Sparc Assembly Language Instructions % type xmp0.s.data ! Assembler directive: data starts here. A_m, B_m, and A_m:.word ’?’ ! C_m are symbolic constants. Furthermore, each B_m :.word 0x30 ! is an address of a certain-sized chunk of memory. Here, C_m :.word 0 ! each chunk is four bytes (one word) long. When the ! program gets loaded, each of these chunks stores a ! number in 2’s complement encoding, as follows: At ! address C_m, zero; at B_m, 48; at A_m, 0x3F = 077 = 63..text! Assembler directive, instructions start here start:! Label (symbolic constant) for this address set A_m, %r2! Put address A_m into register 2 ld [%r2], %r2! Use r2 as an indirect address for a load (read) set B_m, %r3! Put address B_m into register 3 ld [%r3], %r3! Read from B_m and replace r3 w/ value at addr B_m sub %r2, %r3, %r2! Subtract r3 from r2, save in r2 set C_m, %r4! Put address C_m into register 4 st %r2, [%r4]! Store (write) r2 to memory at address C_m terminate:! Label for address where ’ta 0’ instruction stored ta 0! Stop the program beyond_end:! Label for address beyond the end of this program

97 CSE36097 Instructional Sparc Emulator - ISEM u Assembling –The assembler is called "isem-as", and is the GNU Assembler (GAS), configured to cross-assemble to a SPARC object format. –It is used to take your source code, and produce object code that may be linked and run on the ISEM emulator. –The syntax for invoking the assembler is: isem-as [-a[ls]] sourcefile.s -o objectfile.o –The input is read from sourcefile.s, and the output is written to objectfile.o. –The option "-a" tells the assembler to produce a listing file. The sub-options "l" and "s" tell the assembler to include the assembly source in the listing file and produce a symbol table, respectively.

98 CSE36098 Instructional Sparc Emulator - ISEM u The listing file –Will identify all the syntactic errors in your program, and it will warn you if it identifies "suspicious" behavior in your source file. –Column 1 identifies a line number in your source file. –Column 2 is an offset for where this instruction or data resides in memory. –Column 3 is the image of what is put in memory, either the machine instructions or the representation of the data. –The final column is the source code that produced the line. –At the bottom of the file you will find the symbol table. –Again, the symbols are represented as offsets that are relocated when the program is loaded into memory.

99 CSE36099 isem-as -als labn.s -o labn.o >! labn.lst 1.data 2 0000 0000003F A_m:.word ’?’ 3 0004 00000030 B_m:.word 0x30 4 0008 00000000 C_m:.word 0 5 000c 00000000.text 6 start: 7 0000 05000000 set A_m, %r2 7 8410A000 8 0008 C4008000 ld [%r2], %r2 9 000c 07000000 set B_m, %r3 9 8610E000 10 0014 C600C000 ld [%r3], %r3 11 0018 84208003 sub %r2, %r3, %r2 12 001c 09000000 set C_m, %r4 12 88112000 13 0024 C4210000 st %r2, [%r4] 14 terminate: 15 0028 91D02000 ta 0 16 002c 01000000 beyond_end: DEFINED SYMBOLS xmp0.s:2.data:00000000 A_m xmp0.s:3.data:00000004 B_m xmp0.s:4.data:00000008 C_m xmp0.s:6.text:00000000 start xmp0.s:14.text:00000028 terminate xmp0.s:16.text:0000002c beyond_end NO UNDEFINED SYMBOLS Line in source file (.s) Offset to address in memory Contents at address in memory Labels are symbolic offsets

100 CSE360100 Instructional Sparc Emulator - ISEM u Linking –Linking turns a set of raw object file(s) into an executable program. –From the manual page, "ld combines a number of object and archive files, relocates their data and ties up symbol references. Often the last step in building a new compiled program to run is a call to ld." –Several object files are combined into one executable using ld; the separate files could reference symbols from one another. –The output of the linker is an executable program. –The syntax for the linker is as follows: isem-ld objectfile.o [-o execfile] Examples % isem-ld foo.o -o foo Links foo.o into the executable foo. % isem-ld foo.o Links foo.o into the executable a.out.

101 CSE360101 Instructional Sparc Emulator - ISEM u Loading/Running –Execute the program and test it in the emulation environment. –The program "isem" is used to do this, and the majority of its features are covered in your lab manual. –Invoke isem as follows isem [execfile] Examples % isem foo Invokes the emulator, loads the program foo % isem Invokes the emulator, no program is loaded –Once you are in the emulator, you can run your program by typing "run" at the prompt.

102 CSE360102 ISEM Debugging Tools 1 % isem xmp0 Instructional SPARC Emulator Copyright 1993 - Computer Science Department University of New Mexico ISEM comes with ABSOLUTELY NO WARRANTY ISEM Ver 1.00d : Mon Jul 27 16:29:45 EDT 1998 Loading File: xmp0 2000 bytes loaded into Text region at address 8:2000 2000 bytes loaded into Data region at address a:4000 PC: 08:00002020 nPC: 00002024 PSR: 0000003e N:0 Z:0 V:0 C:0 start : sethi 0x10, %g2 ISEM> run Program exited normally. Assembly language programs are not notoriously chatty.

103 CSE360103 ISEM Debugging Tools 2 u reg –Gives values of all 32 general registers –Also PC u symb –Shows the resolved values of all symbolic constants u dump [addr] –Either symbol or hex address –Gives the values stored in memory ISEM> reg ----0--- ----1--- ----2--- ----3--- ----4--- ----5--- ----6--- ----7--- G 00000000 00000000 0000000f 00000030 00004008 00000000 00000000 00000000 O 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 L 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 I 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 PC: 08:0000204c nPC: 00002050 PSR: 0000003e N:0 Z:0 V:0 C:0 beyond_end : sethi 0x0, %g0 ISEM> symb Symbol List A_m : 00004000 B_m : 00004004. terminate : 00004028 ISEM> dump A_m 0a:00004000 00 00 00 3f 00 00 00 30 00 00 00 0f 00 00 00 00...?...0........ 0a:00004010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00................ 0a:00004020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00................

104 CSE360104 ISEM Debugging Tools u break [addr] –Set breakpoints in execution –Once execution is stopped, you can look at the contents of registers and memory. u trace –Causes one (or more) instruction(s) to be executed –Registers are displayed –Handy for sneaking up on an error when you’re not sure where it is.

105 CSE360105 ISEM Debugging Tools u For the all-time “most wanted” list of errors (and their fixes)

106 CSE360106 ISEM Debugging u If you still need help –Print a fresh copy of your source –Make good notes describing the error –Visit your lecturer or grader –Post a question to the discussion board

107 CSE360107 Basic Components 14 u CPU: executes instructions -- primitive operations that the computer can perform. –E.g.,arithmeticA+B data movementA := B controlif expr goto label logicalAND, OR, XOR… t Instructions specify both the operation and the operands. An encoded operand is often a location in memory where the value of interest may be found (address of value of interest).

108 CSE360108 Basic Components 15 –Instruction set: all instructions for a machine. Instruction format specifies number and type of operands. t Ex.: Could have an instruction like ADD A, B, R Where A, B, and R are the addresses of operands in memory. The result is R := A+B.

109 CSE360109 Basic Components 16 –Actually, the “instruction” might be represented in a source file as: 0x41444420412C20422C20520A. … A D D A, B, R As such, it is an assembly language instruction. –An assembler might translate it to, say, 0x504C, the machine’s representation of the instruction. As such, it is a machine language instruction.

110 CSE360110 A Simple Instruction Set 1 u Simple instruction set: the Accumulator machine. –Simplify instruction set by only allowing one operand. Accumulator implied to be the second operand. –Accumulator is a special register. Similar to a simple calculator.  ADD addrACC  ACC + M[addr]  SUB addrACC  ACC - M[addr]  MPY addrACC  ACC * M[addr]  DIV addrACC  ACC / M[addr]  LOAD addrACC  M[addr]  STORE addrM[addr]  ACC

111 CSE360111 A Simple Instruction Set 2  Ex.: C = A  B + C  D LOAD 20! Acc<-M[20] MPY 21! Acc<-Acc*M[21] STORE 30! M[30]<-Acc LOAD 22! Acc<-M[22] MPY 23! Acc<-Acc*M[23] ADD 30! Acc<-Acc+M[30] STORE 22! M[22]<-Acc 1) 2) 3) 4) 5) AddressSymbolicContents 20A0001 21B0010 22C0011 23D0100 … 30temp Accumulator 0000 0001 0010 0010 0011 1100 1110 1110 Try C=2A+B Try C=A+2

112 CSE360112 An Instruction (Encoding) Format u Machine language: Converting from assembly language to machine language is called assembling. u Assume 8-bit architecture. Each instruction may be 8 bits. 3 bits hold the op-code and 5 bits hold the operand. u How much memory can we address? u How many op-codes can we have?

113 CSE360113 A Simple Instruction Set 4 u Convert the mnemonic op-codes into binary codes. u Hand assemble our program: u Instructions are stored in consecutive memory:

114 CSE360114 Simple Accumulator Machine

115 Simple Accumulator Machine (SAM) CSE360115 u REGISTERS –ACC – Accumulator, stores program values –IR - Instruction Register, holds the instruction during interpretation –MAR - Memory Address Register, stores address to read/write to/from –MDR - Memory Data Register, stores data from memory, either written/read –PC - Program Counter, stores the address of the next instruction

116 Simple Accumulator Machine (SAM) CSE360116 u Combinational Circuits –ALU - Arithmetic and logic unit, implements the operations (eg, +,-,*,/) –Decode - Instruction decoder, splits off the opcode and operands –INC - Incrementer, increments the PC –MUX - Multiplexer, controls inputs to PC and ACC

117 Simple Accumulator Machine (SAM) CSE360117 u Sequential Circuit –Timing and control - asserts control signals, clock u Combination of flip-flops, circuits and capacitors –Memory – stores instructions and data

118 CSE360118 A Simple Instruction Set 6 –Control signals: control functional units to determine order of operations, access to bus, loading of registers, etc.

119 CSE360119 A Simple Instruction Set 7 0 1 2 3 State Y N 4 5 Y N 7 8 6

120 CSE360120 State 0: Control Signals 2, 5, 9, 3 Put the address of the next instruction in the Addr Register and Inc. PC.

121 CSE360121 State 1: Control Signals 13, 14 Fetch the word of memory at Address, and load into Data Register.

122 CSE360122 State 2: Control Signals 6, 4 Send the word from the Data Register to the Instruction Register.

123 CSE360123 State 3: Control Signals 12, 5 Put the address from the instruction in the Address Register.

124 CSE360124 After State 3, what values are now stored in each register? u PC u MAR u MDR u IR u ACC

125 CSE360125 State 4: Control Signals 0, 7 Take the value from the ACCumulator and store it in the Data Register.

126 CSE360126 State 5: Control Signal 13 Write the data from the Data Register to the address stored in the MAR.

127 CSE360127 State 6: Control Signals 13, 14 Load the word at the Address from the Addr Reg into the Data Register.

128 CSE360128 After State 6, what values are now stored in each register? u PC u MAR u MDR u IR u ACC

129 CSE360129 State 7: Control Signals 6, 1 Load the word from Data Register into the ACCumulator.

130 CSE360130 State 8: Control Signals 6, 8, 10/11, 1 Use word from the Data Register for Arith Op and put result in ACC.

131 CSE360131 New Instruction What is necessary to implement a new instruction? New states? New control signals? New fetch/execute cycle? An Example: SWAP Exchange value in Accumulator with value at Address SWAP addr ! Acc <- #M[addr], M[addr] <- #Acc

132 CSE360132 New Instruction u What changes to fetch/execute cycle? –The fetch part of the cycle usually remains the same. –Recall the values stored in registers after each state t E.g., After State 6, t what values are in each register? –PC –MAR –MDR –IR –ACC t Handy to have #M[addr] in MDR –Start after state 6 then….

133 CSE360133 New State 9: Control Signals 6, 4 Save the Data value from the MDR in the Address Register. MDR -> bus Load IR

134 CSE360134 New State 10: Control Signals 0, 7 Send the ACCumulator value to the Data Register. ACC -> bus load MDR

135 CSE360135 New State 11: Control Signals 15?, 1 Put the saved value from the IR into the ACCumulator. IR ->bus load ACC Note: there is no control signal in the current architecture opposite of 4 (Load IR), so we would have to create a new control signal (MAR to bus) in addition to creating these new states.

136 CSE360136 New State 12 (Old 5): Control Signals 13 Write the data from the Data Register to the address stored in the MAR. CS

137 CSE360137 New Instruction Solution u Changes to States, added 9 thru 12 u Changes to Signals, added 15: IR-> bus u Changes to Fetch/Execute, new register transfer language (RTL) PC -> bus, load MAR, INC -> PC, Load PC CS, R/w MDR -> bus, load IR Addr -> bus, load MAR CS, R/w MDR -> bus, load IR ACC -> bus, load MDR IR-> bus, load ACC CS MAR->bus IR->bus What if we had added MAR->bus instead of IR->bus?

138 CSE360138 Instruction Set Architectures 1 u RISC vs. CISC –Complex Instruction Set Computer (CISC): t Many, powerful instructions. t High code density to address the Von Neumann Bottleneck. t Instructions have varying lengths, number of operands, formats, and clock cycles in execution. –Reduced Instruction Set Computer (RISC): t Fewer, less powerful, optimized instructions. t Requires simpler, faster hardware. t Instructions have fixed length, number of operands, formats, and similar number of clock cycles in execution.

139 CSE360139 Instruction Set Architectures 2 u Motivation: memory is comparatively slow. –10x to 20x slower than processor. –Need to minimize number of trips to memory. t Provide faster storage in the processor -- registers. t Registers (16, 32, 64 bits wide) are used for intermediate storage for calculations, or repeated operands. t Accumulator machine –One data register -- ACC. –2 memory accesses per instruction -- one for the instruction and one for the operand. t Add more registers (R0, R1, R2, …, Rn)

140 CSE360140 Instruction Set Architectures 3 u How many addresses to specify? –With binary operations, need to know two source operands, a destination, and the operation.  E.g., op (dest_operand) (src_op1) (src_op2) –Based on number of operands, could have: t 3 addr. machine: both sources and dest are named. t 2 addr. machine: both sources named, dest is a source. t 1 addr. machine: one source named, other source and dest. is the accumulator. t 0 addr. machine: all operands implicit and available on the stack.

141 CSE360141 Instruction Set Architectures 4  1-address architecture: a:=a  b+c  d  e –Memory onlyUsing registers t 1½-address architecture: at least one operand must always be a register. (½ address is register, 1 address is the memory operand: LOAD 100, R1). –Like an accumulator machine, but with many accumulators.

142 CSE360142 Instruction Set Architectures 5  3-address architecture: a:=a  b+c  d  e –Using memory only: –Using registers: What about instruction size?

143 Instruction Set Architecture u How does instruction size affect addressing? –16-bit instruction, 3 address, 6 instructions –How many addresses will be supported? –What if the instruction were 32 bit? CSE360143 Opcode = 3 bits (2 3 =8) Operand = (size -opcode) / #addr =4 bits Operand = (size -opcode) / #addr =4 bits Operand = (16-3) / 3 =4 bits Operand = (16-3) / 3 =4 bits Operand = 13 / 3 =4 bits Operand = 13 / 3 =4 bits

144 CSE360144 Instruction Set Architectures 6  2-address architecture: a:=a  b+c  d  e –Using memory only: –Using registers: Most CISC arch. this way, making 1 operand implicit

145 CSE360145 Instruction Set Architectures 7  0-address architecture: a:=a  b+c  d  e –Stack machine: All operands are implicit. Only push and pop touch memory. All other operands are pulled from the top of stack, and result is pushed on top. E.g., HP calculators. Stack A B A*B C D E D*E C*D*E A*B + C*D*E

146 CSE360146 Instruction Set Architectures 8 Load/Store Architectures -- RISC Use of registers is simple and efficient. Therefore, the only instructions that can access memory are load and store. All others reference registers. RISC Load/ Store

147 CSE360147 Instruction Set Architectures 9 u Why load/store architectures? –Number of instructions (hence, memory references to fetch them) is high, but can work without waiting on memory. t CISC machines tend to need to have their more complex instructions interpreted in micro code –More room in CPU for registers and memory cache. –Easier to overlap instruction execution through pipelining. Fetch …. Execute

148 CSE360148 Instruction Set Architectures 9 u Side effects –Register interlock: delaying execution until memory read completes. t Machine waits when necessary, to avoid erroneous results. ld [%r1], %r2 add %r2, 100, %r3 –Branch delays: instruction after branch is always executed. u Instruction scheduling –Rearranging instructions to maximize efficiency of pipelining t To prevent register interlock (loads on SPARC) t To use branch delay slots (branches on SPARC).

149 CSE360149 SPARC Assembly Language 1 u SPARC (Scalable Processor ARChitecture) –Used in Sun workstations, descended from RISC-II developed at UC Berkeley –General Characteristics: t 32-bit word size (integer, address, register size, etc.) t Byte-addressable memory t RISC load/store architecture, 32-bit instruction, few addressing modes t Many registers (32 general purpose, 32 floating point, various special purpose registers) –ISEM: Instructional SPARC Emulator - nicer than a real machine for learning to write assembly language programs.

150 CSE360150 SPARC Assembly Language 2 u Structure –Line oriented: 4 types of lines t Blank - Ignored t Labeled - –Any line may be labeled. Creates a symbol in listing. Labels must begin with a letter (other than ‘L’), then any alphanumeric characters. Label must end with a colon “ : ”. Label just assigns a name to an address.  Assembler Directives - E.g.,.data.word.text, etc. t Instructions –Comments start after “ ! ” character and go to the end of the line..data x_m:.word 0x42 y_m:.word 0x20 z_m:.word 0.text start: set x_m, %r2 ld [%r2], %r2 set y_m, %r3 ld [%r3], %r3 ! Load x into reg 2 ! Load y into reg 3

151 CSE360151 SPARC Assembly Language 3 u Directives: Instructions to the assembler –Not executed by the machine .data -- following section contains declarations –Each declaration reserves and initializes a certain number of bits of storage for each of zero or more operands in the declaration..word -- 32 bits.half -- 16 bits.byte -- 8 bits E.g.,.data w:.half 27000 x:.byte 8 y:.byte ’m’, 0x6e, 0x0, 0, 0 z:.word 0x3C5F .text -- following section contains executable instructions

152 CSE360152 SPARC Assembly Language 11 –More assembler directives (.asciz and.ascii): t Each of the following two directives is equivalent: –msg01:.asciz "a phrase" –msg01:.byte 'a', ' ', 'p', 'h', 'r'.byte 'a', 's', 'e', 0 t Note that.asciz generates one byte for each character between the quote (") marks in the operand, plus a null byte at the end. t The.ascii directive does not generate that extra byte. Each of the following three directives is equivalent: –digits:.ascii "0123456789" –digits:.byte '0', '1', '2', '3', '4', '5'.byte '6', '7', '8', '9' –digits:.byte 0x30, 0x31, 0x32, 0x33, 0x34.byte 0x35, 0x36, 0x37, 0x38, 0x39

153 CSE360153 SPARC Assembly Language  Memory alignment:.align 4 –Used when mixing allocations of bytes, words, halfwords, etc. and need word boundary alignment  Reserve bytes of space:.skip 20 –Useful for allocating large amounts of space (e.g., arrays)  Create a symbolic constant:.set mask, 0x0f –Can now use the word “mask” anywhere we could use the constant 0x0f previously

154 CSE360154 SPARC Assembly Language 4 u Registers -- 32 bits wide –32 general purpose integer registers, known by several names to the assembler  %r0-%r7 also known as %g0-%g7 global registers -- Note, %r0 always contains value 0.  %r8-%r15 also known as %o0-%o7 output registers  %r16-%r23 also known as %l0-%l7 local registers  %r24-%r31 also known as %i0-%i7 input registers t Use the %r0-%r31 names for now. Other names are used in procedure calls. –32 floating point registers %f0-%f31. Each reg. is single precision. Double prec. uses reg. pairs.

155 CSE360155 SPARC Assembly Language 5 u Assembly language –3-address operations - format different from book op src1, src2, dest !opposite of text E.g., add %r1, %r2, %r3 !%r3  %r1 + %r2 or %r2, 0x0004, %r2 !%r2  %r2 b-w-or 0x0004 –Contrast SPARC with MiPs (used in the book) t indirect address notation: @addr vs [addr] t operand order, especially the destination register t register notation: R2 vs. %r2 t branches

156 CSE360156 SPARC Assembly Language 6 –2-address operations: load and store ld [addr], %r2 ! %r2  M[addr] st %r2, [addr] ! M[addr]  %r2 –Use set to put an address (a label, a symbolic constant) into a register, followed by ld to load the data itself. set x_m, %r1 !put addr x_m into %r1 ld [%r1],%r2 !use addr in %r1 to load %r2

157 CSE360157 SPARC Assembly Language 7 u Immediate values: operand is not an address, but a value E.g., add %rs, siconst 13, %rd !%rd  %rs+const -4096 to 4095 t Immediate value coded as 13 bit 2’s complement. Range is, then, -2 12 …2 12 -1 or -4096 to 4095.  Immediate values can be specified in decimal, hexadecimal, octal, or binary. E.g., add %r2, 0x1A, %r2 t Constant is coded into instruction itself, therefore available after fetching the instruction (no extra trip to memory for an operand). t On SPARC, no special notation for differentiating constants from addresses because no ambiguity in a load/store architecture.

158 CSE360158 SPARC Assembly Language 8 u Synthetic Instructions: assembler translates one “instruction” into one or more machine instructions. –set : used to load a 32-bit signed integer constant into a register. Has 2 operands - 32 bit value and register number. How does that fit into a 32 bit instruction? E.g., set iconst 32, %rd set -10, %r3 set x_m, %r4 set ’=’, %r8 –clr %rd : used to set all bits in a register to 0. How? –mov %rs, %rd : copies a register. –neg %rs, %rd : copies the negation of a register.

159 CSE360159 SPARC Assembly Language 9 –Operand sizes t double word = 8 bytes, word = 4 bytes, half word = 2 bytes, byte = 8 bits. Recall memory alignment issues. set x_m, %r2 !Put addr x_m in %r2 ld [%r2], %r1 !load word ldsb [%r2], %r1 !load byte, sign extended ldub [%r2], %r1 !load byte, extend with 0’s st %r1, [%r2] !store word, addr is mult of 4 stb %r1, [%r2] !store byte, any address sth %r1, [%r2] !store half word, address is even – Characters use 8 bits t ldub to load a character t stb to store a character

160 CSE360160 SPARC Assembly Language 10 –Traps : provides initial help with I/O, also used in operating systems programming.  ta 0 : terminate program  ta 1 : output ASCII character from %r8  ta 2 input ASCII character into %r8  ta 4 : output integer from %r8 in unsigned hexadecimal  ta 5 : input integer into %r8, can be decimal, octal, or hex E.g., set ’=’, %r8 !put ’=’ in %r8 ta 1 !output the ’=’ ta 5 !read in value into %r8 mov %r8, %r1 !copy %r8 into %r1 set 0x0a, %r8 !load a newline into %r8 ta 1 !output the newline

161 CSE360161 SPARC Assembly Language 12 –Quick review of instructions so far:  ld [addr], %rd! %rd  M[addr]  st %rd, [addr]! M[addr]  %r2 t op %rs1, %rs2, %rd! op is ALU op  op %rs, siconst 13, %rd! %rd  %rs op const  set siconst 32, %rd! %rd  const t ta #! trap signal –Have actually seen many more variants, e.g., ldub, ldsb, sth, clr, mov, neg, add, sub, smul, sdiv, umul, udiv, etc. Can evaluate just about any simple arithmetic expression.

162 CSE360162 Review: Sparc Loads, Stores.data x_m:.word 0xa1b2c3d4.skip 12.text set x_m, %r2 ld [%r2], %r3 ldsb [%r2], %r4 ldub [%r2], %r5 st %r3, [%r2+4] sth %r3, [%r2+8] stb %r3, [%r2+12] ta 0 After this runs, what values are in %r2-5, and memory locations starting at byte address x_m?

163 CSE360163 Flow of Control 1 u In addition to sequential execution, need ability to repeatedly and conditionally execute program fragments. –High level language has: while, for, do, repeat, case, if-then-else, etc. –Assembler has if, goto. –Compare: high level vs. pseudo-assembler, implementation of f=n! f = 1 i = 2 loop: if (i > n) goto done f = f * i i = i + 1 goto loop done:... f = 1; i = 2; while (i <= n) { f = f * i; i = i + 1; }

164 CSE360164 Flow of Control 2 –Branch -- put a new address in the program counter. Next instruction comes from the new address, effectively, a “goto”. –Unconditional branch  (book) BRANCH addr ! PC  addr  (SPARC) ba addr ! PC  addr –Conditional branch  (book) BRcc R1, R2, target “if R1 cc R2 then PC  target” and cc is comparison operation (e.g., LT is , GE is , etc.)

165 CSE360165 Flow of Control 4 t Other conditions (from text, very similar to MIPS) t Can implement high level control structures now. –Factorial example, using the book’s assembly language: LOADR1,#1; R1 = f = 1 LOADR2,#2; R2 = i = 2 LOADR3, n; R3 = n loop:BRGTR2,R3,done; branch if i > n MPYR1,R1,R2; f = f * i ADDR2,R2,#1; i = i + 1 BRANCHloop; goto loop done:STOREf,R1; f = n!

166 CSE360166 Flow of Control 3 u Evaluating conditional branches –Evaluate condition –If condition is true, then PC  target, else PC  PC+1 Consider changes to the fetch-execute cycle given earlier for accumulator machine. Do data paths need to change? New control paths? New opcodes? New instruction formats? Consider changes to the fetch-execute cycle given earlier for accumulator machine. Do data paths need to change? New control paths? New opcodes? New instruction formats?

167 CSE360167 Flow of Control 5 u Condition Codes –Book’s assembly language has 3-address branches. SPARC uses 1-address branches. Must use condition codes. –Non-MIPS machines use condition codes to evaluate branches. Condition Code Register (CCR) holds these bits. SPARC has 4-bit CCR. –N: Negative, Z: Zero, V: Overflow, C: Carry. All are shown in a trace, or in the reg command under ISEM. –Condition codes are not changed by normal ALU instructions. Must use special instructions ending with cc, e.g., addcc.

168 CSE360168 ALU Hardware 1 u Recall the half-adder –Full-adder adds three single digit binary numbers. Results in a sum, and a carry out. FA xy c out c in Sum    xy c out c in Sum C in XYSumC out 00000 00110 01010 01101 10010 10101 11001 11111

169 CSE360169 ALU Hardware 2 u Now cascade the full adder hardware u How are CCR bits set? (Above is a ripple-carry adder.) –C-bit = C out –V-bit = C out  C n-1 –Z-bit =  (rz n-1  rz n-2  rz n-3 ...  rz 0 ) –N-bit = rz n-1 FA 0 register xregister y register z FA c out FA

170 CSE360170 Flow of Control 6.text start: set 1, %r2 set 0xFFFFFFFE, %r1! –2 in 32-bit 2’s comp cc_set: subcc %r1, %r2, %r3! r3<= -2-1 end: ta 0 ISEM> reg ----0--- ----1--- ----2--- ----3--- ----4--- ----5--- ----6--- ----7--- G 00000000 fffffffe 00000001 00000000 00000000 00000000 00000000 00000000 O 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 L 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 I 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 PC: 08:00002028 nPC: 0000202c PSR: 0000003e N:0 Z:0 V:0 C:0 cc_set : subcc %g1, %g2, %g3 ISEM> trace ----0--- ----1--- ----2--- ----3--- ----4--- ----5--- ----6--- ----7--- G 00000000 fffffffe 00000001 fffffffd 00000000 00000000 00000000 00000000 O 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 L 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 I 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 PC: 08:0000202c nPC: 00002030 PSR: 00b0003e N:1 Z:0 V:0 C:0

171 CSE360171 Flow of Control 7 –Setting the condition codes t Regular ALU operations don’t set condition codes.  Use addcc, subcc, smulcc, sdivcc, etc., to set condition codes. –Consider subcc %r1, %r2, %r0 %r1%r2NZVC 10 01 11 Do the values in the CCR tell us anything about the relationship between %r1 and %r2?

172 CSE360172 Flow of Control 8 –Branches use logic to evaluate CCR (SPARC) OperationAssembler SyntaxBranch Condition Branch always batarget 1 (always) Branch never bntarget 0 (never) Branch not equal bnetarget ZZ Branch equal betarget Z Branch greater bgtarget  (Z  (N  V)) Branch less or equal bletarget (Z  (N  V)) Branch greater or equal bgetarget  (N  V) Branch less bltarget N  V Branch greater, unsigned bgutarget  (C  Z) Branch less or equal, unsigned bleutarget C  Z Branch carry clear bcctarget CC Branch carry set bcstarget C Branch positive bpostarget NN Branch negative bnegtarget N Branch overflow clear bvctarget VV Branch overflow set bvstarget V

173 CSE360173 Flow of Control 9 –Setting Condition Codes (continued)  Synthetic instruction cmp %rs1, %rs2 –Sets CCR, but doesn't modify any registers. –Implemented as subcc %rs1, %rs2, %g0 t Back to the factorial example (SPARC) set 1, %r1! %r1 = f = 1 set 2, %r2! %r2 = i = 2 set n, %r3! Get loc of n ld [%r3], %r3! Put n in %r3 loop:cmp %r2, %r3! Set CCR (i?n) bg done! i > n done nop! Branch delay umul %r1, %r2, %r1! f = f * i add %r2, 1, %r2! i = i + 1 ba loop! Goto loop nop! Branch delay done:set f, %r3! Get loc of f st %r1, [%r3]! f = n!

174 CSE360174 Flow of Control 10 –Branch delay slots: unique to RISC architecture t Non-technical explanation: processor is running so fast, it can’t make a quick turn. –Instruction following branch is always executed. t Technical explanation: the efficiency advantage of pipelining is greater if the following instruction, which has almost completed execution, is allowed to complete. t Compilers take advantage of branch delay slots by putting a useful instruction there if possible.  For our purposes, use the nop (no operation) instruction to fill branch delay slots. Beware! Forgetting the nop will be a large source of errors in your programs!

175 CSE360175 High Level Control Structures 1 u Converting high level control structures –You get to be the “compiler”. t Some compilers convert the source language (C, Pascal, Modula 2, etc.) into assembly language and then assemble the result to an object file. GNU C, C++ do this to GAS (Gnu Assembler). –if-then-else, while-do, repeat-until are all possible to create in a structured way in assembly language.

176 CSE360176 High Level Control Structures 2 u General guidelines –Break down into independent (or nested) logical units –Convert to if/goto pseudo-code. –Mechanical, step-by-step, non-creative process f=1 i=2 loop: if (i>n) goto done f = f*i i = i+1 goto loop done:... f = 1; for (i=2; i<=n; i++) f = f * i;

177 CSE360177 High Level Control Structures 3 t if-then-else if (a<b) c = d + 1; else c = 7; t if/goto if (a >= b) goto else c = d + 1 goto end else: c = 7 end: init: set a, %r2 ! get &a into r2 ld [%r2], %r2 ! get a into r2 set b, %r3 ! get &b into r3 ld [%r3], %r3 ! get b into r3 if: cmp %r2, %r3 ! a ?? b (want >=) bge else ! a >= b, do then nop set d, %r5 ! get &d into r5 ld [%r5], %r5 ! get d into r5 add %r5, 1, %r4 ! r4 <- d+1 ba end nop else: set 7, %r4 ! get 7 into r4 end: set c, %r5 ! get &c into r5 st %r4, [%r5] ! c <- r4

178 CSE360178 High Level Control Structures 4 u while loops: while (a<b) a = a+1; c = d; u if/goto: whle:if (a>=b) goto done body:a = a+1 goto whle done:c = d init: set a, %r4 ! get &a into r4 ld [%r4], %r2 ! get a into r2 set b, %r3 ! get &b into r3 ld [%r3], %r3 ! get b into r3 whle: cmp %r2, %r3 ! a ?? b (want >=) bge done ! a >= b skip body nop body: add %r2, 1, %r2 ! r2 = a + 1 st %r2, [%r4] ! a = a + 1 ba whle ! repeat loop body nop done: set c, %r5 ! get &c into r5...

179 CSE360179 High Level Control Structures 5 t repeat-until loops: repeat … until (a>b) t if/goto: repeat: … if (a<=b) goto repeat nop

180 CSE360180 High Level Control Structures 6  Complex condition if((a =c)) … if((a =c)) … u These can be combined and used in if/else or while loops.

181 CSE360181 Flow of Control 11 –Optimizing code: change order of instructions, combine instructions, take advantage of branch delay slots.  Factorial example again. ( for i:=n downto 1 do… ) t Reduced 7 instructions in loop to just 4. t (You gain no advantage if you optimize code in your labs.) set 1, %r1 ! %r1=f=1 set n, %r2! Get loc of n ld [%r2], %r2! Put n in %r2 loop:umul %r1, %r2, %r1! f=f*n subcc %r2, 1, %r2! Decrement n bg loop! Repeat nop! Branch delay set f, %r3! Get loc of f st %r1, [%r3]! f=n!

182 CSE360182 Synthetic Instructions u Remember lab0?.data x_m:.word 0x42 y_m:.word 0x20 z_m:.word 0.text start: set x_m, %r2 ld [%r2], %r2 set y_m,%r3 ld [%r3], %r3 and so on… Suppose you gave this command to ISEM (after loading): ISEM> dump start start 05 00 00 10 84 10 a0 00 c4 00 80 00 07 00 00 10 Could you find the set instruction?

183 CSE360183 Instruction Encodings 1 u First, Instruction Encoding is how instructions are assembled –All instructions must fit into 32 bits.  Register-register: op=10, i=0  Register-immediate: op=10, i=1  Floating point: op=10, i=0

184 CSE360184 Instruction Encodings 2  Call instructions: op=01  Branch instructions: op=00, op2=010  SETHI instructions: op=00, op2=100  Ex.: add %r2, %r3, %r4 in hexadecimal: 88008003 a

185 CSE360185 Decoding an Instruction 05 00 00 10 16 0000 0101 0000 0000 0000 0000 0001 0000 2 Instruction Group (bits 30:31) = 00 Destination Register (bits 25:29) = 00010 Op Code (bits 22:24) = 100 Constant (bits 0:21) = 0000000000000000010000 Meaning: sethi 0x10, %r2 %r2 <-- 00000000000000000100000000000000 (0x4000)

186 CSE360186 Understanding SET Synthetic Usually used to put the value of an address in memory into a register. For example, set 0x4004, %r3 Can do neither ‘add %r0, 0x4004, %r3’ nor ‘or %r0, 0x4004, %r3’. Why not? SET is a synthetic instruction which may be implemented in two steps. #2 #1 Machine language encoding for 'set 0x4004, %r3'

187 CSE360187 SET Synthetic Instruction u set iconst, rd sethi %hi(iconst), rd or rd, %lo(iconst), rd --or-- sethi %hi(iconst), rd --or-- or %g0, iconst, rd

188 CSE360188 SPARC Assembly Language  Memory alignment:.align 4 –Used when mixing allocations of bytes, words, halfwords, etc. and need word boundary alignment  Reserve bytes of space:.skip 20 –Useful for allocating large amounts of space (e.g., arrays)  Create a symbolic constant:.set mask, 0x0f –Can now use the word “mask” anywhere we could use the constant 0x0f previously

189 CSE360189 SET and Symbolic Addresses  C-style example of pointer data type charx;// object of type character char *ptr;// pointer to character type ptr = &x;// ptr has address of x (points to x) *ptr = ‘a’;// store ‘a’ at address in ptr  Assembly language equivalent.data x_m:.byte 0 ! reserve character space; x_m = &x; [x_m] = x.align 4 ! align to word boundary ptr_m:.word 0 ! pointer variable; [ptr_m] = ptr.text set x_m, %r1! get address x_m into %r1 set ptr_m, %r2! get address ptr_m into %r2 st %r1, [%r2]! make [ptr_m] point to [x_m] set ’a’, %r3! put character ‘a’ into r3 set ptr_m, %r2! get address ptr_m into %r2 ld [%r2], %r1! get address [ptr_m], i.e. x_m, into %r1 stb %r3, [%r1]! store ‘a’ at address [ptr_m], i.e., ptr x_m ptr_m ‘a’ x_m, i.e., addr of x x_m: ptr_m: r1 r2 r3

190 CSE360190 Bitwise Operations 1 u Bit Manipulation Instructions –Bitwise logical operations t and %rs1, %rs2, %rd 10010011… (32 bits) 01111001… t or %rs1, %rs2, %rd 10010011… (32 bits) 01111001… t xor %rs1, %rs2, %rd 10010011… (32 bits) 01111001…

191 CSE360191 Bitwise Operations 2 t andn %rs1, %rs2, %rd 10010011… (32 bits) 01111001…  orn %rs1, %rs2, %rd 10010011… (32 bits) 01111001… t not %rs, %rd 10010011… (32 bits)  Recall the cc operations, so andcc, orcc, etc. are available. (However, there is no notcc ; use xnorcc.)

192 CSE360192 Bitwise Operations 3  For what kinds of things are these bit level operations used? Recall the synthetic operation clr, and mov. clr %r2  or %r0, %r0, %r2 mov %r2, %r3  or %r0, %r2, %r3 t Masking operations: Want to select a bit or group of bits from a set of 32. E.g., convert lower (or upper) to upper case: ‘ a ’ in binary is 01100001 ‘ A ’ in binary is 01000001 All we need to do is “turn off” the bit in position 5. and %r1, 0b11011111, %r1 will turn off that bit! t What if we subtract 32 (0b100000) from %r1? t What about converting upper to lower case?

193 CSE360193 Bitwise Operations 4 –Bitwise shifting operations  Shift logical left: sll %rs1, %rs2, %rd %rs1 : data to be shifted %rs2 : shift count %rd : destination register E.g., set 0xABCD1234, %r2 sll %r2, 3, %r3 %r2: 1010 1011 1100 1101 0001 0010 0011 0100 %r3: 0101 1110 0110 1000 1001 0001 1010 0000 t sll is equivalent to multiplying by a power of 2 (barring overflow). (In the decimal system, what’s a shortcut for multiplying by a power of ten?)

194 CSE360194 Bitwise Operations 5  Shift Logical Right: srl %rs1, %rs2, %rd –Shifts right instead of left, inserting zeros.  Arithmetic shifts: propagate the sign bit when shifting right, e.g., sra. (Left shift doesn't change.) –Almost equivalent to dividing by a power of 2. t Rotating shifts: Bits that would have gone into the bit bucket are shifted in instead. (E.g., rr, rl) –Rotate not implemented in SPARC

195 CSE360195 Addressing Modes 1 u Addressing Modes –How do we specify operand values? t In a register, location is encoded in the instruction. t As a constant, immediate value is in the instruction. t In memory, operand is somewhere in memory, location may only be known at runtime. –Memory operands: t Effective address: actual location of operand in memory. This may be calculated implicitly (e.g., by a displacement in the instruction) or may be calculated by the programmer in code.

196 CSE360196 Addressing Modes 2 –Summary of addressing modes:

197 CSE360197 Addressing Modes 3 –Memory Direct addressing t Entire address is in the instruction (not in SPARC). E.g., accumulator machine: each instruction had an opcode and a hard address in memory. –Can’t be done on SPARC because an address is 32 bits, which is the length of an instruction. No room for opcodes, etc. Can be done in CISC because multi-word instructions are permitted. –Memory Indirect addressing t Pointer to operand is in memory. Instruction specifies location of pointer. Requires three memory fetches (one each for instruction, pointer, and data). Not in RISC machines because instruction is too slow; such an instruction would cause its own register interlock!

198 CSE360198 Addressing Modes 4 u Register Indirect addressing –Register has address of operand (a pointer). Instruction specifies register number, effective address is contents of register..data n_m:.word 5 ; initialize n to 5.text set n_m, %r1 ; %r1 has n_m, pointer to n ld [%r1], %r3 ; fetch n into %r3 –Simulating Register Indirect addressing on SPARC t SPARC doesn't truly have register indirect addressing. t Assembler converts ‘st %r2, [%r1]’ into ‘st %r2, [%r1+%r0]’

199 CSE360199 Addressing Modes 5 t Ex.: sum up array of integers:.data n_m:.word 5! Size of array a_m:.word 4,2,5,8,3! 5 word array sum_m:.word 0! Sum of elements b_m:.skip 5*4! another 5 word array.text clr %r2! r2 will hold sum set n_m, %r3! r3 points to n ld [%r3], %r3! r3 gets array size set a_m, %r4! r4 points to array a loop:ld [%r4], %r5! Load element of a into r5 add %r5, %r2, %r2! sum = sum + element add %r4, 4, %r4! Incr ptr by word size subcc %r3, 1, %r3! Decrement counter bg loop! Loop until count = 0 nop! Branch delay slot set sum_m, %r1! r1 points to sum st %r2, [%r1]! Store sum ta 0! done 05 4 3 2 1 a_m a_m+4 a_m+8 a_m+12 a_m+16 r2 r3 r4 r5 loop loop+1 loop+2 loop+3 loop+4 5 n_m a_m a_m+4 a_m+8 a_m+12 a_m+16 sum_m 4 2 5 8 3

200 CSE360200 Register Indexed & Displaced Recall these Assembler directives  Reserve bytes of space:.skip 20  Create a symbolic constant:.set offset, 0x16 Register Indexed and Displaced addressing modes help us work with pointers, arrays, and records in assembly language.

201 CSE360201 Addressing Modes 7 –Register Indexed addressing t Suitable for accessing successive elements of the same type in a data structure.  Ex.: Swap elements A[i] and A[k] in array t Effective address calculations! A A+4 A+8 A+12 0010010 A 1001000 r2 r3 r4 r7 r8 after sll <-

202 CSE360202 Addressing Modes 8 u Array mapping functions: used by compilers to determine addresses of array elements. –Must know upper bound, lower bound, and size of elements of array. t Total storage = (upper - lower + 1)*element_size t Address offset for element at index k = (k - lower)*element_size Address (byte) offset for A[3] = (3-0)*4 = 12 This is for 1 dimensional arrays only!

203 CSE360203 Addressing Modes 9 u 1D array mapping functions: Want an array of n elements, each element is 4 bytes in size, array starts at address arr. –Total storage is 4n bytes –First element is at arr+0 –Last element is at arr+4(n-1) –k th (k can range from 0…n-1) element is at arr+4k. Array uses zero-based indexing.

204 CSE360204 Addressing Modes 10 u 2D array mapping functions: must linearize the 2D concept; e.g., map the 2D structure into 1D memory. –Convert into 1D array in memory

205 CSE360205 Addressing Modes 11 u 2 ways to convert to 1D –Row major order (Pascal, C, Modula-2) stores first by rows, then by columns. E.g., –Column major order (FORTRAN) stores first by columns then by rows. E.g.,

206 Addressing Modes u Row major 2D array mapping function: u Given an array starting at address arr, that is x rows by y columns, each element is m bytes in size, and indices start at zero, then element (i, j) may be found at location: CSE360206 Offset to A (0,2) = (5 * 0 + 2) * element size Offset to A (0,2) = (5 * 0 + 2) * element size arr + (y  i + j)  m

207 CSE360207 Addressing Modes 12 –3D array mapping function: natural extension of 2D function. Store by row, then column, then depth. –Array starting at arr with x rows, y columns, depth z, m element size. Element (i, j, k) is found at location: arr + (z  y  i + j) + k)  m +0 +1 +2+4+6+8 +3+5+7+9 +10+12+14+16+18 1,0,0

208 CSE360208 Addressing Modes 15 –Displacement Addressing t Suitable for accessing the individual fields of record data structures. Each field can be of a different type.  Use.set directive to establish offsets to fields within records. Then use displacement addressing to access those fields.

209 CSE360209 Addressing Modes 16 t Ex.: Add 1 to the age field in a person record t Problem: alignment in memory. May have to waste some space in the person record in order to have the integer fields align on a word boundary.

210 CSE360210 Addressing Modes 17 –Auto-increment and Auto-decrement addressing t SPARC does not support these modes. They may be simulated using register indirect addressing followed by an add or subtract of the size of the element on that register. t Useful for traversing arrays forward (auto-increment) and backward (auto-decrement). Also useful for stacks and queues of data elements.

211 CSE360211 Subroutines 1 u Subroutine (also function, method, procedure, or subprogram) –a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code. u Advantages of subroutines –reducing the duplication of code in a program –enabling reuse of code across multiple programs –decomposing complex problems into simpler pieces –improving readability of a program –hiding or regulating part of the program Requires little hardware support, mostly protocols and conventions to handle parameters.

212 CSE360212 Subroutines 2 u Terminology –Caller: the code (which could be a subroutine itself) which invokes the subroutine of interest –Callee: the subroutine being invoked by the caller –Function: subroutine that returns one or more values back to the caller and exactly one of these values is distinguished as the return value –Return value: the distinguished value returned by a function

213 CSE360213 Subroutines 3 u Terminology (continued) –Procedure: a subroutine that may return values to the caller (through the subroutine’s parameter(s)), but none of these values is distinguished as the return value –Return address: address of the subroutine call instruction –Parameters: information passed to/from a subroutine (a.k.a. arguments) –Subroutine linkage: a protocol for passing parameters between the caller and the callee

214 CSE360214 Subroutines 4 u Calling a subroutine –Assembly language syntax for calling a subroutine call label nop –Must change the program counter (as in a branch instruction) however, we must also keep track of where to resume execution after the subroutine finishes. Call instruction handles this atomically (i.e., without interruption) by: %r15  #PC (PC  #nPC) nPC  label

215 CSE360215 Subroutines 4 u Returning from a subroutine –Assembly language syntax for returning from a subroutine retl nop u Again, must change the program counter to return to an instruction after the one that called the subroutine. The address of the instruction that called it was saved in %r15, and we must skip over the branch delay slot as well. So, this is accomplished by: nPC  %r15+8

216 CSE360216 Subroutines 5 u Parameter passing: 2 approaches –Register based linkage: pass parameters solely through registers. Has the advantage of speed, but can only pass a few parameters, and it won’t support nested subroutine calls. Such a subroutine is called a leaf subroutine. –Stack based linkage: pass parameters through the run-time stack. Not as fast, but can pass more parameters and have nested subroutine calls (including recursion).

217 CSE360217 Register-based Linkage 1 –Subroutine linkage : t Startup Sequence: load parameters and return address into registers, branch to subroutine. t Prologue: if non-leaf procedure then save return address to memory, save registers used by callee. t Epilogue: place return parameters into registers, restore registers saved in prologue, restore saved return address, return. t Cleanup Sequence: work with returned values

218 CSE360218 Register-based Linkage 2 –Example: Print subroutine..text main:set1, %r1! Initialize r1 and r2 set3, %r2 mov%r1, %r8! Print %r1 callprint nop mov%r2, %r8! Print %r2 callprint nop add%r1, %r2, %r8! Do our calculation callprint! Print the result (expect ‘4’) nop ta0 print:set‘0’, %r1! Ascii value of zero or%r8, %r1, %r2! Treat r8 as parameter mov%r2, %r8! Move into output register ta1! Output character mov‘\n’, %r8 ta1! Output end of line (newline) retl! Return nop t What’s wrong with the above code?

219 CSE360219 Register-based Linkage 3 –Which registers can leaf subroutines change? t Convention for optimized leaf procedures: t The subroutine must not use the value in any other register except to save it to memory somewhere and restore it before returning to the caller. t Problem: how can a subroutine call another subroutine? How can a subroutine call itself?

220 CSE360220 Register-based Linkage 4 –Example: procedure to print linked list of ints. nop

221 CSE360221 Parameter Passing 1 –Review of parameter passing mechanisms: t Pass by value copy: parameters to subroutine are copies upon which the subroutine acts. t Pass by result copy: parameters are copies of results produced by the subroutine. t Pass by reference copy: parameters to subroutine are (copies of) addresses of values upon which the subroutine acts. Callee is responsible for saving each result to memory at the location referred to by the appropriate parameter. t Hybrid: some parameters passed by value copy, some by result copy, and/or some by reference copy. Callee is responsible for saving results for reference parameters.

222 CSE360222 Parameter Passing 2 –Parameter passing notes: t Array or record parameters typically are passed by reference copy (efficiency reasons). Primitive data types may be passed either way. t Conventions among languages allows any language to call functions in any other language: –Pascal: VAR parameters are passed by reference copy; all others are passed by value copy. –C: all parameters are passed by value copy. Must explicitly pass a pointer if you want a reference parameter. –C++: like Pascal, can pass by value or reference copy. –FORTRAN: all things passed by reference copy (even constants). –ADA: pass by value/result copy.

223 CSE360223 Parameter Passing 3.text ! Example 10.1 of Lab Manual ! pr_str – print a null terminated string ! Parameters: %r8 – pointer to string (initially) ! ! Temporaries: %r8 – the character to be printed ! %r9 – pointer to string ! pr_str: mov %r8, %r9 ! we need %r8 for the “ta 1” below pr_lp: ldub [%r9], %r8 ! load character cmp %r8, 0 ! check for null be pr_dn nop ta 1 ! print character ba pr_lp inc %r9 ! increment the pointer (in ! branch delay slot) pr_dn: retl nop

224 CSE360224 Parameter Passing 4 t Summary from text (p. 220) –Pass by value copy: For small “in” parameters. Subroutines cannot alter the originals whose copies are passed as parameters. –Pass by value/result copy: For small “in/out” parameters. Caller’s cleanup sequence stores values of any “in/out” parameters. –Pass by reference copy: for “in/out” parameters of all sizes, and large “in” parameters. “Out” values are provided by changing memory at those addresses. (Note: pass by reference copy is passing an address by value copy.)

225 CSE360225 Parameter Passing 5 –Write Sparc code for the caller and callee for the following subroutine using register based parameter passing ! global_function Integer subchr (A, B, C) ! Substitutes character C for each B in string [A], ! and returns count of changes. ! ! // In comments, "[A+index]" is denoted by "ch". ! index = 0 ! count = 0 ! LOOP: if [A+index]=0 go to END // while (ch != 0) { ! if [A+index]  B go to INC // if (ch == B) { ! [A+index]=C // ch = C; ! count=count+1 // count++; } ! INC: index=index+1 // index++; ! go to LOOP // } ! END:.data! data section C_m:.byte ’I’ ! parameter C B_m:.byte ’i’ ! parameter B A_m:.asciz "i will tip"! parameter A.align 4 R_m:.word 0! for storing result count Assume

226 CSE360226 Stack-based Linkage 1 u Stack based linkage –Advantages t Permits subroutines to call others. t Allows a larger number of parameters to be passed. t Permits records and arrays to be passed by value copy. t Saving of registers by callee is “built-in”. t A way for callee to reserve memory for other uses is “built-in”, too. –Disadvantages t Slower than register based t More complex protocol –Why a stack? t Subroutine calls and returns happen in a last-in first-out order (LIFO). Also known as a runtime stack, parameter stack, or subroutine stack.

227 CSE360227 Stack-based Linkage 2 t Items “saved” on the stack in one activation record –Parameters to the subroutine –Old values of registers used in the subroutine –Local memory variables used in subroutine –Return value and return address  Say A() calls B(), B() calls C(), and C() calls A()

228 CSE360228 Stack-based Linkage 3 –Stack based linkage parameter passing convention t Startup sequence: –Push parameters –Push space for return value t Prologue –Push registers that are changed (including return address) –Allocate space for local variables t Epilogue –Restore general purpose registers –Free local variable space –Use return address to return t Cleanup Sequence –Pop and save returned values –Pop parameters

229 CSE360229 Stack-based Linkage 4 –Stack based parameter passing example:  Register %r14  %sp  stack pointer –Invariant: Always indicates the top of the stack (it has the address in memory of the last item on stack, usually a word). –Moved when items are “pushed” onto the stack. –Due to interruptions (system interrupts (I/O) and exceptions), values stored above %sp (at addresses less than %sp) can change at any time! Hence, any access above %sp is unsafe!  Register %r30  %fp  frame pointer –Indicates the previous stack pointer. Activation record is from (some subroutine-specific number of words before) the %fp to the %sp. –Invariant: %fp is constant within a subroutine (after prologue).

230 CSE360230 Stack-based Linkage 5 –Stack based parameter passing example: t Want to implement the following subroutine (also a caller): ! global_function Integer subchr (A, B, C) ! Substitutes character C for all B in string A, ! and returns count of changes. ! ! // In comments, "*(A+index)" is denoted by "ch". ! index = 0 ! count = 0 ! LOOP: if *(A+index)=0 go to END // while (ch != 0) { ! if *(A+index)  B go to INC // if (ch == B) { ! *(A+index)=C // ch = C; ! count=count+1 // count++; } ! INC: index=index+1 // index++; ! go to LOOP // } ! END:.data! data section C_m:.byte ’I’ ! parameter C B_m:.byte ’i’ ! parameter B A_m:.asciz "i will tip"! parameter A.align 4 R_m:.word 0! for storing result count

231 CSE360231 Stack-based Linkage 6.data! data section C_m:.word ’I’ ! parameter C B_m:.word ’i’ ! parameter B A_m:.asciz "i will tip"! parameter A.align 4 ! align to word address stack:.skip 250*4! allocate 250 word stack bstak: ! point to bottom of stack R_m:.word 0! reserve for count.text ! Program’s one-time initialization start: set bstak, %sp! set initial stack ptr mov %sp, %fp! set initial frame ptr ! STARTUP SEQUENCE to call subchr() sub %sp, 16, %sp! move stack ptr set A_m, %r1! A is passed by reference st %r1, [%sp+4]! push address on stack set B_m, %r1! B is passed by value ld [%r1], %r1! get value of B st %r1, [%sp+8]! push parameter B on stack set C_m, %r1! C is passed by value ld [%r1], %r1! get value of C st %r1, [%sp+12]! push parameter C on stack ! SUBROUTINE CALL call subchr! make subroutine call nop! branch delay slot ! CLEANUP SEQUENCE ld [%sp], %r1! pop return value off stack add %sp, 16, %sp! pop stack set R_m, %r2! get address of R st %r1, [%r2]! store R...! the rest of the program Return value b stack: %sp -> %fp -> addr (a) c

232 CSE360232 Stack-based Linkage 7 ! SUBROUTINE PROLOGUE subchr: sub %sp, 32, %sp! open 8 words on stack st %fp, [%sp+28]! Save old frame pointer add %sp, 32, %fp! old sp is new fp st %r15, [%fp-8]! save return address st %r8, [%fp-12] ! Save gen. Register … ! Save r9-r13, omitted ! SUBROUTINE BODY ld_reg: ld [%fp+4], %r8! “pop” (load) addr of A ld [%fp+8], %r9! “pop” (load) value of B ld [%fp+12], %r10! “pop” (load) value of C clr %r12! count clr %r13! index loop: ldub [%r8+%r13], %r11! load a string chr cmp %r11, 0x0! is chr=null? be done! then go to done cmp %r11, %r9! is chr<>B? (branch delay) bne inc! then go to inc nop! branch delay slot stb %r10, [%r8+%r13] ! change chr to C add %r12, 1, %r12! increment count inc: add %r13, 1, %r13! increment index ba loop! do next chr nop! branch delay slot done: st %r12, [%fp+0]! “push” (store) count on stack ! EPILOGUE … ! Restore r9-r13, omitted ld [%fp-12], %r8 ! Restore r8 ld [%fp-8], %r15! get saved return address ld [%fp-4], %fp! Get old value of frame ptr add %sp, 32, %sp! Restore stack pointer retl! return to caller nop! branch delay slot c b addr (a) %sp -> %fp -> return addr old frame ptr Return value... %r9 %r8

233 CSE360233 Stack-based Linkage 8 u General Guidelines –Keep Startups, Cleanups, Prologues, and Epilogues standard (but not necessarily identical); easy to cut, paste, and modify. –Caller: leave space for return value on the TOP of the stack. –Callee: always save and restore locally used registers. –Pass data structures and arrays by reference, all others by value (efficiency).

234 CSE360234 Our Fourth Example Architecture u Motorola M68HC11 u Called “HC11” for short u Used in ECE 567, a course required of CSE majors u References: –Data Acquisition and Process Control with the M68HC11 Microcontroller, 2nd Ed., by F. F. Driscoll, R. F. Coughlin, and R. S. Villanucci, Prentice-Hall, 2000. –M68HC11 Processor Manual, on Carmen

235 CSE360235 Another Reference u Late in an academic term (such as now), you can hope to access on-line lecture notes from the Electrical and Computer Engineering course, ECE 265. u Visit http://www.ece.osu.edu u Under “Academic Program”, click on the link “ECE Course Listings”. u Find 265 and click on the link “Syllabus of this quarter”.

236 CSE360236 HC11 compared with Sparc (1) HC11Sparc CISCRISC, Load/Store Instruction encoding lengths vary (8 to 32 bits) Instruction encoding lengths constant (32 bits) About 316 instructionsAbout 175 instructions 4 16-bit user registers, one of which is divided into two 8- bit registers 32 32-bit user integer registers

237 CSE360237 HC11 compared with Sparc (2) HC11Sparc 8-bit data bus32-bit data bus 16-bit address bus32-bit address bus 8-bit addressable Instruction execution not overlapped Instruction execution overlapped in a pipeline

238 CSE360238 HC11 compared with Sparc (3) u A Strange Fact: The HC11 architecture “allows accessing an operand from an external memory location with no execution-time penalty.” [p. 27, M68HC11 Processor Manual] u Reason: The HC11 requirements state that the CPU cycle must be kept long enough to accommodate a memory access within one cycle. This seeming miracle is accomplished by keeping processor speed slow enough.

239 CSE360239 HC11 Programmer’s Model (1) 7 0 0 7 15 0 Accumulator AAccumulator B Accumulator D X Index Register Y Index Register Stack Pointer (SP) Program Counter (PC)

240 CSE360240 HC11 Programmer’s Model (2) 0 1 2 3 4 5 6 7 Condition Code Register (CCR) S X HI N ZVC Carry/Borrow Overflow Zero Negative I Interrupt Mask Half-Carry X Interrupt Mask Stop

241 CSE360241 HC11 Assembly Language Format (1) u Like Sparc, it is line-oriented. u A line may: –Be blank (containing no printable characters), –Be a comment line, the first printable character being either a semicolon (‘;’) or an asterisk (‘*’), or –Have the following format (“[] means an optional field”): [Label] Operation [Operand field] [Comment field]

242 CSE360242 HC11 Assembly Language Format (2) u Label: –begins in column 1, ending either with a space or a colon (‘:’) –Contains 1 to 15 characters –Case sensitive –The first character may not be a decimal digit (0-9) –Characters may be upper- or lowercase letter, digits 0- 9, period (‘.’), dollar sign (‘$’), or underscore (‘_’)

243 CSE360243 HC11 Assembly Language Format (3) u Operation: –Cannot begin in column 1 –Contains: t Instruction mnemonic, t Assembler directive, or t Macro call (we haven’t studied macro expansion in this course) u Operand field: –Terminated by a space or tab character, –So multiple operands are separated by commas (‘,’) without using any spaces or tabs

244 CSE360244 HC11 Assembly Language Format (4) u Comment field: –Begins with the first space character following the operand field (or following the operation, if there is no operand field) –So no special printable character is required to begin a comment field –But it appears to be conventional to begin a comment field with a semicolon (‘;’)

245 CSE360245 Prefixes for Numeric Constants EncodingHC11Sparc DecimalNo symbol Hexadecimal$0x Octal@0 Binary%0b

246 CSE360246 Assembler Directives (1) MeaningHC11Sparc Set location counter (origin) ORG.data or.text End of sourceENDDoesn’t have Equate symbol to a value EQU.set Form constant byteFCB.byte

247 CSE360247 Assembler Directives (2) MeaningHC11Sparc Form double byteFDB.half Form character string constant FCC.ascii Reserve memory byte or bytes RMB.skip

248 CSE360248 HC11 Addressing Modes u Immediate (IMM) u Extended (EXT) u Direct (DIR) u Inherent (INH) u Relative (REL) u Indexed (INDX, INDY)

249 CSE360249 Immediate (IMM) u Assembler interprets the # symbol to mean the immediate addressing mode u Examples –LDAA#10 –LDAA#$1C –LDAA#@17 –LDAA#%11100 –LDAA#’C’ –LDAA#LABEL

250 CSE360250 Extended (EXT) u Lack of # symbol indicates extended or direct addressing mode. These are forms of memory direct addressing, like SAM. u “Extended” means full 16-bit address, whereas “Direct” means directly to a low address, specified using only the least significant 8 bits of the address. u Examples –LDAA$2025 –LDAALABEL

251 CSE360251 Direct (DIR) u Examples –LDAA$C2 –LDAALABEL

252 CSE360252 Inherent (INH) u All operands are implicit (i.e., inherent in the instruction) u Examples: ABA, SBA, DAA u ABA means add the contents of register B to the contents of A, placing the sum in A (A + B  A) u SBA means A – B  A u DAA means to adjust the sum that got placed in A by the previous instruction to the correct BCD result; e.g., $09 + $26 yields $2F in A, then DAA changes this to $35.

253 CSE360253 Relative (REL) u Used only for branch instructions u Relative to the address of the following instruction (the new value of the PC) u Signed offset from -128 to +127 bytes u Examples –BGE-18 –BHS27 –BGTLABEL

254 CSE360254 Indexed (INDX, INDY) u Uses the contents of either the X or Y register and adds it to a (positive, unsigned) offset contained in the instruction to calculate the effective address u Example –LDAA4,X

255 CSE360255 Interrupts u When an interrupt is acknowledged, the CPU’s hardware saves the registers’ contents on the stack. An interrupt service routine ends with a(n) RTI instruction. This instruction automatically restores the CPU register values from the copies on the stack.

256 CSE360256 Condition Code Register (CCR) u It’s reasonably safe to say that every instruction that changes a register (A, B, D, X, Y, SP) affects the CCR appropriately. Unlike Sparc, there are no arithmetic instructions that do not set condition codes. u There do exist instructions that compare a register to a memory location by subtracting the memory contents from the register and throwing the result away, but setting the CCR (CMPA, CMPB, CPD, CPX, CPY).

257 CSE360257 HC11 Condition Code Register u The H bit is turned on by an 8-bit addition operation when there is a carry from the lower- order nibble into the higher-order nibble, that is to say, from bit 3 into bit 4. 0000 1111 +0000 1000 ------------- 0001 0111 1 0 0 0

258 CSE360258 HC11 Condition Code Register u The Z bit is turned on when the result is zero. u The N bit is turned on when the result is negative according to the appropriately-sized 2's complement encoding scheme. 0000 1010

259 CSE360259 HC11 Condition Code Register u The V bit is turned on when, under the appropriately-sized 2's complement interpretation of the two source operands and the result, the result is wrong. 0100 + 1100 ------- 0000 2’s Comp +4 -4 ---- 0 Simple Binary +4 +12 ---- 0?? Correct so V-bit is off Incorrec t so C-bit is on

260 CSE360260 HC11 Condition Code Register u The C bit is turned on when, under the simple binary interpretation of the two source operands and the result, the result is wrong. 0111 + 0111 ------- 1110 2’s Comp +7 ---- -2?? Simple Binary +7 ---- 14 Incorrec t so V-bit is on Correct so C-bit is off

261 CSE360261 Example HC11 Program u Problem: Produce the following waveforms on the three least significant bits (LSBs) of parallel 8-bit output Port B (mapped to $1004), where we name the bits X, Y, and Z in increasing order of significance (X is bit 0; Y is bit 1; Z is bit 2). 10 ms 20 ms 15 ms X Y Z

262 CSE360262 Example Source File, p. 1 STACK: EQU $00FF; set stack pointer PORTB: EQU $1004 ; set address of Port B ORG 0 DELAY1: FCB 10 ; set the waveform times DELAY2: FCB 20 ; for X, Y, and Z DELAY3: FCB 15

263 CSE360263 Example Source File, p. 2 ORG $E000; program starts at $E000 MAIN: LDS #STACK ; initialize stack pointer L0: LDAA #1 ; set X on Port B to 1 STAA PORTB LDAB DELAY1 ; delay for 10 ms L1: JSR DELAY_1MS DECB BNE L1

264 CSE360264 Example Source File, p. 3 LDAA #%00000010 ; set Y on Port B to 1 STAA PORTB LDAB DELAY2 ; delay for 20 ms L2: JSR DELAY_1MS DECB BNE L2 LDAA #%00000100 ; set Z on Port B to 1 STAA PORTB LDAB DELAY3 ; delay for 15 ms L3: JSR DELAY_1MS DECB BNE L3 BRA L0 ; continue to cycle

265 CSE360265 Example Source File, p. 4 DELAY_1MS: PSHB ; subr. to delay for 1 ms LDAB #198 DELAY: DECB BRN DELAY NOP BNE DELAY PULB RETURN: RTS ORG $FFFE ; initialize reset vector RESET: FDB MAIN END

266 CSE360266 Traps and Exceptions 1 u Traps, Exceptions, and Extended Operations –Other side of low level programming -- the interface between applications and peripherals –OS provides access and protocols

267 CSE360267 Traps and Exceptions 2 –BIOS: Basic Input/Output System t Subroutines that control I/O t No need for you to write them as application programmer t OS interfaces application with BIOS through traps (extended operations (XOPs))

268 CSE360268 Traps and Exceptions 3 –Where are OS traps kept? Two approaches: t Transient monitor: traps kept in a library that is copied into the application at link-time t Resident monitor: always keep OS in main memory; applications share the trap routines. t OS routines monitor devices. Frequently used routines kept resident; others loaded as needed.

269 CSE360269 Traps and Exceptions 4 –(Assuming a res. monitor) How to find I/O routines?  Store routines in memory, and make a call to a hard address. E.g., call 256 –When new OS is released, need to recompile all application programs to use different addresses. t Use a dispatcher –Dispatcher is a subroutine that takes a parameter (the trap number). Dispatcher knows where all routines actually are in memory, and makes the branch for you. Dispatcher subroutine must always exist in the same location. 2

270 CSE360270 Traps and Exceptions 5 t Use vectored linking –Branch table exists at a well known location. The address of each trap subroutine is stored in the table, indexed by the trap number. –On RISC, usually about 4 words reserved in the table. If the trap routine is larger than 4 words, can call the actual routine.

271 CSE360271 Traps and Exceptions 6 –Levels of privilege t Supervisor mode - can access every resource t User mode - limited access to resources t OS routines operate in supervisor mode, access is determined by bit in PSW (processor status word).  XOP (book’s notation) can always be executed, sets privilege to supervisor mode ( ta )  RTX (book’s notation) can only be executed by the OS, and returns privilege to user mode ( rett )

272 CSE360272 Traps and Exceptions 7 –Exceptions t Caused by invalid use of resource. E.g., divide by zero, invalid address, illegal operation, protection violation, etc. t Control transferred automatically to exception handler routine. Similar to trap or XOP transfer. t Exceptions vs. XOPs –XOPs explicit in code, exceptions are implicit –XOPs service request and return to application; exceptions print message and abort (unless masked). –On SPARC, trap table has 256 entries. t 0-127 are reserved for exceptions and external interrupts. 128- 255 are used for XOPs. Trap table begins at address 0x0000. Each entry is 4 instructions (16 bytes) long.

273 CSE360273 Traps and Exceptions 8 –Trap example: non-blocking read ta 3 t If there is nothing in the keyboard buffer, return with a message that nothing is there. Otherwise, put the character into register 8. –Status of the keyboard is kept in a memory location, as is the (one-character) keyboard buffer. Memory mapped devices.

274 CSE360274 Traps and Exceptions 9 –Trap execution: ta 3 t Calculate trap address: 3 * 16 + 0x0800 = 16 * (3 + 0x080) t Save nPC and PSW to memory –SPARC uses register windows –Assumes local registers are available t Set privilege level to supervisor mode t Update PC with trap address (and make nPC = PC + 4) (jumps to trap table)  Trap table has instruction ba ta3_handler t rett –Restores PC (from saved nPC value) and PSW (resets to user mode) –Returns to application program

275 CSE360275 Programmed I/O 1 u Programmed I/O –Early approach: Isolated I/O t Special instructions to do input and output, using two operands: a register and an I/O address. t CPU puts device address on address bus, and issues an I/O instruction to load from or store to the device.

276 CSE360276 Programmed I/O 2 Isolated I/O

277 CSE360277 Memory Mapped I/O t No special I/O instructions. Treat the I/O device like a memory address. Hardware checks to see if the memory address is in the I/O device range, and makes the adjustment. t Use high addresses (not “real” memory) for I/O memory maps. E.g., 0xFFFF0000 through 0xFFFFFFFF. CPU Memory I/O addr bus data bus read/write

278 CSE360278 Programmed I/O 3 –Advantages of each t Memory mapped: reduced instruction set, reduced redundancy in hardware. t Isolated: don’t have to give up memory address space on machines with little memory

279 CSE360279 Programmed I/O - UARTs t UARTs –Universal Asynchronous Receiver Transmitter –Asynchronous = not on the same clock. –Handshake coordinates communication between two devices. –A kind of programmed I/O. KeyboardUART 0 1 0 CPU. 0 01101010 serial parallel

280 CSE360280 UARTs 1 u UART registers –Control: set up at init, speed, parity, etc. –Status: transmit empty, receive ready, etc. –Transmit: output data –Receive: input data –All four needed for bi- directional communications, –Status/control, transmit / receive often combined. Why? Control Reg Status Reg Transmit Reg Receive Reg Transmit Logic Receive Logic Control bus Address bus Data bus

281 CSE360281 UARTs 2 u Memory mapped UARTs –Both memory and I/O “listen” to the address bus. The appropriate device will act based on the addresses. –Keyboards and Printers require three addresses (when addresses are not combined). –Modems require four. –(why?) UART 1 data UART 1 status UART 1 control UART 2 xmit UART 2 recv UART 2 status UART 2 control UART 3 xmit FFFF 0000 FFFF 0004 FFFF 0008 FFFF 000C FFFF 0010 FFFF 0014 FFFF 0018 FFFF 001C CPU MemoryUART1UART2 Control bus Address bus Data bus and so on

282 CSE360282 Programmed I/O 4 u Programmed I/O Characteristics: –Used to determine if device is ready (can it be read or written). –Each device has a status register in addition to the data register. –Like previous trap example, must check status before getting data. –Involves polling loops.

283 CSE360283 Programmed I/O – Polling Ex.: ta 2 handler (blocking keyboard input) u Can’t afford to wait like this. Computer is millions of times faster than a typist. Also, multi-tasking operating systems can’t wait. u Special purpose computers can wait. E.g., microwave oven controllers. u Must have a better way! Interrupts are the answer! Are you ready?... Are you ready now?... How about NOW?... Nope.. Not yet.. Hang on..

284 CSE360284 Interrupts and DMA transfers 1 u Programmed (polled) I/O used busy waiting. –Advantages: simpler hardware –Disadvantages: wastes time u Interrupts (IRQs on PCs) –I/O device “requests” service from CPU. –CPU can execute program code until interrupted. Solves busy waiting problems. –Interrupt handlers are run (like traps) whenever an interrupt occurs. Current application program is suspended.

285 CSE360285 Interrupts and DMA transfers 2 u Servicing an interrupt –I/O controller generates interrupt, sets request line “high”. –CPU detects interrupt at beginning of fetch/execute cycle (for interrupts “between” instructions). –CPU saves state of running program, invokes intrpt. handler. –Handler services request; sets the request line “low”. –Control is returned to the application program. Application Program : *Interrupt Detected* : Interrupt Handler Service Request : Clear Interrupt

286 CSE360286 Interrupts and DMA transfers 3 u Changes to fetch/execute cycle u Problems –Requires additional hardware in Timing & Control. –Queuing of interrupts –Interrupting an interrupt handler (solution: priorities and maskable interrupts) –Interrupts that must be serviced within an instruction –How to find address of interrupt handler Interrupt Pending? Save PC Save PSW PSW=new PSW PC=handler_addr PC -> bus load MAR INC to PC load PC YN

287 CSE360287 Interrupts and DMA transfers 4 u Example: interrupt driven string output –Want to print a string without busy waiting. –Want to return to the application as fast as possible I’m ready!

288 CSE360288 Trap handler implementation u Install trap handler into trap table –Buffer is like circular queue –only outputs, at most, one character disp_buf:.skip 256 ! buffers string to print disp_frnt:.byte 0 ! offset to front of queue disp_bck:.byte 0 ! offset to back of queue ta_6_handler: ! Copy str from mem[%r8] to mem[disp_buf+disp_bck] ! Disp_back = (disp_back+len(str)) mod 256 ! If display is ready ! If first char is not null, then output it ! Disp_frnt = (disp_frnt+1) mod 256 rett ! Return from trap Disp_buf: disp_frnt  disp_bck  newest byte Undisplayed byte Oldest byte

289 CSE360289 Interrupt handler implementation u This too outputs only one character at most, but when display becomes ready again, it generates another interrupt which invokes this routine! display_IRQ_handler: ! Save any registers used ! If disp_frnt != disp_bck (queue is not empty) ! Get char at mem[disp_frnt] ! If char is not null, then output it ! Disp_frnt = (disp_frnt+1) mod 256 ! Restore registers and set the request line “low” rett ! Return from trap u Uses the UART for transmission. I’m ready! CPU Memory

290 CSE360290 Interrupts and DMA transfers 5 u Problems with interrupt driven I/O t CPU is involved with each interrupt t Each interrupt corresponds to transfer of a single byte t Lots of overhead for large amounts of data (blocks of  512 bytes) MemoryCPU Device Controller Execute 10s or 100s of instructions per byte Transfer one word of data Interrupt Transfer one byte of data

291 CSE360291 Interrupts and DMA transfers 6 u DMA (Direct Memory Access) t Want I/O without CPU intervention t Want larger than one byte data transfers t Solution: add a new device that can talk to both I/O devices and memory without the CPU; a “specialized” CPU strictly for data transfers. Memory CPU Device Controller DMA Controller

292 CSE360292 Interrupts and DMA transfers 7 u Steps to a DMA transfer –CPU specifies a memory address, the operation (read/write), byte count, and disk block location to the DMA controller (or specify other I/O device). –DMA controller initiates the I/O, and transfers the data to/from memory directly –DMA controller interrupts the CPU when the entire block transfer is completed. u Problem –Conflicts accessing memory. Can either arbitrate access or get a more expensive dual ported memory system.


Download ppt "CSE3601 CSE 360: Introduction to Computer Systems Course Notes Bettina Bair"

Similar presentations


Ads by Google