3
votes

I found 512 byte os contest during web surfing.

everything is fitted in bootsector.

after read some of those source files,

I found there is always cli instruction before start routine. (in assembly)

use16
org 7c00h
jmp 0:start
start:
  cli
  do something here..(this section sometimes include int 10h)

the thing I wonder is

  1. why cli is necessary before start routine.

  2. after cli, sometimes, they use interrupt! like int 10h I wonder why they use interrupt after cli would it be normal?

2
Can you show us this "do something here"? - Alexey Frunze

2 Answers

6
votes

1) The only case where cli is necessary before (or within) a boot sector's initialisation is if the boot sector might run on 8086. For later CPUs loading ss causes interrupts to be disabled (postponed) until after the next instruction, which is long enough to load sp and get a valid ss:sp for a potential IRQ handler to use.

2) Software interrupts (e.g. int 0x10) aren't IRQs and aren't disabled by cli. It's normal to do a sti soon after a cli to avoid messing up IRQs. When you're trying to squeeze something in 512 bytes it's normal to do silly things that no sane programmer would consider allowing (like leaving interrupts disabled) just to squeeze an extra byte of code in.

4
votes

cli is only necessary if we don't want hardware interrupts to be serviced at the moment.

It's hard to tell why it's used in the code you're referring to without seeing the actual code, but generally there can be multiple reasons:

  • to avoid race conditions with interrupt service routines (when accessing shared mutable data)
  • to change the interrupt vector table atomically (very similar to the above)
  • to change SS:SP atomically (very similar to the above)
  • to avoid exceptions caused by ISRs while switching CPU modes (real<->protected)
  • to measure time more precisely avoiding ISR contribution
  • etc

Basically, whenever hardware ISRs can interfere with the main code in some undesired ways, you disable interrupts.

Oh, and int 10h has nothing to do with interrupt requests coming from the hardware. It's just that some ISRs are used to handle hardware interrupts (from e.g. the keyboard or network) and others are used as various helper routines or system calls with a convenient interface (you don't need to know the exact location of the ISR, vector number (10h) suffices). The BIOS int 10h functions let you change display modes and write text on the screen.