Low-Level Programming

Contents

  • The CPU
  • Interrupts
  • The ROM-BIOS
  • Port Access
  • Memory
  • Video Graphics Adapter

  • information about the CPU The CPU

    The CPU can communicate with any part of the computer via Ports.   Each hardware device, inside or outside the computer, has a Port number assigned to it which the CPU calls on to access.  The Bus acts like a telephone line through which signals are sent.  Communication is a two-way affair.   Data can be sent to a Port number and data can be requested from a Port number.

    Please note: Ports are an integral part of low-level PC control, the Operating System's control programs generally place a security curtain around Port operations, but be careful when using direct Port access in your own programs.

    You must know what device you are communicating with and what type of values are expected by that device's Ports.  The BIOS is a safer mechanism for accessing hardware than direct Port access, although it is slower.  When programming hardware at a low-level, decide what type of access is required by your program at a given time and code for BIOS communication or direct Port access accordingly.   For example: When speed is not a pre-requisite, it would be better to use the BIOS to request a device's service.  An instance of this is at the initalisation or entry stage of your program to request that the BIOS send some graphics settings to the VGA card to set the video mode.  Where speed is the name of the game, direct hardware access is more appropriate.

    contents

    A Look Inside The CPU

    Registers

    Registers are the CPU's internal memory for holding data and instructions   General-purpose registers AX,BX,CX and DX are used as a temporary storage area.   Each is split into High and Low order halves, denoted by H and L. Segment registers are used by the CPU to access main memory CS points to a program, DS to that programs data, ES works as an additional placeholder to DS and SS is the Stack.   The Stack is used as a temporary placeholder for instructions.  It is used primarily with loops and control, but is also used to contain instructions that will be used at a later stage by the CPU, such as when an interrupt occurs.  These registers access main memory in 64kb blocks.  Offset registers are used in connection with segment registers to locate specific memory locations.  PC is used to hold the location of the next instruction to be executed.  SP and BP keep track of adittional data belonging to a program that needs future operating on.  SI and DI are used to move blocks of data around in memory.  Please note that there are other registers in the CPU, for example the Instruction Register (IR), the Address Register (AR) among others.

    Flags

    Flags are used to hold data such as the results of arithmetic or logic operations, CPU state information, interrupt information and other status type data.  There are usually nine flags, each being a seperate entity, although they are normally grouped together physically in the CPU;   that can be tested for a particular state.  Zero Flag (ZF), indicates a result of zero of equality.  Sign Flag (SF), indicates a negative or not equal to result.   Carry Flag (CF), indicates a carry to next position.  Auxiliary Flag (AF), indicates a carry from first four bits (for decimal calculations).  Overflow Flag (OF), indicates that a result is too large.  Parity Flag (PF), indicates either odd or even parity.   Direction Flag (DF) controls which direction repeated operations follow.   Interrupt Flag (IF), controls if interrupts are allowed at a particular time.  Trap Flag (TF), can cause the computer to generate a "trap" interrupt.  There may be more Flags, but these are the most common.

    The CPU
    contents

    information about Interrupts Interrupts

    There are a few different kinds of interrupt, but all exact the same action, allowing the CPU to temporarily suspend what it is currently processing, to switch to another operation initiated by the interrupt call.  The Stack, refered to earlier, in the CPU is used in conjunction with interrupts, to hold information being put aside by the calling of the interrupt.   Every component or device in the computer that can send an interrupt to the CPU has it's own unique number assigned to it.  For example: video has the interrupt number INT 10h, the mouse INT 33h, etc.

      The h denotes hexadecimal.

    For a list of INT numbers and there corresponding devices Click Here.

    1. Hardware Interrupts

    Issued by hardware, these call the CPU for attention when a device is ready for use, or has finished a particular operation.  An example of this is the keyboard interrupt INT 9h, which interupts the cpu twice each time a key is pressed and released.  Another example is the DMA (Direct Memory Addressing) Controller that can tell the CPU that it has finished sending a block of memory to Main memory and needs the starting address of the next memory block.

    2. Exception Interrupts

    Issued by hardware or the CPU itself.  Exception interrupts occur when something goes wrong, such as a divide-by-zero or a Stack overflow.  As you saw above, the flags in the CPU are used to test for staus information.  The flags can be used to determine if an exception has occured and issues and exception interrupt to the CPU accordingly.

    3. Software Interrupts

    Issued by Firmware or a particular manufacturter's embedded software in ROM chips, such as the BIOS.   These types of interrupts are used to request services from other devices and components.  Unlike hardware interrupts and exception interrupts, software interrupts are implemented intentionally and are pre-programmed to occur at a particluar time depending on the service required.

    4. Aplication Software Interrupts

    These are the type of interrupts us programmers are interested in most, because we can perform them.   Issued from software programs, these types of interrupts are used to access the BIOS, or other hardware devices, to request information and/or services.

    There are other types of interrupts that are issued by different operating systems and manufacturer components, depending on the type of P.C. and platform you are using, but the above types are the most common.

      Warning: Do not use interrupt calls in your programs unless you are sure of the consequences.

    contents

    What Happens When an Interrupt Occurs ?

    When an interrupt occurs and gets the attention of the CPU.  The CPU saves the stsus of the flags and the location of the next instruction from the Instruction register (IR) to be executed, which would have previously been executed had it not been for the interrupt call, in the segment registers and any adittional information is saved in the Stack.  The CPU then passes control to a program called an Interrupt Handler that, depending on the interrupt call issued, executes a corresponding list of instructions that are found by accessing the first 1024 bytes of main memory, called the Interrupt Vector Table (IVT), also known as the Interrupt Descriptor Table (IDT).   The CPU calculates the address of these instructions by multiplying the interrupt number by four.  These instructions are called an Interrupt Service Routine (ISR).  When the ISR has completed it's execution, the CPU regains control.  How it does this is the ISR's last instructions pop values off the stack and returns the flags.  These instructions are known as Interrupt Return (IRET) instructions.  The CPU then reads the segment registers to continue executing the instruction previously detained by the calling of the interrupt.  You don't really need to worry about this as a programmer, just acknowledge the fact that it happens each time the CPU responds to an Interrupt call.  Please note that some interrupts do not have a corresponding ISR and calling them from a program could affect the operation of your P.C.

    Sometimes the CPU can be made to ignore interrupts, this is used when critical data and instructions are being executed.   This is done by executing the Clear Interrupt enable flag (CLI).  The Non-Maskable Interrupt (NMI) however, cannot be disabled and is used to tell the CPU if something is drastically wrong with the P.C's opertation.

    You can think of interrupts as being the electrons that feed the nucleus (CPU), described by some as the driving-force behind the P.C's operation.  This in my opinion is very true.  So much of the computers' operation depends on interrupts.   You may be led to believe that with so many devices in the modern P.C. competing for resources, that the CPU would be interrupted out of use, but interrupts can and do occur thousands of times per second.  The internal clock alone interrupts the CPU 18 times a second and even this interrupt can be manuipulated in our programs to speed up or slow down the rate at which the CPU can execute instructions.  The instruction set of the CPU is actually built on interrupts.  If you look at any low-level code, such as assembly, you will more often than not see one or more interrupt calls in each function.

    contents

    information about the ROM BIOS The ROM BIOS

    The ROM BIOS (Read-Only Memory Basic Input/Output System) is a chip situated on the motherboard that stores hardware information about devices and components attqached to the P.C.  Using the BIOS may be slower than direct communication between our programs and a specific piece of hardware, but no knowlegde about the communication protocols, or even where a particular device may be situated in the P.C.  The BIOS provides all this inrformation in routines that can be accessed via interrupts.

    contents

    A Look Inside The ROM BIOS

    Start-up Routines

    When you switch your P.C. on, this part of the ROM BIOS gets the computer initialsed for interrupts by writing the interrupt vector table (IVT), which provides the correct interrupt handling routine, to handle interrupts when they occur.  The BIOS also checks that the computer is in proper working order.  Housekeeping routines set registers, load default settings and perform initialisation on devices belonging to the P.C.  The BIOS knows what hardware is connected to the computer and can test if these devices are present and working properly.  It can also check for new or previously undetected devices and list information about them in it's ROM Memory.   The BIOS does this by checking jumper switch settings to see what ports are open.  It also checks main memory.  The BIOS is loaded into high memory and any new devices (if any), called BIOS extensions, are loaded into standard memory reserved for new devices.  The Boot-strap program then looks for a boot record, a record of a previous boot-up sequence, on the P.C.s' fixed disks that will load the operating system.

    Service-Handling Routines

    These are employed to request information or make settings to the P.C.s' hardware devices.  These are Input/Output (I/O) services that gives the BIOS it's name.  The BIOS keeps track of the systems time and performs other services.  The strength of the BIOS is in the fact that using these services does not call for intimate knowledge of Port, memory or hardware operation.  To use the services of a device we can just ask the BIOS to do the work whereby any errors are handled by the BIOS, thus saving our programs from failure.

    Hardware Interrupt-Handling Routines

    This part of the BIOS takes requests from hardware and passes it to the Service-Handling Routines that carry out the request.  For example, pressing a key on the keyboard causes a hardware interrupt, which signals the CPU, the CPU then signals the Hardware Interrupt-Handler.  The Service-Handling Routines then map to the correct keyboard routines to output or otherwise process the inputed character.

    The ROM BIOS
    contents

    information about Port Access Port Access

    Every hardware device inside the PC has one or more ports, which are used to control communication between a particular device and the CPU.  Ports act like telephone numbers that can be called or signalled to request information from or send information to.  Using direct port access cuts out the overhead of interrupts and there is no need to involve the CPU or the ROM BIOS.  This means that this type of communication is faster than using interrupts, although the programmer must fully understand how to communicate with the particular device using its port number and how to use that device properly.  This type of access is best suited to changing device settings quickly without the involvement of the CPU.  Changing a port's value can have far running implications to routines and services operating with that port or that ports device.  Therefore, this method would be best suited to routines that need to change how a device works or uses values that are sent to it.  An example of this is changing the value of the palette register accessed through the palette index to change the three primary colour values red, green and blue; which control the palette of colours on the monitor.  Using port access to change the palette register will change the whole palette of colours on screen at once.  This is a fast way of setting palettes to suit image palettes in one operation.

    contents

    information about Memory Memory

    Hardware and device mapping information occupy memory addresses, especially in low memory.  All the interrupts for each device are stored in the first block of memory and are used by the BIOS.  It is possible to redirect or re-vector interrupts by grabbing the information from the particular device before it can look up the interrupt vector table.  An example of this is keyboard interrupts.  When a key is pressed on the keyboard, an interrupt is invoked that processes the character set and maps the output to the correct destination, i.e., the screen, printer, etc., directed by the BIOS.  By catching the keyboard press before the interrupt can be invoked, or re-vectoring the interrupt catching the keyboard press, it is possible to control what a future call to that particular interrupt will execute.  In effect, the programmer can cut out the use of the BIOS and the CPU altogether and carry out their own routine to process the keyboard press.  This can be used to control multiple simultaneous keyboard presses and releases on the keyboard with speed.  Another example of Direct Memory addressing is the use of blocks of memory as a buffer for hardware devices.  For example, the standard Video Graphics Adapter (VGA) card uses memory at address 0xa (in hex).  By accessing this memory directly, the programmer can print or plot values directly to the screen as that particular address maps directly to Video RAM (VRAM).  The sound card uses memory in the same way.  The DMA Controller can be programmed to queue sound files for later use involving the CPU only to re-assign the next block of memory.

      Placing values in unknown locations in memory is a great way of corrupting your data and programs.  Unless you are happy with the consequences, leave well enough alone.

    contents

    information about The VGA Card Video Graphics Adapter

    The Video Graphics Adapter (or Array) is an ageing standard for displaying graphics on the P.C.  The reason for it's decline in recent years has been the growth in popularity of 3d graphics and games.  The problem with the VGA standard is that it is too slow to cater for the power needed to support 3d.  The VGA is an add-on component and as with all add-ons it can only communicate with the CPU as fast (or as slow) as the BUS or line to the CPU can carry.  The AT bus was notoriously slow at delivering graphics.  PCI, is was recent attempt to address this, but, alas the advent of AGP (accelerated Graphics Port) has heralded the decline of VGA and the rise of 3d.  Of course we don't need to include the CPU every time we want to display graphics.  Plotting a pixel on the screen can be done by accessing Video memory directly, however when more complex shapes and models are needed, the CPU must be used for calculatation.  This is why most 3d cards have on-board processors to take some of the strain away from the CPU.  Anyway, back to VGA.  In the early days, before good graphics, programmer's had to cope with some very recalcitrant standards, CGA,EGA to name two.  I won't bore you with the details.  Just take it that these standards still live on, in part, in VGA.  SVGA is another standard Super Video Graphics Adapter, which is not so super anymore, enhanced VGA to allow for bigger resolutions and more colours on screen at once.

    contents

    A Look Inside The VGA Card

    The VGA consists of Three basic units.  These are: The video Controller, Video memory or VRAM and a Video BIOS.

    1. The Video Controller

    This part of the VGA card generates signals that are sent to the monitor, depending on the current mode.  There are various modes available to the VGA, both text and graphics.  The CPU sends instructions to the Video Controller's registers and reads status information from them to set the particular mode.  Since the VGA card has a register-level programmable graphics controller, you may create your own modes and resolutions by programming the internal registers manually, via their port numbers.

    2. Video RAM

    Video Random-Access Memory is an area of memory, which is located on-board the VGA card itself (usually), or in main memory.  This VRAM contains information that the monitor can display.  The Interrupts that handle screen displays transfer data to this memory area, although you can also send data directly to Video RAM as long as you know the address to send your data to.  For example, to plot a pixel on the screen, firstly you need to know the starting address of VRAM.  To find this out you need to know what mode the VGA is currently displaying in.  If for instance you were displaying in the graphics mode known as mode 12h, we have a 640 x 480 screen resolution.  That means that we have 307200 pixel locations on screen (memory addresses in VRAM).  With this information we can now plot a pixel on the screen.  Mode 12h has a starting address of 0xa in VRAM.  Remember that addresses in VRAM can map to a pixel location on the screen.  To plot a pixel in the first pixel location all we have to do is fill 0xa with a value, which represents a colour.  Mode 12h has 16 colours, so the value we place in 0xa will have to be a value between 0 and 15 inclusive.  The default value for 0 is Black, 15 will be White, with a selection of 14 colours in between.  Other video modes may have smaller or bigger resolutions with less or more colours, and have either text or graphics capabilities.  Video memory above 64kb is accessed by planes.  Each plane can be 64kb in size or bigger, but only 64kb can be accessed at any one time.  The value that you send to VRAM is a representation of RGB (Red,Green,Blue) intensities.  This means that every colour consists of a red, green and blue value.  If you have ever mixed paints or plasticene, you will find that different colours when mixed take on a new colour.  Well the colours in the VGA are done in the same way.  Black is 0 because no red, no green and no blue make black, wheras the highest intensity of each RGB value gives white.

    3. Video BIOS

    The Video Bios acts as an interface to the VGA card and controls routines for commanding the adapter.  For example setting the display mode and accessing the correct location in VRAM for a specific mode.

    contents

    How does the VGA and monitor make an image on screen ?

    The Video Controller converts data from Video RAM into electro-magnetic signals, which are sent to the monitor via the Bus to be interpreted.  The monitor uses these signals to render an image by creating pixels, which are drawn by an electron gun that excites phosphors on the back of the monitor screen.  The monitor draws these pixels from top to bottom, left to right.  Each time a line of pixels is drawn, the electron gun moves back to the left again and draws another line until it reaches the bottom of the screen.  When it has completed drawing the screen, it moves back up to the top left of the screen and repeats it's drawing and retracing action.  The period during which the electron gun is moving back to the left after drawing a line is called the Horizontal retrace period and the time taken to return to the top left is called the Vertical retrace period.  The Vertical retrace period usually occurs about 60 to 90 times a second depending on your monitor.  This is measured in Hz (Hertz), 60hz to 90hz.  During the two retrace periods, the VGA does not send data to the monitor, although this can be overridden, it's not a good idea to plot anything on the screen during the vertical retrace period as it will cause disruption to the image being displayed.

    contents